Skip to main content

sui_render_wgpu/
lib.rs

1#![deny(unsafe_code)]
2#![allow(clippy::too_many_arguments)]
3
4mod feathering;
5mod gpu;
6mod retained;
7mod scene;
8mod text;
9
10use std::{
11    collections::{HashMap, HashSet, hash_map::Entry},
12    fmt,
13    hash::{DefaultHasher, Hash, Hasher},
14    sync::{
15        Arc, Condvar, Mutex,
16        atomic::{AtomicU64, Ordering},
17    },
18    time::Duration,
19};
20
21use bytemuck::{Pod, Zeroable};
22use half::f16;
23use lyon_path::{Path as LyonPath, builder::PathBuilder as LyonPathBuilder, math::point};
24use lyon_tessellation::{
25    BuffersBuilder, FillOptions, FillTessellator, FillVertex, FillVertexConstructor, StrokeVertex,
26    StrokeVertexConstructor, VertexBuffers,
27};
28use sui_core::{
29    Color, ColorSpace, Error, ImageHandle, Path as ScenePath, PathElement, Point, Rect, Result,
30    Size, Transform, Vector, WindowId,
31};
32pub use sui_scene::TextSubpixelOrder;
33use sui_scene::{
34    Brush, ImageSampling, RegisteredExternalImage, RegisteredImage, RegisteredImageFormat, Scene,
35    SceneCommand, SceneFrame, SceneLayer, SceneLayerId, SceneLayerUpdateKind, StrokeStyle,
36    TextRenderCoveragePolicy, TextRenderHinting, TextRenderPolicy, TextRenderStemDarkening,
37};
38use sui_text::{
39    FontRegistry, ResolvedTextFace, ShapedGlyph as SceneShapedGlyph, ShapedText, TextLayout,
40    TextLayoutCacheSnapshot, TextRun, TextStyle, TextSystem,
41};
42use swash::{
43    FontRef as SwashFontRef,
44    scale::{
45        Render as SwashRender, ScaleContext as SwashScaleContext, Source as SwashSource,
46        StrikeWith as SwashStrikeWith, image::Content as SwashImageContent,
47    },
48    zeno::Format as SwashFormat,
49};
50#[cfg(test)]
51use tiny_skia::PathBuilder as TinySkiaPathBuilder;
52use web_time::Instant;
53use wgpu::util::DeviceExt;
54use winit::window::Window;
55
56use gpu::*;
57use retained::*;
58use scene::*;
59use text::*;
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RendererCapabilities {
63    pub supports_color_management: bool,
64    pub supports_offscreen_surfaces: bool,
65}
66
67impl Default for RendererCapabilities {
68    fn default() -> Self {
69        Self {
70            supports_color_management: true,
71            supports_offscreen_surfaces: true,
72        }
73    }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub enum DisplayColorPrimaries {
78    #[default]
79    Srgb,
80    DisplayP3,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum DynamicRangeMode {
85    #[default]
86    StandardDynamicRange,
87    HighDynamicRange,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum DisplayTransferFunction {
92    #[default]
93    Srgb,
94    LinearExtended,
95    Pq,
96    Hlg,
97}
98
99#[derive(Debug, Clone, PartialEq)]
100pub struct DisplayCapabilities {
101    pub supports_wide_gamut: bool,
102    pub supports_hdr: bool,
103    pub preferred_primaries: DisplayColorPrimaries,
104    pub preferred_dynamic_range: DynamicRangeMode,
105    pub max_luminance_nits: Option<f32>,
106    pub sdr_white_nits: Option<f32>,
107    pub max_content_headroom: Option<f32>,
108    pub native_hdr_presentation_supported: bool,
109    pub notes: String,
110}
111
112impl Default for DisplayCapabilities {
113    fn default() -> Self {
114        Self {
115            supports_wide_gamut: false,
116            supports_hdr: false,
117            preferred_primaries: DisplayColorPrimaries::Srgb,
118            preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
119            max_luminance_nits: None,
120            sdr_white_nits: None,
121            max_content_headroom: None,
122            native_hdr_presentation_supported: false,
123            notes: "Default SDR capability profile".to_string(),
124        }
125    }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub enum RequestedOutputColorPrimaries {
130    #[default]
131    Automatic,
132    Srgb,
133    DisplayP3,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum RequestedDynamicRangeMode {
138    #[default]
139    Automatic,
140    StandardDynamicRange,
141    HighDynamicRange,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145pub enum RequestedColorManagementMode {
146    #[default]
147    Automatic,
148    ForceSdr,
149    PreferWideGamut,
150    PreferHdr,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154pub enum RequestedToneMappingMode {
155    #[default]
156    Automatic,
157    Clamp,
158    Reinhard,
159}
160
161pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
162const SCRGB_REFERENCE_WHITE_NITS: f32 = 80.0;
163
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub struct ColorManagementMode {
166    pub mode: RequestedColorManagementMode,
167    pub output_primaries: RequestedOutputColorPrimaries,
168    pub dynamic_range: RequestedDynamicRangeMode,
169    pub tone_mapping: RequestedToneMappingMode,
170    pub sdr_content_brightness_nits: f32,
171}
172
173impl Default for ColorManagementMode {
174    fn default() -> Self {
175        Self {
176            mode: RequestedColorManagementMode::Automatic,
177            output_primaries: RequestedOutputColorPrimaries::Automatic,
178            dynamic_range: RequestedDynamicRangeMode::Automatic,
179            tone_mapping: RequestedToneMappingMode::Automatic,
180            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
181        }
182    }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum OutputStrategy {
187    SdrSurface {
188        format: wgpu::TextureFormat,
189    },
190    WideGamutSurface {
191        format: wgpu::TextureFormat,
192        primaries: DisplayColorPrimaries,
193    },
194    HdrNativeSurface {
195        format: wgpu::TextureFormat,
196        primaries: DisplayColorPrimaries,
197        transfer: DisplayTransferFunction,
198    },
199    /// Debug/offscreen-only path for inspecting HDR scene values on SDR outputs.
200    ///
201    /// Normal presentation should choose native HDR when the environment can present
202    /// HDR end-to-end; otherwise it should render SDR instead of tone mapping HDR.
203    HdrIntermediateThenToneMap {
204        intermediate_format: wgpu::TextureFormat,
205        surface_format: wgpu::TextureFormat,
206        primaries: DisplayColorPrimaries,
207    },
208}
209
210impl OutputStrategy {
211    pub const fn surface_format(self) -> wgpu::TextureFormat {
212        match self {
213            Self::SdrSurface { format }
214            | Self::WideGamutSurface { format, .. }
215            | Self::HdrNativeSurface { format, .. } => format,
216            Self::HdrIntermediateThenToneMap { surface_format, .. } => surface_format,
217        }
218    }
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
222pub enum DebugCaptureStage {
223    HdrIntermediate,
224    #[default]
225    FinalComposed,
226}
227
228impl DebugCaptureStage {
229    pub const fn is_hdr_capable(self) -> bool {
230        matches!(self, Self::HdrIntermediate)
231    }
232
233    pub const fn uses_hdr_intermediate(self) -> bool {
234        matches!(self, Self::HdrIntermediate)
235    }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
239pub enum DebugSdrVisualization {
240    #[default]
241    ToneMappedColor,
242    LuminanceHeatmap,
243    HeadroomHeatmap,
244    ClipMask,
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
248pub enum DebugCaptureEncoding {
249    Exr,
250    #[default]
251    Png,
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
255pub struct DebugCaptureRequest {
256    pub stage: DebugCaptureStage,
257    pub encoding: DebugCaptureEncoding,
258    pub sdr_visualization: DebugSdrVisualization,
259}
260
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
262pub struct RendererInterop {
263    pub raw_wgpu_enabled: bool,
264}
265
266/// Cloneable access to the renderer-owned WGPU device and queue.
267///
268/// The handles refer to the exact device used by SUI. Applications can use
269/// them to populate textures or run conversion passes, then register the
270/// resulting sampled texture through [`WgpuExternalTextureRegistry`].
271#[derive(Debug, Clone)]
272pub struct WgpuExternalTextureContext {
273    device: wgpu::Device,
274    queue: wgpu::Queue,
275}
276
277impl WgpuExternalTextureContext {
278    pub fn device(&self) -> &wgpu::Device {
279        &self.device
280    }
281
282    pub fn queue(&self) -> &wgpu::Queue {
283        &self.queue
284    }
285}
286
287#[derive(Debug, Clone)]
288struct WgpuExternalTextureEntry {
289    texture: wgpu::Texture,
290    view: wgpu::TextureView,
291    descriptor: RegisteredExternalImage,
292    binding_revision: u64,
293    content_revision: Option<u64>,
294}
295
296#[derive(Default)]
297struct WgpuExternalTextureRegistryInner {
298    context: Mutex<Option<WgpuExternalTextureContext>>,
299    context_ready: Condvar,
300    textures: Mutex<HashMap<ImageHandle, WgpuExternalTextureEntry>>,
301    next_binding_revision: AtomicU64,
302}
303
304/// Shared registry for app-owned textures sampled by SUI's normal image draw
305/// path.
306///
307/// This contract is intentionally media-agnostic. The application owns the
308/// producer, update cadence, pixel conversion, and texture contents. SUI owns
309/// only the renderer device handoff and sampled-texture lifetime needed to
310/// compose the resource with ordinary scene transforms and clips.
311#[derive(Clone, Default)]
312pub struct WgpuExternalTextureRegistry {
313    inner: Arc<WgpuExternalTextureRegistryInner>,
314}
315
316impl fmt::Debug for WgpuExternalTextureRegistry {
317    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318        formatter
319            .debug_struct("WgpuExternalTextureRegistry")
320            .field("attached", &self.context().is_some())
321            .field("len", &self.len())
322            .finish()
323    }
324}
325
326impl WgpuExternalTextureRegistry {
327    pub fn new() -> Self {
328        Self::default()
329    }
330
331    /// Returns the renderer device once the first render target initializes.
332    pub fn context(&self) -> Option<WgpuExternalTextureContext> {
333        self.inner
334            .context
335            .lock()
336            .unwrap_or_else(|poisoned| poisoned.into_inner())
337            .clone()
338    }
339
340    /// Wait for renderer initialization without tying the registry to a
341    /// platform event-loop type.
342    pub fn wait_for_context(&self, timeout: Duration) -> Option<WgpuExternalTextureContext> {
343        let context = self
344            .inner
345            .context
346            .lock()
347            .unwrap_or_else(|poisoned| poisoned.into_inner());
348        let (context, _) = self
349            .inner
350            .context_ready
351            .wait_timeout_while(context, timeout, |context| context.is_none())
352            .unwrap_or_else(|poisoned| poisoned.into_inner());
353        context.clone()
354    }
355
356    /// Upload tightly packed sRGB RGBA8 pixels into a persistent texture.
357    /// Reusing `handle` and dimensions updates the existing allocation.
358    pub fn upload_rgba8(
359        &self,
360        handle: ImageHandle,
361        width: u32,
362        height: u32,
363        pixels: Arc<[u8]>,
364        revision: u64,
365    ) -> Result<RegisteredExternalImage> {
366        let context = self.context().ok_or_else(|| {
367            Error::new("external texture registry is not attached to an initialized renderer")
368        })?;
369        let descriptor = RegisteredExternalImage::new(width, height)?;
370        let row_bytes = width
371            .checked_mul(4)
372            .ok_or_else(|| Error::new("external RGBA8 image row size overflow"))?;
373        let expected_len = row_bytes
374            .checked_mul(height)
375            .map(|len| len as usize)
376            .ok_or_else(|| Error::new("external RGBA8 image byte size overflow"))?;
377        if pixels.len() != expected_len {
378            return Err(Error::new(format!(
379                "external RGBA8 image data length {} does not match expected size {} for a {}x{} image",
380                pixels.len(),
381                expected_len,
382                width,
383                height
384            )));
385        }
386
387        let mut textures = self
388            .inner
389            .textures
390            .lock()
391            .unwrap_or_else(|poisoned| poisoned.into_inner());
392        let reusable = textures.get_mut(&handle).filter(|entry| {
393            entry.descriptor == descriptor
394                && entry.texture.format() == wgpu::TextureFormat::Rgba8UnormSrgb
395                && entry
396                    .texture
397                    .usage()
398                    .contains(wgpu::TextureUsages::COPY_DST)
399        });
400        if let Some(entry) = reusable {
401            if entry.content_revision == Some(revision) {
402                return Ok(entry.descriptor);
403            }
404            Self::write_rgba8(&context.queue, &entry.texture, width, height, &pixels);
405            entry.content_revision = Some(revision);
406            return Ok(entry.descriptor);
407        }
408
409        let texture = context.device.create_texture(&wgpu::TextureDescriptor {
410            label: Some("SUI external RGBA8 texture"),
411            size: wgpu::Extent3d {
412                width,
413                height,
414                depth_or_array_layers: 1,
415            },
416            mip_level_count: 1,
417            sample_count: 1,
418            dimension: wgpu::TextureDimension::D2,
419            format: wgpu::TextureFormat::Rgba8UnormSrgb,
420            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
421            view_formats: &[],
422        });
423        Self::write_rgba8(&context.queue, &texture, width, height, &pixels);
424        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
425        let binding_revision = self.next_binding_revision();
426        textures.insert(
427            handle,
428            WgpuExternalTextureEntry {
429                texture,
430                view,
431                descriptor,
432                binding_revision,
433                content_revision: Some(revision),
434            },
435        );
436        Ok(descriptor)
437    }
438
439    /// Register a sampled texture created from this registry's renderer
440    /// context. This supports app-owned GPU conversion/render passes without
441    /// exposing backend-native shared-handle policy in SUI.
442    pub fn register_texture(
443        &self,
444        handle: ImageHandle,
445        texture: wgpu::Texture,
446    ) -> Result<RegisteredExternalImage> {
447        let context = self.context().ok_or_else(|| {
448            Error::new("external texture registry is not attached to an initialized renderer")
449        })?;
450        if texture.dimension() != wgpu::TextureDimension::D2
451            || texture.depth_or_array_layers() != 1
452            || texture.sample_count() != 1
453        {
454            return Err(Error::new(
455                "external texture must be a single-sampled two-dimensional texture",
456            ));
457        }
458        if !texture
459            .usage()
460            .contains(wgpu::TextureUsages::TEXTURE_BINDING)
461        {
462            return Err(Error::new(
463                "external texture must include TEXTURE_BINDING usage",
464            ));
465        }
466        if texture.format().sample_type(
467            Some(wgpu::TextureAspect::All),
468            Some(context.device.features()),
469        ) != Some(wgpu::TextureSampleType::Float { filterable: true })
470        {
471            return Err(Error::new(
472                "external texture format must support filterable float sampling",
473            ));
474        }
475
476        let descriptor = RegisteredExternalImage::new(texture.width(), texture.height())?;
477        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
478        let entry = WgpuExternalTextureEntry {
479            texture,
480            view,
481            descriptor,
482            binding_revision: self.next_binding_revision(),
483            content_revision: None,
484        };
485        self.inner
486            .textures
487            .lock()
488            .unwrap_or_else(|poisoned| poisoned.into_inner())
489            .insert(handle, entry);
490        Ok(descriptor)
491    }
492
493    pub fn unregister(&self, handle: ImageHandle) -> bool {
494        self.inner
495            .textures
496            .lock()
497            .unwrap_or_else(|poisoned| poisoned.into_inner())
498            .remove(&handle)
499            .is_some()
500    }
501
502    pub fn contains(&self, handle: ImageHandle) -> bool {
503        self.inner
504            .textures
505            .lock()
506            .unwrap_or_else(|poisoned| poisoned.into_inner())
507            .contains_key(&handle)
508    }
509
510    pub fn len(&self) -> usize {
511        self.inner
512            .textures
513            .lock()
514            .unwrap_or_else(|poisoned| poisoned.into_inner())
515            .len()
516    }
517
518    pub fn is_empty(&self) -> bool {
519        self.len() == 0
520    }
521
522    fn attach(&self, device: wgpu::Device, queue: wgpu::Queue) {
523        let mut context = self
524            .inner
525            .context
526            .lock()
527            .unwrap_or_else(|poisoned| poisoned.into_inner());
528        if context.is_none() {
529            *context = Some(WgpuExternalTextureContext { device, queue });
530            self.inner.context_ready.notify_all();
531        }
532    }
533
534    fn resolve(&self, handle: ImageHandle) -> Option<WgpuExternalTextureEntry> {
535        self.inner
536            .textures
537            .lock()
538            .unwrap_or_else(|poisoned| poisoned.into_inner())
539            .get(&handle)
540            .cloned()
541    }
542
543    fn next_binding_revision(&self) -> u64 {
544        self.inner
545            .next_binding_revision
546            .fetch_add(1, Ordering::Relaxed)
547            .wrapping_add(1)
548    }
549
550    fn write_rgba8(
551        queue: &wgpu::Queue,
552        texture: &wgpu::Texture,
553        width: u32,
554        height: u32,
555        pixels: &[u8],
556    ) {
557        queue.write_texture(
558            wgpu::TexelCopyTextureInfo {
559                texture,
560                mip_level: 0,
561                origin: wgpu::Origin3d::ZERO,
562                aspect: wgpu::TextureAspect::All,
563            },
564            pixels,
565            wgpu::TexelCopyBufferLayout {
566                offset: 0,
567                bytes_per_row: Some(width * 4),
568                rows_per_image: Some(height),
569            },
570            wgpu::Extent3d {
571                width,
572                height,
573                depth_or_array_layers: 1,
574            },
575        );
576    }
577}
578
579#[derive(Debug, Clone, Copy, PartialEq)]
580pub struct FeatheringOptions {
581    pub enabled: bool,
582    pub width: f32,
583}
584
585impl FeatheringOptions {
586    pub const fn new(enabled: bool, width: f32) -> Self {
587        Self { enabled, width }
588    }
589
590    pub fn clamped(self) -> Self {
591        Self {
592            enabled: self.enabled,
593            width: self.width.max(0.0),
594        }
595    }
596
597    pub fn effective_width(self) -> f32 {
598        if self.enabled {
599            self.width.max(0.0)
600        } else {
601            0.0
602        }
603    }
604}
605
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
607pub enum TextRenderMode {
608    #[default]
609    Grayscale,
610    LcdSubpixel,
611}
612
613#[derive(Debug, Clone, Copy, PartialEq)]
614pub enum TextHinting {
615    None,
616    Slight { max_ppem: f32 },
617}
618
619const DEFAULT_TEXT_HINTING_MAX_PPEM: f32 = 96.0;
620
621impl Default for TextHinting {
622    fn default() -> Self {
623        Self::Slight {
624            max_ppem: DEFAULT_TEXT_HINTING_MAX_PPEM,
625        }
626    }
627}
628
629impl TextHinting {
630    pub fn normalized(self) -> Self {
631        match self {
632            Self::None => Self::None,
633            Self::Slight { max_ppem } if max_ppem.is_finite() && max_ppem > 0.0 => {
634                Self::Slight { max_ppem }
635            }
636            Self::Slight { .. } => Self::None,
637        }
638    }
639
640    pub fn should_hint(self, ppem: f32) -> bool {
641        match self.normalized() {
642            Self::None => false,
643            Self::Slight { max_ppem } => ppem.is_finite() && ppem <= max_ppem,
644        }
645    }
646}
647
648#[derive(Debug, Clone, Copy, PartialEq, Default)]
649pub enum StemDarkening {
650    #[default]
651    None,
652    Enabled {
653        max_ppem: f32,
654        amount: f32,
655    },
656}
657
658impl StemDarkening {
659    pub fn normalized(self) -> Self {
660        match self {
661            Self::None => Self::None,
662            Self::Enabled { max_ppem, amount }
663                if max_ppem.is_finite() && max_ppem > 0.0 && amount.is_finite() && amount > 0.0 =>
664            {
665                Self::Enabled {
666                    max_ppem,
667                    amount: amount.clamp(0.0, 1.0),
668                }
669            }
670            Self::Enabled { .. } => Self::None,
671        }
672    }
673
674    pub fn effective_amount(self, ppem: f32) -> f32 {
675        match self.normalized() {
676            Self::None => 0.0,
677            Self::Enabled { max_ppem, amount } if ppem.is_finite() && ppem <= max_ppem => amount,
678            Self::Enabled { .. } => 0.0,
679        }
680    }
681}
682
683#[derive(Debug, Clone, Copy, PartialEq, Default)]
684pub enum TextCoveragePolicy {
685    #[default]
686    Perceptual,
687    Linear,
688    Gamma(f32),
689    CoverageBoost(f32),
690    TwoCoverageMinusCoverageSq,
691}
692
693impl TextCoveragePolicy {
694    pub fn normalized(self) -> Self {
695        match self {
696            Self::Perceptual => Self::Perceptual,
697            Self::Linear => Self::Linear,
698            Self::Gamma(gamma) if gamma.is_finite() && gamma > 0.0 => Self::Gamma(gamma),
699            Self::Gamma(_) => Self::Linear,
700            Self::CoverageBoost(amount) if amount.is_finite() && amount > 0.0 => {
701                Self::CoverageBoost(amount.clamp(0.0, 1.0))
702            }
703            Self::CoverageBoost(_) => Self::Linear,
704            Self::TwoCoverageMinusCoverageSq => Self::TwoCoverageMinusCoverageSq,
705        }
706    }
707
708    pub fn resolved_for_text_color(self, color: Color) -> Self {
709        match self.normalized() {
710            Self::Perceptual => Self::CoverageBoost(perceptual_text_coverage_boost(color)),
711            policy => policy,
712        }
713    }
714
715    pub fn apply(self, coverage: f32) -> f32 {
716        let coverage = coverage.clamp(0.0, 1.0);
717        match self.normalized() {
718            Self::Perceptual => {
719                apply_coverage_boost(coverage, perceptual_text_coverage_boost(Color::BLACK))
720            }
721            Self::Linear => coverage,
722            Self::Gamma(gamma) => coverage.powf(gamma),
723            Self::CoverageBoost(amount) => apply_coverage_boost(coverage, amount),
724            Self::TwoCoverageMinusCoverageSq => (2.0 * coverage) - (coverage * coverage),
725        }
726    }
727}
728
729fn perceptual_text_coverage_boost(color: Color) -> f32 {
730    let luminance = encoded_srgb_luminance(color);
731    (1.0 - luminance).clamp(0.45, 0.92)
732}
733
734fn apply_coverage_boost(coverage: f32, amount: f32) -> f32 {
735    coverage + (coverage * (1.0 - coverage) * amount.clamp(0.0, 1.0))
736}
737
738fn encoded_srgb_luminance(color: Color) -> f32 {
739    let linear = color.to_linear_srgb();
740    let red = linear_srgb_to_encoded_unit(linear.red);
741    let green = linear_srgb_to_encoded_unit(linear.green);
742    let blue = linear_srgb_to_encoded_unit(linear.blue);
743    ((0.2126 * red) + (0.7152 * green) + (0.0722 * blue)).clamp(0.0, 1.0)
744}
745
746fn linear_srgb_to_encoded_unit(channel: f32) -> f32 {
747    let value = channel.clamp(0.0, 1.0);
748    if value <= 0.003_130_8 {
749        value * 12.92
750    } else {
751        (1.055 * value.powf(1.0 / 2.4)) - 0.055
752    }
753}
754
755#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
756pub struct GlyphCacheSnapshot {
757    pub entries: usize,
758    pub hits: usize,
759    pub misses: usize,
760}
761
762impl GlyphCacheSnapshot {
763    pub const fn requests(self) -> usize {
764        self.hits + self.misses
765    }
766
767    pub fn hit_rate(self) -> f64 {
768        let requests = self.requests();
769        if requests == 0 {
770            0.0
771        } else {
772            self.hits as f64 / requests as f64
773        }
774    }
775}
776
777#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
778pub struct RendererTextCacheSnapshot {
779    pub layout: TextLayoutCacheSnapshot,
780    pub glyph: GlyphCacheSnapshot,
781    pub path: GlyphCacheSnapshot,
782}
783
784#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
785struct TextFrameStats {
786    glyph_instances: usize,
787    glyph_upload_bytes: u64,
788    atlas_miss_count: usize,
789    atlas_miss_time_us: u64,
790}
791
792const TEXT_ATLAS_WIDTH: usize = 2048;
793const TEXT_ATLAS_HEIGHT: usize = 2048;
794const TEXT_ATLAS_PADDING: usize = 2;
795/// Maximum number of atlas pages (texture-array layers) before whole-page LRU eviction kicks in.
796/// Each page is TEXT_ATLAS_WIDTH x TEXT_ATLAS_HEIGHT x 4 bytes (~16 MB); 4 pages -> ~64 MB.
797const TEXT_ATLAS_MAX_PAGES: usize = 4;
798
799#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
800pub struct RetainedPacketRebuildStats {
801    pub new_count: usize,
802    pub coordinate_space_count: usize,
803    pub signature_count: usize,
804    pub scene_count: usize,
805    pub state_count: usize,
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809enum PacketRebuildReason {
810    NewPacket,
811    CoordinateSpace,
812    Signature,
813    Scene,
814    State,
815}
816
817impl RetainedPacketRebuildStats {
818    pub const fn new(
819        new_count: usize,
820        coordinate_space_count: usize,
821        signature_count: usize,
822        scene_count: usize,
823        state_count: usize,
824    ) -> Self {
825        Self {
826            new_count,
827            coordinate_space_count,
828            signature_count,
829            scene_count,
830            state_count,
831        }
832    }
833
834    fn record_reason(&mut self, reason: PacketRebuildReason) {
835        match reason {
836            PacketRebuildReason::NewPacket => self.new_count += 1,
837            PacketRebuildReason::CoordinateSpace => self.coordinate_space_count += 1,
838            PacketRebuildReason::Signature => self.signature_count += 1,
839            PacketRebuildReason::Scene => self.scene_count += 1,
840            PacketRebuildReason::State => self.state_count += 1,
841        }
842    }
843
844    pub const fn total_count(&self) -> usize {
845        self.new_count
846            + self.coordinate_space_count
847            + self.signature_count
848            + self.scene_count
849            + self.state_count
850    }
851}
852
853#[derive(Debug, Clone, PartialEq, Eq, Default)]
854pub struct RendererFrameStats {
855    pub pass_count: usize,
856    pub draw_count: usize,
857    pub uploaded_vertex_bytes: u64,
858    pub text_glyph_instance_count: usize,
859    pub text_vertex_bytes: u64,
860    pub visible_layer_count: usize,
861    pub direct_packet_count: usize,
862    pub retained_state_update_time_us: u64,
863    pub composition_time_us: u64,
864    pub retained_scene_traversal_time_us: u64,
865    pub retained_packet_build_time_us: u64,
866    pub retained_packet_build_count: usize,
867    pub retained_packet_rebuilds: RetainedPacketRebuildStats,
868    pub retained_packet_normalize_time_us: u64,
869    pub retained_packet_signature_time_us: u64,
870    pub retained_packet_raster_state_init_time_us: u64,
871    pub retained_packet_scene_build_time_us: u64,
872    pub retained_packet_command_count: usize,
873    pub retained_packet_text_command_count: usize,
874    pub retained_packet_path_command_count: usize,
875    pub retained_packet_clip_path_command_count: usize,
876    pub retained_packet_image_command_count: usize,
877    pub retained_packet_rect_command_count: usize,
878    pub retained_packet_text_command_time_us: u64,
879    pub retained_packet_path_command_time_us: u64,
880    pub retained_packet_clip_path_command_time_us: u64,
881    pub retained_packet_image_command_time_us: u64,
882    pub retained_packet_rect_command_time_us: u64,
883    pub text_atlas_miss_count: usize,
884    pub text_atlas_miss_time_us: u64,
885    pub surface_acquire_time_us: u64,
886    pub resource_collection_time_us: u64,
887    pub bind_group_prepare_time_us: u64,
888    pub image_bind_group_time_us: u64,
889    pub analytic_path_bind_group_time_us: u64,
890    pub analytic_path_bind_group_miss_count: usize,
891    pub analytic_path_bind_group_upload_bytes: u64,
892    pub text_atlas_bind_group_time_us: u64,
893    pub text_atlas_upload_copy_time_us: u64,
894    pub text_atlas_upload_write_time_us: u64,
895    pub text_atlas_upload_bytes: u64,
896    pub batch_prepare_time_us: u64,
897    pub gpu_upload_time_us: u64,
898    pub pass_encode_time_us: u64,
899    pub queue_submit_time_us: u64,
900    pub surface_present_time_us: u64,
901    pub retained_packet_hotspot: Option<RendererPacketHotspot>,
902}
903
904#[derive(Debug, Clone, PartialEq, Eq)]
905pub struct RendererPacketHotspot {
906    pub container_layer_id: Option<u64>,
907    pub owner_widget_id: Option<u64>,
908    pub segment_index: u32,
909    pub total_time_us: u64,
910    pub scene_build_time_us: u64,
911    pub command_count: usize,
912    pub text_command_count: usize,
913    pub path_command_count: usize,
914    pub rect_command_count: usize,
915    pub text_command_time_us: u64,
916    pub path_command_time_us: u64,
917    pub rect_command_time_us: u64,
918    pub text_sample: Option<String>,
919}
920
921impl RendererFrameStats {
922    #[cfg(test)]
923    fn from_prepared_frame(prepared: &PreparedFrameBatches) -> Self {
924        Self::from_prepared_counts(
925            prepared.passes.len().max(1),
926            prepared
927                .passes
928                .iter()
929                .map(|pass| pass.clip_paths.len() + pass.draws.len())
930                .sum(),
931            (prepared.scene_vertices.len() as u64 + prepared.clip_vertices.len() as u64)
932                * VERTEX_SIZE
933                + prepared.text_instances.len() as u64 * TEXT_ATLAS_INSTANCE_SIZE,
934        )
935    }
936
937    fn from_prepared_counts(
938        pass_count: usize,
939        draw_count: usize,
940        uploaded_vertex_bytes: u64,
941    ) -> Self {
942        Self {
943            pass_count,
944            draw_count,
945            uploaded_vertex_bytes,
946            text_glyph_instance_count: 0,
947            text_vertex_bytes: 0,
948            visible_layer_count: 0,
949            direct_packet_count: 0,
950            retained_state_update_time_us: 0,
951            composition_time_us: 0,
952            retained_scene_traversal_time_us: 0,
953            retained_packet_build_time_us: 0,
954            retained_packet_build_count: 0,
955            retained_packet_rebuilds: RetainedPacketRebuildStats::default(),
956            retained_packet_normalize_time_us: 0,
957            retained_packet_signature_time_us: 0,
958            retained_packet_raster_state_init_time_us: 0,
959            retained_packet_scene_build_time_us: 0,
960            retained_packet_command_count: 0,
961            retained_packet_text_command_count: 0,
962            retained_packet_path_command_count: 0,
963            retained_packet_clip_path_command_count: 0,
964            retained_packet_image_command_count: 0,
965            retained_packet_rect_command_count: 0,
966            retained_packet_text_command_time_us: 0,
967            retained_packet_path_command_time_us: 0,
968            retained_packet_clip_path_command_time_us: 0,
969            retained_packet_image_command_time_us: 0,
970            retained_packet_rect_command_time_us: 0,
971            text_atlas_miss_count: 0,
972            text_atlas_miss_time_us: 0,
973            surface_acquire_time_us: 0,
974            resource_collection_time_us: 0,
975            bind_group_prepare_time_us: 0,
976            image_bind_group_time_us: 0,
977            analytic_path_bind_group_time_us: 0,
978            analytic_path_bind_group_miss_count: 0,
979            analytic_path_bind_group_upload_bytes: 0,
980            text_atlas_bind_group_time_us: 0,
981            text_atlas_upload_copy_time_us: 0,
982            text_atlas_upload_write_time_us: 0,
983            text_atlas_upload_bytes: 0,
984            batch_prepare_time_us: 0,
985            gpu_upload_time_us: 0,
986            pass_encode_time_us: 0,
987            queue_submit_time_us: 0,
988            surface_present_time_us: 0,
989            retained_packet_hotspot: None,
990        }
991    }
992
993    fn with_compositor_stats(mut self, stats: RetainedCompositorFrameStats) -> Self {
994        self.visible_layer_count = stats.visible_layers;
995        self.direct_packet_count = stats.direct_packets;
996        self.retained_state_update_time_us = (stats.state_update_time_ms * 1000.0).round() as u64;
997        self.composition_time_us = (stats.composition_time_ms * 1000.0).round() as u64;
998        self.retained_scene_traversal_time_us =
999            (stats.scene_traversal_time_ms * 1000.0).round() as u64;
1000        self.retained_packet_build_time_us = (stats.packet_build_time_ms * 1000.0).round() as u64;
1001        self.retained_packet_build_count = stats.packet_build_count;
1002        self.retained_packet_rebuilds = stats.packet_rebuilds;
1003        self.retained_packet_normalize_time_us =
1004            (stats.packet_normalize_time_ms * 1000.0).round() as u64;
1005        self.retained_packet_signature_time_us =
1006            (stats.packet_signature_time_ms * 1000.0).round() as u64;
1007        self.retained_packet_raster_state_init_time_us =
1008            (stats.packet_raster_state_init_time_ms * 1000.0).round() as u64;
1009        self.retained_packet_scene_build_time_us =
1010            (stats.packet_scene_build_time_ms * 1000.0).round() as u64;
1011        self.retained_packet_command_count = stats.packet_command_count;
1012        self.retained_packet_text_command_count = stats.packet_text_command_count;
1013        self.retained_packet_path_command_count = stats.packet_path_command_count;
1014        self.retained_packet_clip_path_command_count = stats.packet_clip_path_command_count;
1015        self.retained_packet_image_command_count = stats.packet_image_command_count;
1016        self.retained_packet_rect_command_count = stats.packet_rect_command_count;
1017        self.retained_packet_text_command_time_us =
1018            (stats.packet_text_command_time_ms * 1000.0).round() as u64;
1019        self.retained_packet_path_command_time_us =
1020            (stats.packet_path_command_time_ms * 1000.0).round() as u64;
1021        self.retained_packet_clip_path_command_time_us =
1022            (stats.packet_clip_path_command_time_ms * 1000.0).round() as u64;
1023        self.retained_packet_image_command_time_us =
1024            (stats.packet_image_command_time_ms * 1000.0).round() as u64;
1025        self.retained_packet_rect_command_time_us =
1026            (stats.packet_rect_command_time_ms * 1000.0).round() as u64;
1027        self.retained_packet_hotspot =
1028            stats
1029                .slowest_packet_build
1030                .map(|hotspot| RendererPacketHotspot {
1031                    container_layer_id: hotspot.container_layer_id,
1032                    owner_widget_id: hotspot.owner_widget_id,
1033                    segment_index: hotspot.segment_index,
1034                    total_time_us: (hotspot.total_time_ms * 1000.0).round() as u64,
1035                    scene_build_time_us: (hotspot.scene_build_time_ms * 1000.0).round() as u64,
1036                    command_count: hotspot.command_count,
1037                    text_command_count: hotspot.text_command_count,
1038                    path_command_count: hotspot.path_command_count,
1039                    rect_command_count: hotspot.rect_command_count,
1040                    text_command_time_us: (hotspot.text_command_time_ms * 1000.0).round() as u64,
1041                    path_command_time_us: (hotspot.path_command_time_ms * 1000.0).round() as u64,
1042                    rect_command_time_us: (hotspot.rect_command_time_ms * 1000.0).round() as u64,
1043                    text_sample: hotspot.text_sample,
1044                });
1045        self
1046    }
1047
1048    fn with_text_stats(mut self, stats: TextFrameStats) -> Self {
1049        self.text_glyph_instance_count = stats.glyph_instances;
1050        self.text_vertex_bytes = stats.glyph_upload_bytes;
1051        self.text_atlas_miss_count = stats.atlas_miss_count;
1052        self.text_atlas_miss_time_us = stats.atlas_miss_time_us;
1053        self
1054    }
1055}
1056
1057pub struct WgpuRenderer {
1058    instance: wgpu::Instance,
1059    feathering_enabled: bool,
1060    feather_width: f32,
1061    text_render_mode: TextRenderMode,
1062    text_subpixel_order: TextSubpixelOrder,
1063    text_hinting: TextHinting,
1064    stem_darkening: StemDarkening,
1065    text_coverage_policy: TextCoveragePolicy,
1066    vsync_enabled: bool,
1067    runtime_feathering_override: Option<FeatheringOptions>,
1068    runtime_text_subpixel_order_override: Option<TextSubpixelOrder>,
1069    runtime_text_hinting_override: Option<TextHinting>,
1070    runtime_stem_darkening_override: Option<StemDarkening>,
1071    runtime_text_coverage_policy_override: Option<TextCoveragePolicy>,
1072    runtime_diagnostics_enabled: bool,
1073    frames_rendered: usize,
1074    capabilities: RendererCapabilities,
1075    last_frames: HashMap<WindowId, SceneFrame>,
1076    last_frame_stats: HashMap<WindowId, RendererFrameStats>,
1077    shared: Option<SharedRenderer>,
1078    text_engine: Option<TextEngine>,
1079    image_cache: HashMap<ImageHandle, CachedImageTexture>,
1080    external_texture_registry: Option<WgpuExternalTextureRegistry>,
1081    external_image_cache: HashMap<ImageHandle, CachedExternalTextureBindGroup>,
1082    text_atlas_array: Option<CachedTextAtlasTexture>,
1083    analytic_path_cache: HashMap<u64, CachedAnalyticPathGpu>,
1084    compositors: HashMap<WindowId, RetainedCompositorState>,
1085    surfaces: HashMap<WindowId, SurfaceState>,
1086    offscreen_targets: HashMap<WindowId, OffscreenTarget>,
1087    intermediate_targets: HashMap<WindowId, OffscreenTarget>,
1088    frame_resources: FrameResources,
1089}
1090
1091#[derive(Default)]
1092struct FrameResources {
1093    stencil: Option<StencilTarget>,
1094    analytic_path_arena: AnalyticPathArena,
1095}
1096
1097#[derive(Default)]
1098struct AnalyticPathArena {
1099    bind_group: Option<wgpu::BindGroup>,
1100    meta_buffer: Option<wgpu::Buffer>,
1101    contour_buffer: Option<wgpu::Buffer>,
1102    point_buffer: Option<wgpu::Buffer>,
1103    meta_capacity: usize,
1104    contour_capacity: usize,
1105    point_capacity: usize,
1106    used_slots: usize,
1107    used_contours: usize,
1108    used_points: usize,
1109}
1110
1111struct StencilTarget {
1112    texture: wgpu::Texture,
1113    view: wgpu::TextureView,
1114    size: (u32, u32),
1115}
1116
1117#[derive(Debug, Clone, PartialEq, Eq)]
1118pub struct RgbaImage {
1119    width: u32,
1120    height: u32,
1121    pixels: Vec<u8>,
1122}
1123
1124#[derive(Debug, Clone, PartialEq)]
1125pub struct HdrRgbaImage {
1126    width: u32,
1127    height: u32,
1128    pixels: Vec<f32>,
1129}
1130
1131#[derive(Debug, Clone, PartialEq)]
1132pub enum DebugCaptureArtifact {
1133    SdrRgba8(RgbaImage),
1134    HdrLinearRgbaF32(HdrRgbaImage),
1135}
1136
1137#[repr(C)]
1138#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
1139struct OutputTransformUniform {
1140    tone_mapping_mode: u32,
1141    encode_srgb: u32,
1142    output_primaries: u32,
1143    _padding0: u32,
1144    sdr_content_scale: f32,
1145    _padding1: [u32; 3],
1146}
1147
1148impl OutputTransformUniform {
1149    const fn new(
1150        tone_mapping_mode: u32,
1151        encode_srgb: bool,
1152        output_primaries: DisplayColorPrimaries,
1153        sdr_content_scale: f32,
1154    ) -> Self {
1155        Self {
1156            tone_mapping_mode,
1157            encode_srgb: encode_srgb as u32,
1158            output_primaries: match output_primaries {
1159                DisplayColorPrimaries::Srgb => 0,
1160                DisplayColorPrimaries::DisplayP3 => 1,
1161            },
1162            _padding0: 0,
1163            sdr_content_scale,
1164            _padding1: [0; 3],
1165        }
1166    }
1167}
1168
1169impl RgbaImage {
1170    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
1171        let expected_len = width as usize * height as usize * 4;
1172        if pixels.len() != expected_len {
1173            return Err(Error::new(format!(
1174                "RGBA image pixel buffer length {} does not match {}x{} image size",
1175                pixels.len(),
1176                width,
1177                height
1178            )));
1179        }
1180
1181        Ok(Self {
1182            width,
1183            height,
1184            pixels,
1185        })
1186    }
1187
1188    pub const fn width(&self) -> u32 {
1189        self.width
1190    }
1191
1192    pub const fn height(&self) -> u32 {
1193        self.height
1194    }
1195
1196    pub fn pixels(&self) -> &[u8] {
1197        &self.pixels
1198    }
1199
1200    pub fn into_pixels(self) -> Vec<u8> {
1201        self.pixels
1202    }
1203}
1204
1205impl HdrRgbaImage {
1206    pub fn new(width: u32, height: u32, pixels: Vec<f32>) -> Result<Self> {
1207        let expected_len = width as usize * height as usize * 4;
1208        if pixels.len() != expected_len {
1209            return Err(Error::new(format!(
1210                "HDR RGBA image pixel buffer length {} does not match {}x{} image size",
1211                pixels.len(),
1212                width,
1213                height
1214            )));
1215        }
1216
1217        Ok(Self {
1218            width,
1219            height,
1220            pixels,
1221        })
1222    }
1223
1224    pub const fn width(&self) -> u32 {
1225        self.width
1226    }
1227
1228    pub const fn height(&self) -> u32 {
1229        self.height
1230    }
1231
1232    pub fn pixels(&self) -> &[f32] {
1233        &self.pixels
1234    }
1235
1236    pub fn into_pixels(self) -> Vec<f32> {
1237        self.pixels
1238    }
1239}
1240
1241const STENCIL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
1242const DEFAULT_FEATHER_WIDTH: f32 = 0.0;
1243
1244/// Bind group layout for the multi-page glyph atlas: a filtering sampler plus a
1245/// `texture_2d_array` (one layer per atlas page). Distinct from the image layout, which is `D2`.
1246fn create_text_atlas_array_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
1247    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1248        label: Some("SUI text atlas array bind group layout"),
1249        entries: &[
1250            wgpu::BindGroupLayoutEntry {
1251                binding: 0,
1252                visibility: wgpu::ShaderStages::FRAGMENT,
1253                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1254                count: None,
1255            },
1256            wgpu::BindGroupLayoutEntry {
1257                binding: 1,
1258                visibility: wgpu::ShaderStages::FRAGMENT,
1259                ty: wgpu::BindingType::Texture {
1260                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
1261                    view_dimension: wgpu::TextureViewDimension::D2Array,
1262                    multisampled: false,
1263                },
1264                count: None,
1265            },
1266        ],
1267    })
1268}
1269
1270fn strip_padded_readback_rows(
1271    mapped: &[u8],
1272    bytes_per_row: usize,
1273    padded_bytes_per_row: usize,
1274    rows: usize,
1275) -> Vec<u8> {
1276    let mut tightly_packed = Vec::with_capacity(bytes_per_row * rows);
1277    for row in 0..rows {
1278        let start = row * padded_bytes_per_row;
1279        tightly_packed.extend_from_slice(&mapped[start..start + bytes_per_row]);
1280    }
1281    tightly_packed
1282}
1283
1284fn decode_rgba16f_pixels(raw: &[u8]) -> Vec<f32> {
1285    let mut pixels = Vec::with_capacity(raw.len() / 2);
1286    for chunk in raw.chunks_exact(2) {
1287        pixels.push(f16::from_bits(u16::from_le_bytes([chunk[0], chunk[1]])).to_f32());
1288    }
1289    pixels
1290}
1291
1292fn hdr_image_to_sdr_rgba(
1293    image: &HdrRgbaImage,
1294    visualization: DebugSdrVisualization,
1295    reference_white: f32,
1296    output_primaries: DisplayColorPrimaries,
1297) -> Result<RgbaImage> {
1298    let reference_white = if reference_white.is_finite() && reference_white > 0.0 {
1299        reference_white
1300    } else {
1301        1.0
1302    };
1303    let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
1304    for rgba in image.pixels().chunks_exact(4) {
1305        let normalized = linear_output_primaries_to_srgb(
1306            [
1307                rgba[0] / reference_white,
1308                rgba[1] / reference_white,
1309                rgba[2] / reference_white,
1310            ],
1311            output_primaries,
1312        );
1313        match visualization {
1314            DebugSdrVisualization::ToneMappedColor => {
1315                // Native HDR final targets store SDR white above 1.0. Divide that
1316                // headroom back out, convert the output primaries to linear sRGB,
1317                // then clamp during sRGB encoding. SDR-authored sRGB colors round
1318                // back to their original PNG bytes; HDR values overflow to white.
1319                pixels.extend_from_slice(&[
1320                    linear_to_srgb_capture_u8(normalized[0]),
1321                    linear_to_srgb_capture_u8(normalized[1]),
1322                    linear_to_srgb_capture_u8(normalized[2]),
1323                    linear_alpha_to_capture_u8(rgba[3]),
1324                ]);
1325            }
1326            DebugSdrVisualization::LuminanceHeatmap => {
1327                let luminance =
1328                    (normalized[0] * 0.2126 + normalized[1] * 0.7152 + normalized[2] * 0.0722)
1329                        .max(0.0);
1330                let normalized = (luminance / (1.0 + luminance)).clamp(0.0, 1.0);
1331                let value = (normalized * 255.0).round() as u8;
1332                pixels.extend_from_slice(&[value, value, value, 255]);
1333            }
1334            DebugSdrVisualization::HeadroomHeatmap => {
1335                let headroom = normalized[0].max(normalized[1]).max(normalized[2]).max(0.0);
1336                let normalized = (headroom / (1.0 + headroom)).clamp(0.0, 1.0);
1337                let red = (normalized * 255.0).round() as u8;
1338                let blue = ((1.0 - normalized) * 96.0).round() as u8;
1339                pixels.extend_from_slice(&[red, 32, blue, 255]);
1340            }
1341            DebugSdrVisualization::ClipMask => {
1342                let clipped = normalized[0].max(normalized[1]).max(normalized[2]) > 1.0;
1343                if clipped {
1344                    pixels.extend_from_slice(&[255, 64, 64, 255]);
1345                } else {
1346                    pixels.extend_from_slice(&[0, 0, 0, 255]);
1347                }
1348            }
1349        }
1350    }
1351    RgbaImage::new(image.width(), image.height(), pixels)
1352}
1353
1354fn linear_output_primaries_to_srgb(
1355    color: [f32; 3],
1356    output_primaries: DisplayColorPrimaries,
1357) -> [f32; 3] {
1358    match output_primaries {
1359        DisplayColorPrimaries::Srgb => color,
1360        DisplayColorPrimaries::DisplayP3 => {
1361            let det = (0.822_461_96 * 0.966_805_76) - (0.177_538_02 * 0.033_194_2);
1362            let red = (0.966_805_76 * color[0] - 0.177_538_02 * color[1]) / det;
1363            let green = (-0.033_194_2 * color[0] + 0.822_461_96 * color[1]) / det;
1364            let blue = (color[2] - (0.017_082_63 * red) - (0.072_397_43 * green)) / 0.910_519_96;
1365            [red, green, blue]
1366        }
1367    }
1368}
1369
1370fn encode_hdr_debug_artifact(
1371    image: HdrRgbaImage,
1372    request: DebugCaptureRequest,
1373    sdr_reference_white: f32,
1374    output_primaries: DisplayColorPrimaries,
1375) -> Result<DebugCaptureArtifact> {
1376    match request.encoding {
1377        DebugCaptureEncoding::Exr => Ok(DebugCaptureArtifact::HdrLinearRgbaF32(image)),
1378        DebugCaptureEncoding::Png => hdr_image_to_sdr_rgba(
1379            &image,
1380            request.sdr_visualization,
1381            sdr_reference_white,
1382            output_primaries,
1383        )
1384        .map(DebugCaptureArtifact::SdrRgba8),
1385    }
1386}
1387
1388fn linear_to_srgb_capture_u8(channel: f32) -> u8 {
1389    let value = channel.clamp(0.0, 1.0);
1390    let encoded = if value <= 0.003_130_8 {
1391        value * 12.92
1392    } else {
1393        (1.055 * value.powf(1.0 / 2.4)) - 0.055
1394    };
1395    (encoded.clamp(0.0, 1.0) * 255.0).round() as u8
1396}
1397
1398fn linear_alpha_to_capture_u8(alpha: f32) -> u8 {
1399    (alpha.clamp(0.0, 1.0) * 255.0).round() as u8
1400}
1401
1402fn optional_renderer_features(adapter: &wgpu::Adapter) -> wgpu::Features {
1403    let mut features = wgpu::Features::empty();
1404    if adapter
1405        .features()
1406        .contains(wgpu::Features::DUAL_SOURCE_BLENDING)
1407    {
1408        features |= wgpu::Features::DUAL_SOURCE_BLENDING;
1409    }
1410    features
1411}
1412
1413impl WgpuRenderer {
1414    pub fn new() -> Self {
1415        Self::default()
1416    }
1417
1418    pub fn with_feathering(mut self, feathering: FeatheringOptions) -> Self {
1419        self.set_feathering(feathering);
1420        self
1421    }
1422
1423    pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
1424        self.set_feathering_enabled(enabled);
1425        self
1426    }
1427
1428    pub fn with_text_coverage_policy(mut self, policy: TextCoveragePolicy) -> Self {
1429        self.set_text_coverage_policy(policy);
1430        self
1431    }
1432
1433    pub fn with_text_render_mode(mut self, mode: TextRenderMode) -> Self {
1434        self.set_text_render_mode(mode);
1435        self
1436    }
1437
1438    pub fn with_text_subpixel_order(mut self, order: TextSubpixelOrder) -> Self {
1439        self.set_text_subpixel_order(order);
1440        self
1441    }
1442
1443    pub fn with_text_hinting(mut self, hinting: TextHinting) -> Self {
1444        self.set_text_hinting(hinting);
1445        self
1446    }
1447
1448    pub fn with_stem_darkening(mut self, darkening: StemDarkening) -> Self {
1449        self.set_stem_darkening(darkening);
1450        self
1451    }
1452
1453    pub fn with_feather_width(mut self, feather_width: f32) -> Self {
1454        self.set_feather_width(feather_width);
1455        self
1456    }
1457
1458    pub fn with_vsync_enabled(mut self, enabled: bool) -> Self {
1459        self.set_vsync_enabled(enabled);
1460        self
1461    }
1462
1463    pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
1464        self.set_external_texture_registry(registry);
1465        self
1466    }
1467
1468    pub fn feathering(&self) -> FeatheringOptions {
1469        FeatheringOptions::new(self.feathering_enabled, self.feather_width)
1470    }
1471
1472    pub fn feathering_enabled(&self) -> bool {
1473        self.feathering_enabled
1474    }
1475
1476    pub fn feather_width(&self) -> f32 {
1477        self.feather_width
1478    }
1479
1480    pub fn vsync_enabled(&self) -> bool {
1481        self.vsync_enabled
1482    }
1483
1484    pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
1485        self.external_texture_registry.as_ref()
1486    }
1487
1488    pub fn set_external_texture_registry(&mut self, registry: WgpuExternalTextureRegistry) {
1489        if let Some(shared) = &self.shared {
1490            registry.attach(shared.device.clone(), shared.queue.clone());
1491        }
1492        self.external_texture_registry = Some(registry);
1493        self.external_image_cache.clear();
1494    }
1495
1496    pub fn text_coverage_policy(&self) -> TextCoveragePolicy {
1497        self.text_coverage_policy
1498    }
1499
1500    pub fn text_render_mode(&self) -> TextRenderMode {
1501        self.text_render_mode
1502    }
1503
1504    pub fn text_subpixel_order(&self) -> TextSubpixelOrder {
1505        self.text_subpixel_order
1506    }
1507
1508    pub fn text_hinting(&self) -> TextHinting {
1509        self.text_hinting
1510    }
1511
1512    pub fn stem_darkening(&self) -> StemDarkening {
1513        self.stem_darkening
1514    }
1515
1516    pub fn set_feathering(&mut self, feathering: FeatheringOptions) {
1517        let feathering = feathering.clamped();
1518        self.feathering_enabled = feathering.enabled;
1519        self.feather_width = feathering.width;
1520    }
1521
1522    pub fn set_feathering_enabled(&mut self, enabled: bool) {
1523        self.feathering_enabled = enabled;
1524    }
1525
1526    pub fn set_text_coverage_policy(&mut self, policy: TextCoveragePolicy) {
1527        let policy = policy.normalized();
1528        if self.text_coverage_policy == policy {
1529            return;
1530        }
1531
1532        self.text_coverage_policy = policy;
1533        if let Some(text_engine) = self.text_engine.as_mut() {
1534            text_engine.set_text_coverage_policy(policy);
1535        }
1536        self.invalidate_text_render_state();
1537    }
1538
1539    pub fn set_text_render_mode(&mut self, mode: TextRenderMode) {
1540        if self.text_render_mode == mode {
1541            return;
1542        }
1543
1544        self.text_render_mode = mode;
1545        if let Some(text_engine) = self.text_engine.as_mut() {
1546            text_engine.set_text_render_mode(mode);
1547        }
1548        self.invalidate_text_render_state();
1549    }
1550
1551    pub fn set_text_subpixel_order(&mut self, order: TextSubpixelOrder) {
1552        if self.text_subpixel_order == order {
1553            return;
1554        }
1555
1556        self.text_subpixel_order = order;
1557        if let Some(text_engine) = self.text_engine.as_mut() {
1558            text_engine.set_text_subpixel_order(order);
1559        }
1560        self.invalidate_text_render_state();
1561    }
1562
1563    pub fn set_text_hinting(&mut self, hinting: TextHinting) {
1564        let hinting = hinting.normalized();
1565        if self.text_hinting == hinting {
1566            return;
1567        }
1568
1569        self.text_hinting = hinting;
1570        if let Some(text_engine) = self.text_engine.as_mut() {
1571            text_engine.set_text_hinting(hinting);
1572        }
1573    }
1574
1575    pub fn set_stem_darkening(&mut self, darkening: StemDarkening) {
1576        let darkening = darkening.normalized();
1577        if self.stem_darkening == darkening {
1578            return;
1579        }
1580
1581        self.stem_darkening = darkening;
1582        if let Some(text_engine) = self.text_engine.as_mut() {
1583            text_engine.set_stem_darkening(darkening);
1584        }
1585    }
1586
1587    pub fn set_feather_width(&mut self, feather_width: f32) {
1588        self.feather_width = feather_width.max(0.0);
1589    }
1590
1591    pub fn set_vsync_enabled(&mut self, enabled: bool) {
1592        self.vsync_enabled = enabled;
1593    }
1594
1595    pub fn set_window_display_capabilities(
1596        &mut self,
1597        window_id: WindowId,
1598        capabilities: DisplayCapabilities,
1599    ) -> Result<()> {
1600        if let Some(surface) = self.surfaces.get_mut(&window_id) {
1601            if surface.display_capabilities == capabilities {
1602                return Ok(());
1603            }
1604            surface.display_capabilities = capabilities;
1605        }
1606        self.configure_existing_surface(window_id)
1607    }
1608
1609    pub fn window_display_capabilities(&self, window_id: WindowId) -> Option<DisplayCapabilities> {
1610        self.surfaces
1611            .get(&window_id)
1612            .map(|surface| surface.display_capabilities.clone())
1613    }
1614
1615    pub fn set_window_color_management(
1616        &mut self,
1617        window_id: WindowId,
1618        color_management: ColorManagementMode,
1619    ) -> Result<()> {
1620        if let Some(surface) = self.surfaces.get_mut(&window_id) {
1621            if surface.color_management == color_management {
1622                return Ok(());
1623            }
1624            surface.color_management = color_management;
1625        }
1626        self.configure_existing_surface(window_id)
1627    }
1628
1629    pub fn window_output_strategy(&self, window_id: WindowId) -> Option<OutputStrategy> {
1630        self.surfaces
1631            .get(&window_id)
1632            .map(|surface| surface.output_strategy)
1633    }
1634
1635    pub fn window_surface_formats(&self, window_id: WindowId) -> Option<Vec<wgpu::TextureFormat>> {
1636        self.surfaces
1637            .get(&window_id)
1638            .map(|surface| surface.available_surface_formats.clone())
1639    }
1640
1641    pub fn set_runtime_feathering_override(&mut self, feathering: Option<FeatheringOptions>) {
1642        self.runtime_feathering_override = feathering.map(FeatheringOptions::clamped);
1643    }
1644
1645    pub fn set_runtime_text_subpixel_order_override(&mut self, order: Option<TextSubpixelOrder>) {
1646        self.runtime_text_subpixel_order_override = order;
1647    }
1648
1649    pub fn set_runtime_text_hinting_override(&mut self, hinting: Option<TextHinting>) {
1650        self.runtime_text_hinting_override = hinting.map(TextHinting::normalized);
1651    }
1652
1653    pub fn set_runtime_stem_darkening_override(&mut self, darkening: Option<StemDarkening>) {
1654        self.runtime_stem_darkening_override = darkening.map(StemDarkening::normalized);
1655    }
1656
1657    pub fn set_runtime_text_coverage_policy_override(
1658        &mut self,
1659        policy: Option<TextCoveragePolicy>,
1660    ) {
1661        self.runtime_text_coverage_policy_override = policy.map(TextCoveragePolicy::normalized);
1662    }
1663
1664    pub fn set_runtime_diagnostics_enabled(&mut self, enabled: bool) {
1665        self.runtime_diagnostics_enabled = enabled;
1666        if let Some(text_engine) = self.text_engine.as_mut() {
1667            text_engine.set_diagnostics_enabled(enabled);
1668        }
1669        for compositor in self.compositors.values_mut() {
1670            compositor.set_diagnostics_enabled(enabled);
1671        }
1672    }
1673
1674    fn active_feather_width(&self) -> f32 {
1675        self.runtime_feathering_override
1676            .unwrap_or_else(|| self.feathering())
1677            .effective_width()
1678    }
1679
1680    fn active_text_hinting(&self) -> TextHinting {
1681        self.runtime_text_hinting_override
1682            .unwrap_or(self.text_hinting)
1683            .normalized()
1684    }
1685
1686    fn active_text_subpixel_order(&self) -> TextSubpixelOrder {
1687        self.runtime_text_subpixel_order_override
1688            .unwrap_or(self.text_subpixel_order)
1689    }
1690
1691    fn active_stem_darkening(&self) -> StemDarkening {
1692        self.runtime_stem_darkening_override
1693            .unwrap_or(self.stem_darkening)
1694            .normalized()
1695    }
1696
1697    fn active_text_coverage_policy(&self) -> TextCoveragePolicy {
1698        self.runtime_text_coverage_policy_override
1699            .unwrap_or(self.text_coverage_policy)
1700            .normalized()
1701    }
1702
1703    fn invalidate_text_render_state(&mut self) {
1704        self.text_engine = None;
1705        self.text_atlas_array = None;
1706        self.compositors.clear();
1707        self.last_frames.clear();
1708        self.last_frame_stats.clear();
1709    }
1710
1711    pub fn register_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
1712        let physical_size = window.inner_size();
1713        let size = normalize_surface_size(physical_size.width, physical_size.height);
1714        let state = self.create_surface_state(window, size)?;
1715
1716        self.surfaces.insert(window_id, state);
1717        self.offscreen_targets.remove(&window_id);
1718        self.intermediate_targets.remove(&window_id);
1719        Ok(())
1720    }
1721
1722    pub fn remove_window(&mut self, window_id: WindowId) {
1723        self.surfaces.remove(&window_id);
1724        self.offscreen_targets.remove(&window_id);
1725        self.intermediate_targets.remove(&window_id);
1726        self.last_frames.remove(&window_id);
1727        self.last_frame_stats.remove(&window_id);
1728        self.compositors.remove(&window_id);
1729    }
1730
1731    pub fn render(&mut self, frame: &SceneFrame) -> Result<()> {
1732        let viewport = normalize_framebuffer_size(frame.surface_size);
1733        let mut frame_stats = RendererFrameStats::default();
1734
1735        if let Some(size) = viewport {
1736            if self.surfaces.contains_key(&frame.window_id) {
1737                frame_stats = self.render_surface(frame, size)?;
1738            } else {
1739                frame_stats = self.render_offscreen(frame, size)?;
1740            }
1741        }
1742
1743        self.frames_rendered += 1;
1744        self.last_frames.insert(frame.window_id, frame.clone());
1745        self.last_frame_stats.insert(frame.window_id, frame_stats);
1746        self.analytic_path_cache
1747            .retain(|_, entry| self.frames_rendered.saturating_sub(entry.last_used_frame) <= 120);
1748        Ok(())
1749    }
1750
1751    pub fn capabilities(&self) -> RendererCapabilities {
1752        self.capabilities
1753    }
1754
1755    pub fn frames_rendered(&self) -> usize {
1756        self.frames_rendered
1757    }
1758
1759    pub fn last_frame(&self, window_id: WindowId) -> Option<&SceneFrame> {
1760        self.last_frames.get(&window_id)
1761    }
1762
1763    pub fn last_frame_stats(&self, window_id: WindowId) -> Option<RendererFrameStats> {
1764        self.last_frame_stats.get(&window_id).cloned()
1765    }
1766
1767    pub fn text_cache_snapshot(&self, window_id: WindowId) -> RendererTextCacheSnapshot {
1768        let mut snapshot = self
1769            .text_engine
1770            .as_ref()
1771            .map(TextEngine::cache_snapshot)
1772            .unwrap_or_default();
1773        snapshot.path = self
1774            .compositors
1775            .get(&window_id)
1776            .map(|compositor| compositor.path_cache.snapshot())
1777            .unwrap_or_default();
1778        snapshot
1779    }
1780
1781    pub fn capture_last_frame_rgba(&mut self, window_id: WindowId) -> Result<RgbaImage> {
1782        match self.capture_last_frame_debug(window_id, DebugCaptureRequest::default())? {
1783            DebugCaptureArtifact::SdrRgba8(image) => Ok(image),
1784            DebugCaptureArtifact::HdrLinearRgbaF32(_) => Err(Error::new(format!(
1785                "window {} returned an HDR debug artifact when SDR RGBA capture was requested",
1786                window_id.get()
1787            ))),
1788        }
1789    }
1790
1791    pub fn capture_last_frame_debug(
1792        &mut self,
1793        window_id: WindowId,
1794        request: DebugCaptureRequest,
1795    ) -> Result<DebugCaptureArtifact> {
1796        let frame = self.last_frames.get(&window_id).cloned().ok_or_else(|| {
1797            Error::new(format!(
1798                "window {} does not have a previously rendered frame available for capture",
1799                window_id.get()
1800            ))
1801        })?;
1802
1803        let size = normalize_framebuffer_size(frame.surface_size).ok_or_else(|| {
1804            Error::new(format!(
1805                "window {} last rendered frame has an invalid framebuffer size",
1806                window_id.get()
1807            ))
1808        })?;
1809
1810        self.render_debug_capture_stage(&frame, size, request)?;
1811        self.capture_debug_frame(window_id, request)
1812    }
1813
1814    pub fn capture_debug_frame(
1815        &self,
1816        window_id: WindowId,
1817        request: DebugCaptureRequest,
1818    ) -> Result<DebugCaptureArtifact> {
1819        match request.stage {
1820            DebugCaptureStage::FinalComposed => {
1821                self.capture_final_composed_debug_artifact(window_id, request)
1822            }
1823            DebugCaptureStage::HdrIntermediate => {
1824                let image = self.capture_hdr_intermediate_rgba_f32(window_id)?;
1825                encode_hdr_debug_artifact(image, request, 1.0, DisplayColorPrimaries::Srgb)
1826            }
1827        }
1828    }
1829
1830    pub fn capture_rgba(&self, window_id: WindowId) -> Result<RgbaImage> {
1831        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
1832            Error::new(format!(
1833                "window {} does not have an offscreen render target available for screenshot capture",
1834                window_id.get()
1835            ))
1836        })?;
1837        let raw = self.readback_target_bytes(
1838            &target.texture,
1839            target.size,
1840            4,
1841            "SUI screenshot readback",
1842            "SUI screenshot readback encoder",
1843        )?;
1844
1845        let mut pixels = Vec::with_capacity((target.size.0 * target.size.1 * 4) as usize);
1846        for chunk in raw.chunks_exact(4) {
1847            pixels.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]]);
1848        }
1849
1850        RgbaImage::new(target.size.0, target.size.1, pixels)
1851    }
1852
1853    pub fn capture_hdr_intermediate_rgba_f32(&self, window_id: WindowId) -> Result<HdrRgbaImage> {
1854        let target = self.intermediate_targets.get(&window_id).ok_or_else(|| {
1855            Error::new(format!(
1856                "window {} does not have an HDR intermediate target available for debug capture",
1857                window_id.get()
1858            ))
1859        })?;
1860        let raw = self.readback_target_bytes(
1861            &target.texture,
1862            target.size,
1863            8,
1864            "SUI HDR intermediate readback",
1865            "SUI HDR intermediate readback encoder",
1866        )?;
1867        let pixels = decode_rgba16f_pixels(&raw);
1868        HdrRgbaImage::new(target.size.0, target.size.1, pixels)
1869    }
1870
1871    fn capture_final_composed_debug_artifact(
1872        &self,
1873        window_id: WindowId,
1874        request: DebugCaptureRequest,
1875    ) -> Result<DebugCaptureArtifact> {
1876        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
1877            Error::new(format!(
1878                "window {} does not have an offscreen target available for final composed debug capture",
1879                window_id.get()
1880            ))
1881        })?;
1882
1883        match target.format {
1884            wgpu::TextureFormat::Bgra8UnormSrgb => self
1885                .capture_rgba(window_id)
1886                .map(DebugCaptureArtifact::SdrRgba8),
1887            wgpu::TextureFormat::Rgba16Float => {
1888                let image = self.capture_hdr_offscreen_rgba_f32(window_id)?;
1889                encode_hdr_debug_artifact(
1890                    image,
1891                    request,
1892                    self.final_composed_sdr_reference_white(window_id),
1893                    self.final_composed_output_primaries(window_id),
1894                )
1895            }
1896            other => Err(Error::new(format!(
1897                "window {} uses unsupported final composed debug capture format {other:?}",
1898                window_id.get()
1899            ))),
1900        }
1901    }
1902
1903    fn capture_hdr_offscreen_rgba_f32(&self, window_id: WindowId) -> Result<HdrRgbaImage> {
1904        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
1905            Error::new(format!(
1906                "window {} does not have an offscreen HDR target available for debug capture",
1907                window_id.get()
1908            ))
1909        })?;
1910        let raw = self.readback_target_bytes(
1911            &target.texture,
1912            target.size,
1913            8,
1914            "SUI HDR final readback",
1915            "SUI HDR final readback encoder",
1916        )?;
1917        let pixels = decode_rgba16f_pixels(&raw);
1918        HdrRgbaImage::new(target.size.0, target.size.1, pixels)
1919    }
1920
1921    fn final_composed_sdr_reference_white(&self, window_id: WindowId) -> f32 {
1922        self.surfaces
1923            .get(&window_id)
1924            .map(|surface| {
1925                scene::output_sdr_content_scale(
1926                    surface.output_strategy,
1927                    surface.color_management.sdr_content_brightness_nits,
1928                    surface.display_capabilities.sdr_white_nits,
1929                )
1930            })
1931            .filter(|scale| scale.is_finite() && *scale > 0.0)
1932            .unwrap_or(1.0)
1933    }
1934
1935    fn final_composed_output_primaries(&self, window_id: WindowId) -> DisplayColorPrimaries {
1936        self.surfaces
1937            .get(&window_id)
1938            .map(|surface| scene::output_primaries(surface.output_strategy))
1939            .unwrap_or(DisplayColorPrimaries::Srgb)
1940    }
1941
1942    fn readback_target_bytes(
1943        &self,
1944        texture: &wgpu::Texture,
1945        size: (u32, u32),
1946        bytes_per_pixel: u32,
1947        buffer_label: &'static str,
1948        encoder_label: &'static str,
1949    ) -> Result<Vec<u8>> {
1950        let shared = self
1951            .shared
1952            .as_ref()
1953            .ok_or_else(|| Error::new("renderer has not initialized a wgpu device yet"))?;
1954        let bytes_per_row = size.0 * bytes_per_pixel;
1955        let padded_bytes_per_row = bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
1956            * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1957        let buffer_size = padded_bytes_per_row as u64 * size.1 as u64;
1958        let buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
1959            label: Some(buffer_label),
1960            size: buffer_size,
1961            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1962            mapped_at_creation: false,
1963        });
1964
1965        let mut encoder = shared
1966            .device
1967            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1968                label: Some(encoder_label),
1969            });
1970        encoder.copy_texture_to_buffer(
1971            wgpu::TexelCopyTextureInfo {
1972                texture,
1973                mip_level: 0,
1974                origin: wgpu::Origin3d::ZERO,
1975                aspect: wgpu::TextureAspect::All,
1976            },
1977            wgpu::TexelCopyBufferInfo {
1978                buffer: &buffer,
1979                layout: wgpu::TexelCopyBufferLayout {
1980                    offset: 0,
1981                    bytes_per_row: Some(padded_bytes_per_row),
1982                    rows_per_image: Some(size.1),
1983                },
1984            },
1985            wgpu::Extent3d {
1986                width: size.0,
1987                height: size.1,
1988                depth_or_array_layers: 1,
1989            },
1990        );
1991        shared.queue.submit([encoder.finish()]);
1992
1993        let (sender, receiver) = std::sync::mpsc::channel();
1994        let slice = buffer.slice(..);
1995        slice.map_async(wgpu::MapMode::Read, move |result| {
1996            let _ = sender.send(result);
1997        });
1998        shared
1999            .device
2000            .poll(wgpu::PollType::wait_indefinitely())
2001            .map_err(|error| {
2002                Error::new(format!(
2003                    "failed to poll device for screenshot capture: {error}"
2004                ))
2005            })?;
2006        receiver
2007            .recv()
2008            .map_err(|error| {
2009                Error::new(format!(
2010                    "failed to receive screenshot readback completion: {error}"
2011                ))
2012            })?
2013            .map_err(|error| {
2014                Error::new(format!("failed to map screenshot readback buffer: {error}"))
2015            })?;
2016
2017        let mapped = slice.get_mapped_range();
2018        let tightly_packed = strip_padded_readback_rows(
2019            &mapped,
2020            bytes_per_row as usize,
2021            padded_bytes_per_row as usize,
2022            size.1 as usize,
2023        );
2024        drop(mapped);
2025        buffer.unmap();
2026        Ok(tightly_packed)
2027    }
2028
2029    fn ensure_shared(&mut self, compatible_surface: Option<&wgpu::Surface<'_>>) -> Result<()> {
2030        if self.shared.is_some() {
2031            return Ok(());
2032        }
2033
2034        let adapter =
2035            pollster::block_on(self.instance.request_adapter(&wgpu::RequestAdapterOptions {
2036                power_preference: wgpu::PowerPreference::HighPerformance,
2037                force_fallback_adapter: false,
2038                compatible_surface,
2039            }))
2040            .map_err(|error| Error::new(format!("failed to acquire wgpu adapter: {error}")))?;
2041
2042        let required_features = optional_renderer_features(&adapter);
2043        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
2044            label: Some("SUI renderer device"),
2045            required_features,
2046            ..Default::default()
2047        }))
2048        .map_err(|error| Error::new(format!("failed to create wgpu device: {error}")))?;
2049
2050        let image_bind_group_layout =
2051            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2052                label: Some("SUI image bind group layout"),
2053                entries: &[
2054                    wgpu::BindGroupLayoutEntry {
2055                        binding: 0,
2056                        visibility: wgpu::ShaderStages::FRAGMENT,
2057                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2058                        count: None,
2059                    },
2060                    wgpu::BindGroupLayoutEntry {
2061                        binding: 1,
2062                        visibility: wgpu::ShaderStages::FRAGMENT,
2063                        ty: wgpu::BindingType::Texture {
2064                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2065                            view_dimension: wgpu::TextureViewDimension::D2,
2066                            multisampled: false,
2067                        },
2068                        count: None,
2069                    },
2070                ],
2071            });
2072        let text_atlas_array_bind_group_layout = create_text_atlas_array_bind_group_layout(&device);
2073        let image_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2074            label: Some("SUI linear image sampler"),
2075            mag_filter: wgpu::FilterMode::Linear,
2076            min_filter: wgpu::FilterMode::Linear,
2077            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2078            ..Default::default()
2079        });
2080        let image_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2081            label: Some("SUI nearest image sampler"),
2082            mag_filter: wgpu::FilterMode::Nearest,
2083            min_filter: wgpu::FilterMode::Nearest,
2084            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2085            ..Default::default()
2086        });
2087        let text_atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2088            label: Some("SUI text atlas sampler"),
2089            mag_filter: wgpu::FilterMode::Linear,
2090            min_filter: wgpu::FilterMode::Linear,
2091            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2092            ..Default::default()
2093        });
2094        let text_quad_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
2095            label: Some("SUI text atlas quad"),
2096            contents: bytemuck::cast_slice(&TextAtlasQuadVertex::unit_quad()),
2097            usage: wgpu::BufferUsages::VERTEX,
2098        });
2099        let analytic_path_bind_group_layout =
2100            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2101                label: Some("SUI analytic path bind group layout"),
2102                entries: &[
2103                    wgpu::BindGroupLayoutEntry {
2104                        binding: 0,
2105                        visibility: wgpu::ShaderStages::FRAGMENT,
2106                        ty: wgpu::BindingType::Buffer {
2107                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2108                            has_dynamic_offset: false,
2109                            min_binding_size: None,
2110                        },
2111                        count: None,
2112                    },
2113                    wgpu::BindGroupLayoutEntry {
2114                        binding: 1,
2115                        visibility: wgpu::ShaderStages::FRAGMENT,
2116                        ty: wgpu::BindingType::Buffer {
2117                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2118                            has_dynamic_offset: false,
2119                            min_binding_size: None,
2120                        },
2121                        count: None,
2122                    },
2123                    wgpu::BindGroupLayoutEntry {
2124                        binding: 2,
2125                        visibility: wgpu::ShaderStages::FRAGMENT,
2126                        ty: wgpu::BindingType::Buffer {
2127                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2128                            has_dynamic_offset: false,
2129                            min_binding_size: None,
2130                        },
2131                        count: None,
2132                    },
2133                ],
2134            });
2135        let output_transform_bind_group_layout =
2136            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2137                label: Some("SUI output transform bind group layout"),
2138                entries: &[
2139                    wgpu::BindGroupLayoutEntry {
2140                        binding: 0,
2141                        visibility: wgpu::ShaderStages::FRAGMENT,
2142                        ty: wgpu::BindingType::Texture {
2143                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
2144                            view_dimension: wgpu::TextureViewDimension::D2,
2145                            multisampled: false,
2146                        },
2147                        count: None,
2148                    },
2149                    wgpu::BindGroupLayoutEntry {
2150                        binding: 1,
2151                        visibility: wgpu::ShaderStages::FRAGMENT,
2152                        ty: wgpu::BindingType::Buffer {
2153                            ty: wgpu::BufferBindingType::Uniform,
2154                            has_dynamic_offset: false,
2155                            min_binding_size: None,
2156                        },
2157                        count: None,
2158                    },
2159                ],
2160            });
2161
2162        let dual_source_blending_enabled = device
2163            .features()
2164            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
2165
2166        self.shared = Some(SharedRenderer {
2167            adapter,
2168            device,
2169            queue,
2170            pipelines: HashMap::new(),
2171            image_bind_group_layout,
2172            text_atlas_array_bind_group_layout,
2173            analytic_path_bind_group_layout,
2174            output_transform_bind_group_layout,
2175            image_linear_sampler,
2176            image_nearest_sampler,
2177            text_atlas_sampler,
2178            text_quad_buffer,
2179            dual_source_blending_enabled,
2180        });
2181        if let (Some(registry), Some(shared)) = (&self.external_texture_registry, &self.shared) {
2182            registry.attach(shared.device.clone(), shared.queue.clone());
2183        }
2184
2185        Ok(())
2186    }
2187
2188    #[cfg(target_arch = "wasm32")]
2189    pub async fn initialize_async(
2190        &mut self,
2191        compatible_surface: Option<&wgpu::Surface<'_>>,
2192    ) -> Result<()> {
2193        if self.shared.is_some() {
2194            return Ok(());
2195        }
2196
2197        let adapter = self
2198            .instance
2199            .request_adapter(&wgpu::RequestAdapterOptions {
2200                power_preference: wgpu::PowerPreference::None,
2201                force_fallback_adapter: false,
2202                compatible_surface,
2203            })
2204            .await
2205            .map_err(|error| Error::new(format!("failed to acquire wgpu adapter: {error}")))?;
2206
2207        let required_features = optional_renderer_features(&adapter);
2208        let (device, queue) = adapter
2209            .request_device(&wgpu::DeviceDescriptor {
2210                label: Some("SUI renderer device"),
2211                required_features,
2212                ..Default::default()
2213            })
2214            .await
2215            .map_err(|error| Error::new(format!("failed to create wgpu device: {error}")))?;
2216
2217        let image_bind_group_layout =
2218            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2219                label: Some("SUI image bind group layout"),
2220                entries: &[
2221                    wgpu::BindGroupLayoutEntry {
2222                        binding: 0,
2223                        visibility: wgpu::ShaderStages::FRAGMENT,
2224                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2225                        count: None,
2226                    },
2227                    wgpu::BindGroupLayoutEntry {
2228                        binding: 1,
2229                        visibility: wgpu::ShaderStages::FRAGMENT,
2230                        ty: wgpu::BindingType::Texture {
2231                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2232                            view_dimension: wgpu::TextureViewDimension::D2,
2233                            multisampled: false,
2234                        },
2235                        count: None,
2236                    },
2237                ],
2238            });
2239        let text_atlas_array_bind_group_layout = create_text_atlas_array_bind_group_layout(&device);
2240        let image_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2241            label: Some("SUI linear image sampler"),
2242            mag_filter: wgpu::FilterMode::Linear,
2243            min_filter: wgpu::FilterMode::Linear,
2244            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2245            ..Default::default()
2246        });
2247        let image_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2248            label: Some("SUI nearest image sampler"),
2249            mag_filter: wgpu::FilterMode::Nearest,
2250            min_filter: wgpu::FilterMode::Nearest,
2251            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2252            ..Default::default()
2253        });
2254        let text_atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2255            label: Some("SUI text atlas sampler"),
2256            mag_filter: wgpu::FilterMode::Linear,
2257            min_filter: wgpu::FilterMode::Linear,
2258            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2259            ..Default::default()
2260        });
2261        let text_quad_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
2262            label: Some("SUI text atlas quad"),
2263            contents: bytemuck::cast_slice(&TextAtlasQuadVertex::unit_quad()),
2264            usage: wgpu::BufferUsages::VERTEX,
2265        });
2266        let analytic_path_bind_group_layout =
2267            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2268                label: Some("SUI analytic path bind group layout"),
2269                entries: &[
2270                    wgpu::BindGroupLayoutEntry {
2271                        binding: 0,
2272                        visibility: wgpu::ShaderStages::FRAGMENT,
2273                        ty: wgpu::BindingType::Buffer {
2274                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2275                            has_dynamic_offset: false,
2276                            min_binding_size: None,
2277                        },
2278                        count: None,
2279                    },
2280                    wgpu::BindGroupLayoutEntry {
2281                        binding: 1,
2282                        visibility: wgpu::ShaderStages::FRAGMENT,
2283                        ty: wgpu::BindingType::Buffer {
2284                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2285                            has_dynamic_offset: false,
2286                            min_binding_size: None,
2287                        },
2288                        count: None,
2289                    },
2290                    wgpu::BindGroupLayoutEntry {
2291                        binding: 2,
2292                        visibility: wgpu::ShaderStages::FRAGMENT,
2293                        ty: wgpu::BindingType::Buffer {
2294                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2295                            has_dynamic_offset: false,
2296                            min_binding_size: None,
2297                        },
2298                        count: None,
2299                    },
2300                ],
2301            });
2302        let output_transform_bind_group_layout =
2303            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2304                label: Some("SUI output transform bind group layout"),
2305                entries: &[
2306                    wgpu::BindGroupLayoutEntry {
2307                        binding: 0,
2308                        visibility: wgpu::ShaderStages::FRAGMENT,
2309                        ty: wgpu::BindingType::Texture {
2310                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
2311                            view_dimension: wgpu::TextureViewDimension::D2,
2312                            multisampled: false,
2313                        },
2314                        count: None,
2315                    },
2316                    wgpu::BindGroupLayoutEntry {
2317                        binding: 1,
2318                        visibility: wgpu::ShaderStages::FRAGMENT,
2319                        ty: wgpu::BindingType::Buffer {
2320                            ty: wgpu::BufferBindingType::Uniform,
2321                            has_dynamic_offset: false,
2322                            min_binding_size: None,
2323                        },
2324                        count: None,
2325                    },
2326                ],
2327            });
2328
2329        let dual_source_blending_enabled = device
2330            .features()
2331            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
2332
2333        self.shared = Some(SharedRenderer {
2334            adapter,
2335            device,
2336            queue,
2337            pipelines: HashMap::new(),
2338            image_bind_group_layout,
2339            text_atlas_array_bind_group_layout,
2340            analytic_path_bind_group_layout,
2341            output_transform_bind_group_layout,
2342            image_linear_sampler,
2343            image_nearest_sampler,
2344            text_atlas_sampler,
2345            text_quad_buffer,
2346            dual_source_blending_enabled,
2347        });
2348        if let (Some(registry), Some(shared)) = (&self.external_texture_registry, &self.shared) {
2349            registry.attach(shared.device.clone(), shared.queue.clone());
2350        }
2351
2352        Ok(())
2353    }
2354
2355    fn render_surface(
2356        &mut self,
2357        frame: &SceneFrame,
2358        size: (u32, u32),
2359    ) -> Result<RendererFrameStats> {
2360        self.ensure_shared(None)?;
2361        self.resize_surface(frame.window_id, size)?;
2362
2363        let prepared = self.prepare_scene_submission(frame)?;
2364
2365        let Some((frame_texture, suboptimal, surface_acquire_time_us)) =
2366            self.acquire_surface_texture(frame.window_id, size)?
2367        else {
2368            return Ok(RendererFrameStats::default());
2369        };
2370
2371        let (format, strategy, tone_mapping, sdr_content_brightness_nits, display_sdr_white_nits) = {
2372            let surface = self.surfaces.get(&frame.window_id).ok_or_else(|| {
2373                Error::new(format!(
2374                    "missing surface for window {}",
2375                    frame.window_id.get()
2376                ))
2377            })?;
2378            (
2379                surface.config.format,
2380                surface.output_strategy,
2381                surface.color_management.tone_mapping,
2382                surface.color_management.sdr_content_brightness_nits,
2383                surface.display_capabilities.sdr_white_nits,
2384            )
2385        };
2386        let view = frame_texture
2387            .texture
2388            .create_view(&wgpu::TextureViewDescriptor::default());
2389
2390        let mut frame_stats = if output_transform_requires_intermediate(strategy) {
2391            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2392            let intermediate_format = self
2393                .intermediate_targets
2394                .get(&frame.window_id)
2395                .map(|target| target.format)
2396                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2397            let mut frame_stats =
2398                self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2399            self.submit_output_transform_pass(
2400                &intermediate_view,
2401                &view,
2402                format,
2403                strategy,
2404                tone_mapping,
2405                sdr_content_brightness_nits,
2406                display_sdr_white_nits,
2407                &mut frame_stats,
2408            )?;
2409            frame_stats
2410        } else {
2411            self.submit_prepared_scene(prepared, format, &view)?
2412        };
2413        frame_stats.surface_acquire_time_us = surface_acquire_time_us;
2414        let surface_present_started = self.runtime_diagnostics_enabled.then(Instant::now);
2415        frame_texture.present();
2416        frame_stats.surface_present_time_us = surface_present_started
2417            .map(|started| started.elapsed().as_micros() as u64)
2418            .unwrap_or(0);
2419
2420        if suboptimal {
2421            self.configure_surface(frame.window_id, size)?;
2422        }
2423
2424        Ok(frame_stats)
2425    }
2426
2427    fn acquire_surface_texture(
2428        &mut self,
2429        window_id: WindowId,
2430        size: (u32, u32),
2431    ) -> Result<Option<(wgpu::SurfaceTexture, bool, u64)>> {
2432        let surface_acquire_started = self.runtime_diagnostics_enabled.then(Instant::now);
2433        let (frame_texture, suboptimal) = loop {
2434            let result = {
2435                let surface = self.surfaces.get(&window_id).ok_or_else(|| {
2436                    Error::new(format!("missing surface for window {}", window_id.get()))
2437                })?;
2438                surface.surface.get_current_texture()
2439            };
2440
2441            match result {
2442                wgpu::CurrentSurfaceTexture::Success(texture) => break (texture, false),
2443                wgpu::CurrentSurfaceTexture::Suboptimal(texture) => break (texture, true),
2444                wgpu::CurrentSurfaceTexture::Outdated => {
2445                    self.configure_surface(window_id, size)?;
2446                }
2447                wgpu::CurrentSurfaceTexture::Lost => {
2448                    self.recreate_surface(window_id, size)?;
2449                }
2450                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
2451                    return Ok(None);
2452                }
2453                wgpu::CurrentSurfaceTexture::Validation => {
2454                    return Err(Error::new(
2455                        "wgpu surface acquisition triggered a validation error",
2456                    ));
2457                }
2458            }
2459        };
2460        let surface_acquire_time_us = surface_acquire_started
2461            .map(|started| started.elapsed().as_micros() as u64)
2462            .unwrap_or(0);
2463
2464        Ok(Some((frame_texture, suboptimal, surface_acquire_time_us)))
2465    }
2466
2467    fn render_debug_capture_stage(
2468        &mut self,
2469        frame: &SceneFrame,
2470        size: (u32, u32),
2471        request: DebugCaptureRequest,
2472    ) -> Result<RendererFrameStats> {
2473        match request.stage {
2474            DebugCaptureStage::HdrIntermediate => self.render_offscreen(frame, size),
2475            DebugCaptureStage::FinalComposed
2476                if request.encoding == DebugCaptureEncoding::Png
2477                    && request.sdr_visualization == DebugSdrVisualization::ToneMappedColor =>
2478            {
2479                self.render_offscreen(frame, size)
2480            }
2481            DebugCaptureStage::FinalComposed => self.render_final_composed_offscreen(frame, size),
2482        }
2483    }
2484
2485    fn render_final_composed_offscreen(
2486        &mut self,
2487        frame: &SceneFrame,
2488        size: (u32, u32),
2489    ) -> Result<RendererFrameStats> {
2490        self.ensure_shared(None)?;
2491
2492        let Some(surface_state) = self.surfaces.get(&frame.window_id) else {
2493            return self.render_offscreen(frame, size);
2494        };
2495        let strategy = surface_state.output_strategy;
2496        let requested_tone_mapping = surface_state.color_management.tone_mapping;
2497        let sdr_content_brightness_nits =
2498            surface_state.color_management.sdr_content_brightness_nits;
2499        let display_sdr_white_nits = surface_state.display_capabilities.sdr_white_nits;
2500        let final_format = strategy.surface_format();
2501        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
2502        let prepared = self.prepare_scene_submission(frame)?;
2503
2504        if output_transform_requires_intermediate(strategy) {
2505            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2506            let intermediate_format = self
2507                .intermediate_targets
2508                .get(&frame.window_id)
2509                .map(|target| target.format)
2510                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2511            let mut frame_stats =
2512                self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2513            self.submit_output_transform_pass(
2514                &intermediate_view,
2515                &final_view,
2516                final_format,
2517                strategy,
2518                requested_tone_mapping,
2519                sdr_content_brightness_nits,
2520                display_sdr_white_nits,
2521                &mut frame_stats,
2522            )?;
2523            Ok(frame_stats)
2524        } else {
2525            self.submit_prepared_scene(prepared, final_format, &final_view)
2526        }
2527    }
2528
2529    fn render_offscreen(
2530        &mut self,
2531        frame: &SceneFrame,
2532        size: (u32, u32),
2533    ) -> Result<RendererFrameStats> {
2534        self.ensure_shared(None)?;
2535
2536        let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
2537        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
2538        let prepared = self.prepare_scene_submission(frame)?;
2539        let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2540        let intermediate_format = self
2541            .intermediate_targets
2542            .get(&frame.window_id)
2543            .map(|target| target.format)
2544            .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2545        let mut frame_stats =
2546            self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2547        self.submit_output_transform_pass(
2548            &intermediate_view,
2549            &final_view,
2550            final_format,
2551            OutputStrategy::SdrSurface {
2552                format: final_format,
2553            },
2554            RequestedToneMappingMode::Clamp,
2555            ColorManagementMode::default().sdr_content_brightness_nits,
2556            None,
2557            &mut frame_stats,
2558        )?;
2559        Ok(frame_stats)
2560    }
2561
2562    fn ensure_offscreen_target(
2563        &mut self,
2564        window_id: WindowId,
2565        size: (u32, u32),
2566        format: wgpu::TextureFormat,
2567    ) -> Result<wgpu::TextureView> {
2568        let recreate = self
2569            .offscreen_targets
2570            .get(&window_id)
2571            .is_none_or(|target| target.size != size || target.format != format);
2572        if recreate {
2573            let shared = self
2574                .shared
2575                .as_ref()
2576                .expect("renderer shared state initialized");
2577            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
2578                label: Some("SUI offscreen frame"),
2579                size: wgpu::Extent3d {
2580                    width: size.0,
2581                    height: size.1,
2582                    depth_or_array_layers: 1,
2583                },
2584                mip_level_count: 1,
2585                sample_count: 1,
2586                dimension: wgpu::TextureDimension::D2,
2587                format,
2588                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
2589                view_formats: &[],
2590            });
2591            self.offscreen_targets.insert(
2592                window_id,
2593                OffscreenTarget {
2594                    texture,
2595                    format,
2596                    size,
2597                },
2598            );
2599        }
2600        self.offscreen_targets
2601            .get(&window_id)
2602            .map(|target| {
2603                target
2604                    .texture
2605                    .create_view(&wgpu::TextureViewDescriptor::default())
2606            })
2607            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
2608    }
2609
2610    fn ensure_intermediate_target(
2611        &mut self,
2612        window_id: WindowId,
2613        size: (u32, u32),
2614    ) -> Result<wgpu::TextureView> {
2615        let format = wgpu::TextureFormat::Rgba16Float;
2616        let recreate = self
2617            .intermediate_targets
2618            .get(&window_id)
2619            .is_none_or(|target| target.size != size || target.format != format);
2620        if recreate {
2621            let shared = self
2622                .shared
2623                .as_ref()
2624                .expect("renderer shared state initialized");
2625            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
2626                label: Some("SUI HDR intermediate frame"),
2627                size: wgpu::Extent3d {
2628                    width: size.0,
2629                    height: size.1,
2630                    depth_or_array_layers: 1,
2631                },
2632                mip_level_count: 1,
2633                sample_count: 1,
2634                dimension: wgpu::TextureDimension::D2,
2635                format,
2636                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
2637                    | wgpu::TextureUsages::TEXTURE_BINDING
2638                    | wgpu::TextureUsages::COPY_SRC,
2639                view_formats: &[],
2640            });
2641            self.intermediate_targets.insert(
2642                window_id,
2643                OffscreenTarget {
2644                    texture,
2645                    format,
2646                    size,
2647                },
2648            );
2649        }
2650        self.intermediate_targets
2651            .get(&window_id)
2652            .map(|target| {
2653                target
2654                    .texture
2655                    .create_view(&wgpu::TextureViewDescriptor::default())
2656            })
2657            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
2658    }
2659
2660    fn submit_output_transform_pass(
2661        &mut self,
2662        source_view: &wgpu::TextureView,
2663        destination_view: &wgpu::TextureView,
2664        destination_format: wgpu::TextureFormat,
2665        strategy: OutputStrategy,
2666        requested_tone_mapping: RequestedToneMappingMode,
2667        sdr_content_brightness_nits: f32,
2668        display_sdr_white_nits: Option<f32>,
2669        frame_stats: &mut RendererFrameStats,
2670    ) -> Result<()> {
2671        let resolved_tone_mapping = match strategy {
2672            OutputStrategy::HdrNativeSurface { .. } => 0,
2673            _ => match requested_tone_mapping {
2674                RequestedToneMappingMode::Automatic => 1,
2675                RequestedToneMappingMode::Clamp => 1,
2676                RequestedToneMappingMode::Reinhard => 2,
2677            },
2678        };
2679        let shared = self
2680            .shared
2681            .as_mut()
2682            .expect("renderer shared state initialized");
2683        let sdr_content_scale = scene::output_sdr_content_scale(
2684            strategy,
2685            sdr_content_brightness_nits,
2686            display_sdr_white_nits,
2687        );
2688        let encode_srgb = matches!(
2689            destination_format,
2690            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
2691        ) || matches!(
2692            strategy,
2693            OutputStrategy::HdrNativeSurface {
2694                transfer: DisplayTransferFunction::Srgb,
2695                ..
2696            }
2697        );
2698        let uniform = OutputTransformUniform::new(
2699            resolved_tone_mapping,
2700            encode_srgb,
2701            scene::output_primaries(strategy),
2702            sdr_content_scale,
2703        );
2704        let uniform_buffer = shared
2705            .device
2706            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
2707                label: Some("SUI output transform uniform"),
2708                contents: bytemuck::bytes_of(&uniform),
2709                usage: wgpu::BufferUsages::UNIFORM,
2710            });
2711        let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
2712            label: Some("SUI output transform bind group"),
2713            layout: &shared.output_transform_bind_group_layout,
2714            entries: &[
2715                wgpu::BindGroupEntry {
2716                    binding: 0,
2717                    resource: wgpu::BindingResource::TextureView(source_view),
2718                },
2719                wgpu::BindGroupEntry {
2720                    binding: 1,
2721                    resource: uniform_buffer.as_entire_binding(),
2722                },
2723            ],
2724        });
2725        let mut encoder = shared
2726            .device
2727            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2728                label: Some("SUI output transform encoder"),
2729            });
2730        {
2731            let pipeline = shared.output_transform_pipeline(destination_format);
2732            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2733                label: Some("SUI output transform pass"),
2734                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2735                    view: destination_view,
2736                    depth_slice: None,
2737                    resolve_target: None,
2738                    ops: wgpu::Operations {
2739                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
2740                        store: wgpu::StoreOp::Store,
2741                    },
2742                })],
2743                depth_stencil_attachment: None,
2744                occlusion_query_set: None,
2745                timestamp_writes: None,
2746                multiview_mask: None,
2747            });
2748            pass.set_pipeline(pipeline);
2749            pass.set_bind_group(0, &bind_group, &[]);
2750            pass.draw(0..3, 0..1);
2751        }
2752        shared.queue.submit([encoder.finish()]);
2753        frame_stats.pass_count += 1;
2754        Ok(())
2755    }
2756
2757    fn resize_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2758        let surface = self
2759            .surfaces
2760            .get(&window_id)
2761            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
2762
2763        if surface.config.width == size.0 && surface.config.height == size.1 {
2764            return Ok(());
2765        }
2766
2767        self.configure_surface(window_id, size)
2768    }
2769
2770    fn configure_existing_surface(&mut self, window_id: WindowId) -> Result<()> {
2771        let size = {
2772            let surface = self.surfaces.get(&window_id).ok_or_else(|| {
2773                Error::new(format!("missing surface for window {}", window_id.get()))
2774            })?;
2775            (surface.config.width.max(1), surface.config.height.max(1))
2776        };
2777        self.configure_surface(window_id, size)
2778    }
2779
2780    fn configure_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2781        let shared = self
2782            .shared
2783            .as_ref()
2784            .expect("renderer shared state initialized");
2785        let surface = self
2786            .surfaces
2787            .get_mut(&window_id)
2788            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
2789
2790        let available_surface_formats = surface.surface.get_capabilities(&shared.adapter).formats;
2791        let (config, output_strategy) = configure_surface(
2792            &surface.surface,
2793            &shared.adapter,
2794            &shared.device,
2795            size,
2796            self.vsync_enabled,
2797            surface.display_capabilities.clone(),
2798            surface.color_management,
2799        )?;
2800        surface.config = config;
2801        surface.output_strategy = output_strategy;
2802        surface.available_surface_formats = available_surface_formats;
2803        Ok(())
2804    }
2805
2806    fn recreate_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2807        let window = self
2808            .surfaces
2809            .get(&window_id)
2810            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?
2811            .window
2812            .clone();
2813        let state = self.create_surface_state(window, size)?;
2814        self.surfaces.insert(window_id, state);
2815        Ok(())
2816    }
2817
2818    fn prepare_scene_submission(&mut self, frame: &SceneFrame) -> Result<PreparedSceneSubmission> {
2819        let diagnostics_enabled = self.runtime_diagnostics_enabled;
2820        let feather_width = self.active_feather_width();
2821        let text_render_mode = self.text_render_mode();
2822        let text_subpixel_order = self.active_text_subpixel_order();
2823        let text_hinting = self.active_text_hinting();
2824        let stem_darkening = self.active_stem_darkening();
2825        let text_coverage_policy = self.active_text_coverage_policy();
2826        if self.text_engine.is_none() {
2827            self.text_engine = Some(TextEngine::new()?);
2828        }
2829        // The multi-page atlas grows and evicts on demand, so a glyph that cannot be placed is
2830        // simply dropped for the frame -- there is no longer an "atlas full" error to recover
2831        // from, hence no retry loop.
2832        let (submission, compositor_stats, text_frame_stats) = {
2833            let text_engine = self
2834                .text_engine
2835                .as_mut()
2836                .expect("text engine initialized before draw-op construction");
2837            text_engine.set_text_render_mode(text_render_mode);
2838            text_engine.set_text_subpixel_order(text_subpixel_order);
2839            text_engine.set_text_hinting(text_hinting);
2840            text_engine.set_stem_darkening(stem_darkening);
2841            text_engine.set_text_coverage_policy(text_coverage_policy);
2842            text_engine.set_diagnostics_enabled(diagnostics_enabled);
2843            text_engine.begin_frame();
2844            let compositor = self.compositors.entry(frame.window_id).or_default();
2845            compositor.set_diagnostics_enabled(diagnostics_enabled);
2846            let submission =
2847                compositor.prepare_frame_submission(frame, text_engine, feather_width)?;
2848            let compositor_stats = compositor.last_frame_stats.clone();
2849            let text_frame_stats = if diagnostics_enabled {
2850                text_engine.frame_stats()
2851            } else {
2852                TextFrameStats::default()
2853            };
2854            (submission, compositor_stats, text_frame_stats)
2855        };
2856        let framebuffer_size = normalize_framebuffer_size(frame.surface_size).unwrap_or((1, 1));
2857        let mut analytic_paths = HashMap::new();
2858        let mut image_resources = HashSet::new();
2859        let mut uses_text_atlas = false;
2860        let resource_collection_started = diagnostics_enabled.then(Instant::now);
2861        for fragment in &submission.fragments {
2862            let RetainedFrameFragment::Transient(draw_ops) = fragment;
2863            uses_text_atlas |=
2864                collect_draw_op_resources(draw_ops, &mut analytic_paths, &mut image_resources);
2865        }
2866        let resource_collection_time_us = resource_collection_started
2867            .map(|started| started.elapsed().as_micros() as u64)
2868            .unwrap_or(0);
2869
2870        let bind_group_prepare_started = diagnostics_enabled.then(Instant::now);
2871        let (analytic_path_resources, analytic_path_stats) =
2872            self.prepare_analytic_path_resources(analytic_paths, diagnostics_enabled)?;
2873        let analytic_path_bind_group_time_us = analytic_path_stats.total_time_us;
2874        let analytic_path_bind_group_miss_count = analytic_path_stats.miss_count;
2875        let analytic_path_bind_group_upload_bytes = analytic_path_stats.upload_bytes;
2876
2877        let image_bind_group_started = diagnostics_enabled.then(Instant::now);
2878        let mut image_bind_groups = HashMap::new();
2879        for (handle, sampling) in image_resources {
2880            let bind_group = if let Some(image) = frame.image_registry.get_external(handle) {
2881                self.ensure_external_image_bind_group(handle, sampling, *image)?
2882            } else {
2883                let image = frame.image_registry.get(handle).ok_or_else(|| {
2884                    Error::new(format!("image handle {} is not registered", handle.get()))
2885                })?;
2886                self.ensure_image_bind_group(handle, sampling, image)?
2887            };
2888            image_bind_groups.insert((handle, sampling), bind_group);
2889        }
2890        let image_bind_group_time_us = image_bind_group_started
2891            .map(|started| started.elapsed().as_micros() as u64)
2892            .unwrap_or(0);
2893        let mut text_atlas_bind_group_time_us = 0u64;
2894        let mut text_atlas_upload_copy_time_us = 0u64;
2895        let mut text_atlas_upload_write_time_us = 0u64;
2896        let mut text_atlas_upload_bytes = 0u64;
2897        let text_atlas_bind_group = if uses_text_atlas {
2898            let mut text_engine = self
2899                .text_engine
2900                .take()
2901                .expect("text engine initialized before text atlas upload");
2902            let (bind_group, stats) =
2903                self.ensure_text_atlas_bind_group(&mut text_engine, diagnostics_enabled)?;
2904            self.text_engine = Some(text_engine);
2905            text_atlas_bind_group_time_us = stats.total_time_us;
2906            text_atlas_upload_copy_time_us = stats.upload_copy_time_us;
2907            text_atlas_upload_write_time_us = stats.upload_write_time_us;
2908            text_atlas_upload_bytes = stats.upload_bytes;
2909            Some(bind_group)
2910        } else {
2911            None
2912        };
2913        let bind_group_prepare_time_us = bind_group_prepare_started
2914            .map(|started| started.elapsed().as_micros() as u64)
2915            .unwrap_or(0);
2916        let mut prepared_fragments = Vec::new();
2917        let mut draw_count = 0usize;
2918        let mut uploaded_vertex_bytes = 0u64;
2919        let mut needs_stencil = false;
2920        let mut batch_prepare_time_us = 0u64;
2921        let mut gpu_upload_time_us = 0u64;
2922
2923        for fragment in submission.fragments {
2924            let RetainedFrameFragment::Transient(draw_ops) = fragment;
2925            let batch_prepare_started = diagnostics_enabled.then(Instant::now);
2926            let mut prepared = prepare_frame_batches(draw_ops, frame.viewport, framebuffer_size);
2927            stamp_analytic_path_slots(
2928                &mut prepared.scene_vertices,
2929                &prepared.passes,
2930                analytic_path_resources.as_ref(),
2931            );
2932            if let Some(started) = batch_prepare_started {
2933                batch_prepare_time_us += started.elapsed().as_micros() as u64;
2934            }
2935            if diagnostics_enabled {
2936                let (_, fragment_draw_count) = prepared_batch_counts(&prepared.passes);
2937                draw_count += fragment_draw_count;
2938                uploaded_vertex_bytes += (prepared.scene_vertices.len() as u64
2939                    + prepared.clip_vertices.len() as u64)
2940                    * VERTEX_SIZE
2941                    + prepared.text_instances.len() as u64 * TEXT_ATLAS_INSTANCE_SIZE;
2942            }
2943
2944            if prepared.passes.is_empty() {
2945                continue;
2946            }
2947
2948            let shared = self
2949                .shared
2950                .as_ref()
2951                .expect("renderer shared state initialized");
2952            needs_stencil |= prepared
2953                .passes
2954                .iter()
2955                .any(|pass| !pass.clip_paths.is_empty());
2956            let gpu_upload_started = diagnostics_enabled.then(Instant::now);
2957            prepared_fragments.push(PreparedFragmentSubmission {
2958                passes: prepared.passes,
2959                scene_buffer: create_static_vertex_buffer(
2960                    &shared.device,
2961                    "SUI transient fragment scene",
2962                    &prepared.scene_vertices,
2963                ),
2964                clip_buffer: create_static_vertex_buffer(
2965                    &shared.device,
2966                    "SUI transient fragment clip",
2967                    &prepared.clip_vertices,
2968                ),
2969                text_instance_buffer: create_static_text_instance_buffer(
2970                    &shared.device,
2971                    "SUI transient fragment text instances",
2972                    &prepared.text_instances,
2973                ),
2974                translation: Vector::ZERO,
2975            });
2976            if let Some(started) = gpu_upload_started {
2977                gpu_upload_time_us += started.elapsed().as_micros() as u64;
2978            }
2979        }
2980
2981        if needs_stencil {
2982            let shared = self
2983                .shared
2984                .as_ref()
2985                .expect("renderer shared state initialized");
2986            let gpu_upload_started = diagnostics_enabled.then(Instant::now);
2987            self.frame_resources
2988                .ensure_stencil(&shared.device, framebuffer_size);
2989            if let Some(started) = gpu_upload_started {
2990                gpu_upload_time_us += started.elapsed().as_micros() as u64;
2991            }
2992        }
2993
2994        let batch_prepare_started = diagnostics_enabled.then(Instant::now);
2995        let encodable_passes = flatten_fragment_passes(&prepared_fragments);
2996        if let Some(started) = batch_prepare_started {
2997            batch_prepare_time_us += started.elapsed().as_micros() as u64;
2998        }
2999        let mut frame_stats = if diagnostics_enabled {
3000            RendererFrameStats::from_prepared_counts(0, draw_count, uploaded_vertex_bytes)
3001                .with_text_stats(text_frame_stats)
3002                .with_compositor_stats(compositor_stats)
3003        } else {
3004            RendererFrameStats::default()
3005        };
3006        frame_stats.resource_collection_time_us = resource_collection_time_us;
3007        frame_stats.bind_group_prepare_time_us = bind_group_prepare_time_us;
3008        frame_stats.image_bind_group_time_us = image_bind_group_time_us;
3009        frame_stats.analytic_path_bind_group_time_us = analytic_path_bind_group_time_us;
3010        frame_stats.analytic_path_bind_group_miss_count = analytic_path_bind_group_miss_count;
3011        frame_stats.analytic_path_bind_group_upload_bytes = analytic_path_bind_group_upload_bytes;
3012        frame_stats.text_atlas_bind_group_time_us = text_atlas_bind_group_time_us;
3013        frame_stats.text_atlas_upload_copy_time_us = text_atlas_upload_copy_time_us;
3014        frame_stats.text_atlas_upload_write_time_us = text_atlas_upload_write_time_us;
3015        frame_stats.text_atlas_upload_bytes = text_atlas_upload_bytes;
3016        frame_stats.batch_prepare_time_us = batch_prepare_time_us;
3017        frame_stats.gpu_upload_time_us = gpu_upload_time_us;
3018        Ok(PreparedSceneSubmission {
3019            viewport: frame.viewport,
3020            framebuffer_size,
3021            encodable_passes,
3022            image_bind_groups,
3023            text_atlas_bind_group,
3024            analytic_path_resources,
3025            frame_stats,
3026        })
3027    }
3028
3029    fn submit_prepared_scene(
3030        &mut self,
3031        prepared: PreparedSceneSubmission,
3032        target_format: wgpu::TextureFormat,
3033        view: &wgpu::TextureView,
3034    ) -> Result<RendererFrameStats> {
3035        let mut encoder = {
3036            let shared = self
3037                .shared
3038                .as_ref()
3039                .expect("renderer shared state initialized");
3040            shared
3041                .device
3042                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3043                    label: Some("SUI scene encoder"),
3044                })
3045        };
3046
3047        let pass_encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
3048        let pass_count = if prepared.encodable_passes.is_empty() {
3049            let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3050                label: Some("SUI scene clear pass"),
3051                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3052                    view,
3053                    depth_slice: None,
3054                    resolve_target: None,
3055                    ops: wgpu::Operations {
3056                        load: wgpu::LoadOp::Clear(wgpu::Color {
3057                            r: 0.0,
3058                            g: 0.0,
3059                            b: 0.0,
3060                            a: 0.0,
3061                        }),
3062                        store: wgpu::StoreOp::Store,
3063                    },
3064                })],
3065                depth_stencil_attachment: None,
3066                occlusion_query_set: None,
3067                timestamp_writes: None,
3068                multiview_mask: None,
3069            });
3070            1
3071        } else {
3072            let shared = self
3073                .shared
3074                .as_mut()
3075                .expect("renderer shared state initialized");
3076            let stencil_view = self.frame_resources.stencil.as_ref().map(|target| {
3077                let _ = &target.texture;
3078                &target.view
3079            });
3080            encode_fragment_passes(
3081                shared,
3082                &mut encoder,
3083                view,
3084                target_format,
3085                prepared.viewport,
3086                prepared.framebuffer_size,
3087                &prepared.encodable_passes,
3088                stencil_view,
3089                &prepared.image_bind_groups,
3090                prepared.text_atlas_bind_group.as_ref(),
3091                prepared.analytic_path_resources.as_ref(),
3092            )?
3093        };
3094        let pass_encode_time_us = pass_encode_started
3095            .map(|started| started.elapsed().as_micros() as u64)
3096            .unwrap_or(0);
3097
3098        let queue_submit_started = self.runtime_diagnostics_enabled.then(Instant::now);
3099        self.shared
3100            .as_ref()
3101            .expect("renderer shared state initialized")
3102            .queue
3103            .submit([encoder.finish()]);
3104        let queue_submit_time_us = queue_submit_started
3105            .map(|started| started.elapsed().as_micros() as u64)
3106            .unwrap_or(0);
3107
3108        let mut frame_stats = prepared.frame_stats;
3109        frame_stats.pass_encode_time_us = pass_encode_time_us;
3110        frame_stats.queue_submit_time_us = queue_submit_time_us;
3111        frame_stats.pass_count = pass_count.max(1);
3112        Ok(frame_stats)
3113    }
3114
3115    fn registered_image_data_identity_eq(left: &RegisteredImage, right: &RegisteredImage) -> bool {
3116        left.width() == right.width()
3117            && left.height() == right.height()
3118            && left.format() == right.format()
3119            && left.bytes().len() == right.bytes().len()
3120            && std::ptr::addr_eq(left.bytes().as_ptr(), right.bytes().as_ptr())
3121    }
3122
3123    fn write_registered_image_texture(
3124        queue: &wgpu::Queue,
3125        texture: &wgpu::Texture,
3126        image: &RegisteredImage,
3127    ) {
3128        queue.write_texture(
3129            wgpu::TexelCopyTextureInfo {
3130                texture,
3131                mip_level: 0,
3132                origin: wgpu::Origin3d::ZERO,
3133                aspect: wgpu::TextureAspect::All,
3134            },
3135            image.bytes(),
3136            wgpu::TexelCopyBufferLayout {
3137                offset: 0,
3138                bytes_per_row: Some(image.width() * 4),
3139                rows_per_image: Some(image.height()),
3140            },
3141            wgpu::Extent3d {
3142                width: image.width(),
3143                height: image.height(),
3144                depth_or_array_layers: 1,
3145            },
3146        );
3147    }
3148
3149    fn ensure_image_bind_group(
3150        &mut self,
3151        handle: ImageHandle,
3152        sampling: ImageSampling,
3153        image: &RegisteredImage,
3154    ) -> Result<wgpu::BindGroup> {
3155        if let Some(cached) = self.image_cache.get_mut(&handle) {
3156            if Self::registered_image_data_identity_eq(&cached.image, image) {
3157                return Ok(Self::image_bind_group_for_sampling(cached, sampling));
3158            }
3159            if cached.image.width() == image.width()
3160                && cached.image.height() == image.height()
3161                && cached.image.format() == image.format()
3162            {
3163                let shared = self
3164                    .shared
3165                    .as_ref()
3166                    .expect("renderer shared state initialized");
3167                Self::write_registered_image_texture(&shared.queue, &cached.texture, image);
3168                cached.image = image.clone();
3169                return Ok(Self::image_bind_group_for_sampling(cached, sampling));
3170            }
3171        }
3172
3173        let shared = self
3174            .shared
3175            .as_ref()
3176            .expect("renderer shared state initialized");
3177        let texture_format = match image.format() {
3178            RegisteredImageFormat::Rgba8 => wgpu::TextureFormat::Rgba8UnormSrgb,
3179        };
3180        let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
3181            label: Some("SUI image texture"),
3182            size: wgpu::Extent3d {
3183                width: image.width(),
3184                height: image.height(),
3185                depth_or_array_layers: 1,
3186            },
3187            mip_level_count: 1,
3188            sample_count: 1,
3189            dimension: wgpu::TextureDimension::D2,
3190            format: texture_format,
3191            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3192            view_formats: &[],
3193        });
3194        Self::write_registered_image_texture(&shared.queue, &texture, image);
3195        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3196        let linear_bind_group =
3197            Self::create_image_bind_group(shared, &view, &shared.image_linear_sampler);
3198        let nearest_bind_group =
3199            Self::create_image_bind_group(shared, &view, &shared.image_nearest_sampler);
3200        let bind_group = match sampling {
3201            ImageSampling::Nearest => nearest_bind_group.clone(),
3202            ImageSampling::Linear => linear_bind_group.clone(),
3203        };
3204
3205        self.image_cache.insert(
3206            handle,
3207            CachedImageTexture {
3208                texture,
3209                _view: view,
3210                linear_bind_group,
3211                nearest_bind_group,
3212                image: image.clone(),
3213            },
3214        );
3215
3216        Ok(bind_group)
3217    }
3218
3219    fn ensure_external_image_bind_group(
3220        &mut self,
3221        handle: ImageHandle,
3222        sampling: ImageSampling,
3223        descriptor: RegisteredExternalImage,
3224    ) -> Result<wgpu::BindGroup> {
3225        let entry = self
3226            .external_texture_registry
3227            .as_ref()
3228            .and_then(|registry| registry.resolve(handle))
3229            .ok_or_else(|| {
3230                Error::new(format!(
3231                    "external image handle {} has no WGPU texture registered",
3232                    handle.get()
3233                ))
3234            })?;
3235        if entry.descriptor != descriptor {
3236            return Err(Error::new(format!(
3237                "external image handle {} scene dimensions {}x{} do not match registered texture dimensions {}x{}",
3238                handle.get(),
3239                descriptor.width(),
3240                descriptor.height(),
3241                entry.descriptor.width(),
3242                entry.descriptor.height()
3243            )));
3244        }
3245
3246        if let Some(cached) = self.external_image_cache.get(&handle)
3247            && cached.binding_revision == entry.binding_revision
3248        {
3249            return Ok(Self::external_image_bind_group_for_sampling(
3250                cached, sampling,
3251            ));
3252        }
3253
3254        let shared = self
3255            .shared
3256            .as_ref()
3257            .expect("renderer shared state initialized");
3258        let linear_bind_group =
3259            Self::create_image_bind_group(shared, &entry.view, &shared.image_linear_sampler);
3260        let nearest_bind_group =
3261            Self::create_image_bind_group(shared, &entry.view, &shared.image_nearest_sampler);
3262        let bind_group = match sampling {
3263            ImageSampling::Nearest => nearest_bind_group.clone(),
3264            ImageSampling::Linear => linear_bind_group.clone(),
3265        };
3266        self.external_image_cache.insert(
3267            handle,
3268            CachedExternalTextureBindGroup {
3269                binding_revision: entry.binding_revision,
3270                linear_bind_group,
3271                nearest_bind_group,
3272            },
3273        );
3274        Ok(bind_group)
3275    }
3276
3277    fn image_bind_group_for_sampling(
3278        cached: &CachedImageTexture,
3279        sampling: ImageSampling,
3280    ) -> wgpu::BindGroup {
3281        match sampling {
3282            ImageSampling::Nearest => cached.nearest_bind_group.clone(),
3283            ImageSampling::Linear => cached.linear_bind_group.clone(),
3284        }
3285    }
3286
3287    fn external_image_bind_group_for_sampling(
3288        cached: &CachedExternalTextureBindGroup,
3289        sampling: ImageSampling,
3290    ) -> wgpu::BindGroup {
3291        match sampling {
3292            ImageSampling::Nearest => cached.nearest_bind_group.clone(),
3293            ImageSampling::Linear => cached.linear_bind_group.clone(),
3294        }
3295    }
3296
3297    fn create_image_bind_group(
3298        shared: &SharedRenderer,
3299        view: &wgpu::TextureView,
3300        sampler: &wgpu::Sampler,
3301    ) -> wgpu::BindGroup {
3302        shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
3303            label: Some("SUI image bind group"),
3304            layout: &shared.image_bind_group_layout,
3305            entries: &[
3306                wgpu::BindGroupEntry {
3307                    binding: 0,
3308                    resource: wgpu::BindingResource::Sampler(sampler),
3309                },
3310                wgpu::BindGroupEntry {
3311                    binding: 1,
3312                    resource: wgpu::BindingResource::TextureView(view),
3313                },
3314            ],
3315        })
3316    }
3317
3318    fn ensure_text_atlas_bind_group(
3319        &mut self,
3320        text_engine: &mut TextEngine,
3321        collect_stats: bool,
3322    ) -> Result<(wgpu::BindGroup, TextAtlasBindGroupStats)> {
3323        let total_started = collect_stats.then(Instant::now);
3324        let upload_copy_started = collect_stats.then(Instant::now);
3325        let uploads = text_engine.take_atlas_uploads();
3326        let page_size = text_engine.atlas.page_size();
3327        let page_count = text_engine.atlas.page_count() as u32;
3328        let mut stats = TextAtlasBindGroupStats {
3329            upload_copy_time_us: upload_copy_started
3330                .map(|started| started.elapsed().as_micros() as u64)
3331                .unwrap_or(0),
3332            upload_bytes: if collect_stats {
3333                uploads
3334                    .iter()
3335                    .map(|(_, upload)| upload.pixels.len() as u64)
3336                    .sum()
3337            } else {
3338                0
3339            },
3340            ..TextAtlasBindGroupStats::default()
3341        };
3342
3343        // One persistent texture array; each atlas page is a layer. Dirty rects are written
3344        // directly to their layer -- no ring rotation, no full-texture forward-copy.
3345        self.ensure_text_atlas_array(page_size, page_count)?;
3346
3347        if !uploads.is_empty() {
3348            let shared = self
3349                .shared
3350                .as_ref()
3351                .expect("renderer shared state initialized");
3352            let cached = self
3353                .text_atlas_array
3354                .as_ref()
3355                .expect("text atlas array created above");
3356            let upload_write_started = collect_stats.then(Instant::now);
3357            for (page_index, upload) in &uploads {
3358                shared.queue.write_texture(
3359                    wgpu::TexelCopyTextureInfo {
3360                        texture: &cached.texture,
3361                        mip_level: 0,
3362                        origin: wgpu::Origin3d {
3363                            x: upload.offset.0,
3364                            y: upload.offset.1,
3365                            z: *page_index as u32,
3366                        },
3367                        aspect: wgpu::TextureAspect::All,
3368                    },
3369                    &upload.pixels,
3370                    wgpu::TexelCopyBufferLayout {
3371                        offset: 0,
3372                        bytes_per_row: Some(upload.extent.0 * 4),
3373                        rows_per_image: Some(upload.extent.1),
3374                    },
3375                    wgpu::Extent3d {
3376                        width: upload.extent.0,
3377                        height: upload.extent.1,
3378                        depth_or_array_layers: 1,
3379                    },
3380                );
3381            }
3382            stats.upload_write_time_us = upload_write_started
3383                .map(|started| started.elapsed().as_micros() as u64)
3384                .unwrap_or(0);
3385        }
3386
3387        let bind_group = self
3388            .text_atlas_array
3389            .as_ref()
3390            .map(|cached| cached.bind_group.clone())
3391            .ok_or_else(|| Error::new("text atlas bind group requested before any atlas upload"))?;
3392        stats.total_time_us = total_started
3393            .map(|started| started.elapsed().as_micros() as u64)
3394            .unwrap_or(0);
3395        Ok((bind_group, stats))
3396    }
3397
3398    fn ensure_text_atlas_array(
3399        &mut self,
3400        page_size: (u32, u32),
3401        required_layers: u32,
3402    ) -> Result<()> {
3403        // Allocate only as many layers as there are live pages, growing on demand up to the page
3404        // budget. This keeps the common single-page case at one 16 MB layer instead of committing
3405        // the whole budget up front.
3406        let required_layers = required_layers.clamp(1, TEXT_ATLAS_MAX_PAGES as u32);
3407        if self
3408            .text_atlas_array
3409            .as_ref()
3410            .is_some_and(|cached| cached.size == page_size && cached.layers >= required_layers)
3411        {
3412            return Ok(());
3413        }
3414
3415        let shared = self
3416            .shared
3417            .as_ref()
3418            .expect("renderer shared state initialized before text atlas texture setup");
3419
3420        let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
3421            label: Some("SUI text atlas array texture"),
3422            size: wgpu::Extent3d {
3423                width: page_size.0,
3424                height: page_size.1,
3425                depth_or_array_layers: required_layers,
3426            },
3427            mip_level_count: 1,
3428            sample_count: 1,
3429            dimension: wgpu::TextureDimension::D2,
3430            format: wgpu::TextureFormat::Rgba8Unorm,
3431            usage: wgpu::TextureUsages::TEXTURE_BINDING
3432                | wgpu::TextureUsages::COPY_DST
3433                | wgpu::TextureUsages::COPY_SRC,
3434            view_formats: &[],
3435        });
3436        let view = texture.create_view(&wgpu::TextureViewDescriptor {
3437            dimension: Some(wgpu::TextureViewDimension::D2Array),
3438            ..Default::default()
3439        });
3440        let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
3441            label: Some("SUI text atlas array bind group"),
3442            layout: &shared.text_atlas_array_bind_group_layout,
3443            entries: &[
3444                wgpu::BindGroupEntry {
3445                    binding: 0,
3446                    resource: wgpu::BindingResource::Sampler(&shared.text_atlas_sampler),
3447                },
3448                wgpu::BindGroupEntry {
3449                    binding: 1,
3450                    resource: wgpu::BindingResource::TextureView(&view),
3451                },
3452            ],
3453        });
3454
3455        // Growing an existing array of the same page size: copy the already-populated layers
3456        // forward so their glyphs survive (their CPU dirty state was cleared after first upload).
3457        if let Some(old) = self.text_atlas_array.as_ref()
3458            && old.size == page_size
3459        {
3460            let mut encoder =
3461                shared
3462                    .device
3463                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3464                        label: Some("SUI text atlas array grow copy"),
3465                    });
3466            encoder.copy_texture_to_texture(
3467                wgpu::TexelCopyTextureInfo {
3468                    texture: &old.texture,
3469                    mip_level: 0,
3470                    origin: wgpu::Origin3d::ZERO,
3471                    aspect: wgpu::TextureAspect::All,
3472                },
3473                wgpu::TexelCopyTextureInfo {
3474                    texture: &texture,
3475                    mip_level: 0,
3476                    origin: wgpu::Origin3d::ZERO,
3477                    aspect: wgpu::TextureAspect::All,
3478                },
3479                wgpu::Extent3d {
3480                    width: page_size.0,
3481                    height: page_size.1,
3482                    depth_or_array_layers: old.layers,
3483                },
3484            );
3485            shared.queue.submit([encoder.finish()]);
3486        }
3487
3488        self.text_atlas_array = Some(CachedTextAtlasTexture {
3489            texture,
3490            _view: view,
3491            bind_group,
3492            size: page_size,
3493            layers: required_layers,
3494        });
3495
3496        Ok(())
3497    }
3498
3499    fn prepare_analytic_path_resources(
3500        &mut self,
3501        analytic_paths: HashMap<u64, Arc<AnalyticPathCpuData>>,
3502        collect_stats: bool,
3503    ) -> Result<(
3504        Option<PreparedAnalyticPathResources>,
3505        AnalyticPathBindGroupStats,
3506    )> {
3507        if analytic_paths.is_empty() {
3508            return Ok((None, AnalyticPathBindGroupStats::default()));
3509        }
3510
3511        let total_started = collect_stats.then(Instant::now);
3512        let shared = self
3513            .shared
3514            .as_ref()
3515            .expect("renderer shared state initialized");
3516        let mut slots = HashMap::with_capacity(analytic_paths.len());
3517        let mut pending = Vec::new();
3518        let mut visible_signatures = Vec::with_capacity(analytic_paths.len());
3519        let mut sorted_paths: Vec<_> = analytic_paths.into_iter().collect();
3520        sorted_paths.sort_unstable_by_key(|(signature, _)| *signature);
3521
3522        for (signature, path) in sorted_paths {
3523            visible_signatures.push(signature);
3524            if let Some(cached) = self.analytic_path_cache.get_mut(&signature) {
3525                cached.last_used_frame = self.frames_rendered;
3526                slots.insert(signature, cached.slot);
3527            } else {
3528                pending.push((signature, path));
3529            }
3530        }
3531
3532        let mut stats = AnalyticPathBindGroupStats {
3533            miss_count: if collect_stats { pending.len() } else { 0 },
3534            ..AnalyticPathBindGroupStats::default()
3535        };
3536        let needs_rebuild = if self
3537            .frame_resources
3538            .analytic_path_arena
3539            .bind_group
3540            .is_none()
3541        {
3542            true
3543        } else if pending.is_empty() {
3544            false
3545        } else {
3546            let required_slots =
3547                self.frame_resources.analytic_path_arena.used_slots + pending.len();
3548            let required_contours = self.frame_resources.analytic_path_arena.used_contours
3549                + pending
3550                    .iter()
3551                    .map(|(_, path)| path.contours.len())
3552                    .sum::<usize>();
3553            let required_points = self.frame_resources.analytic_path_arena.used_points
3554                + pending
3555                    .iter()
3556                    .map(|(_, path)| path.points.len())
3557                    .sum::<usize>();
3558            !self.frame_resources.analytic_path_arena.has_capacity(
3559                required_slots,
3560                required_contours,
3561                required_points,
3562            )
3563        };
3564
3565        if needs_rebuild {
3566            let mut cached_entries: Vec<_> = self
3567                .analytic_path_cache
3568                .iter()
3569                .map(|(signature, entry)| {
3570                    (
3571                        *signature,
3572                        entry.slot,
3573                        entry.last_used_frame,
3574                        entry.data.clone(),
3575                    )
3576                })
3577                .collect();
3578            cached_entries.sort_unstable_by_key(|(_, slot, _, _)| *slot);
3579
3580            let total_slots = cached_entries.len() + pending.len();
3581            let total_contours = cached_entries
3582                .iter()
3583                .map(|(_, _, _, data)| data.contours.len())
3584                .sum::<usize>()
3585                + pending
3586                    .iter()
3587                    .map(|(_, data)| data.contours.len())
3588                    .sum::<usize>();
3589            let total_points = cached_entries
3590                .iter()
3591                .map(|(_, _, _, data)| data.points.len())
3592                .sum::<usize>()
3593                + pending
3594                    .iter()
3595                    .map(|(_, data)| data.points.len())
3596                    .sum::<usize>();
3597
3598            self.frame_resources.analytic_path_arena.ensure_capacity(
3599                &shared.device,
3600                &shared.analytic_path_bind_group_layout,
3601                total_slots,
3602                total_contours,
3603                total_points,
3604            );
3605
3606            let mut meta_data = Vec::with_capacity(total_slots);
3607            let mut contour_data = Vec::with_capacity(total_contours);
3608            let mut point_data = Vec::with_capacity(total_points);
3609            let mut rebuilt_cache = HashMap::with_capacity(total_slots);
3610
3611            for (signature, _, last_used_frame, data) in cached_entries {
3612                let slot = meta_data.len() as u32;
3613                let contour_start = contour_data.len() as u32;
3614                let point_start = point_data.len() as u32;
3615                meta_data.push(data.meta(contour_start, point_start));
3616                contour_data.extend_from_slice(&data.contours);
3617                point_data.extend_from_slice(&data.points);
3618                rebuilt_cache.insert(
3619                    signature,
3620                    CachedAnalyticPathGpu {
3621                        data,
3622                        slot,
3623                        last_used_frame,
3624                    },
3625                );
3626            }
3627
3628            for (signature, data) in pending {
3629                let slot = meta_data.len() as u32;
3630                let contour_start = contour_data.len() as u32;
3631                let point_start = point_data.len() as u32;
3632                meta_data.push(data.meta(contour_start, point_start));
3633                contour_data.extend_from_slice(&data.contours);
3634                point_data.extend_from_slice(&data.points);
3635                rebuilt_cache.insert(
3636                    signature,
3637                    CachedAnalyticPathGpu {
3638                        data,
3639                        slot,
3640                        last_used_frame: self.frames_rendered,
3641                    },
3642                );
3643            }
3644
3645            let meta_buffer = self
3646                .frame_resources
3647                .analytic_path_arena
3648                .meta_buffer
3649                .as_ref()
3650                .expect("analytic path arena metadata buffer initialized");
3651            let contour_buffer = self
3652                .frame_resources
3653                .analytic_path_arena
3654                .contour_buffer
3655                .as_ref()
3656                .expect("analytic path arena contour buffer initialized");
3657            let point_buffer = self
3658                .frame_resources
3659                .analytic_path_arena
3660                .point_buffer
3661                .as_ref()
3662                .expect("analytic path arena point buffer initialized");
3663            if !meta_data.is_empty() {
3664                shared
3665                    .queue
3666                    .write_buffer(meta_buffer, 0, bytemuck::cast_slice(&meta_data));
3667            }
3668            if !contour_data.is_empty() {
3669                shared
3670                    .queue
3671                    .write_buffer(contour_buffer, 0, bytemuck::cast_slice(&contour_data));
3672            }
3673            if !point_data.is_empty() {
3674                shared
3675                    .queue
3676                    .write_buffer(point_buffer, 0, bytemuck::cast_slice(&point_data));
3677            }
3678
3679            if collect_stats {
3680                stats.upload_bytes = (meta_data.len() * std::mem::size_of::<AnalyticPathMetaGpu>()
3681                    + contour_data.len() * std::mem::size_of::<AnalyticContourGpu>()
3682                    + point_data.len() * std::mem::size_of::<AnalyticPointGpu>())
3683                    as u64;
3684            }
3685
3686            self.analytic_path_cache = rebuilt_cache;
3687            self.frame_resources.analytic_path_arena.used_slots = meta_data.len();
3688            self.frame_resources.analytic_path_arena.used_contours = contour_data.len();
3689            self.frame_resources.analytic_path_arena.used_points = point_data.len();
3690
3691            for signature in visible_signatures {
3692                let slot = self
3693                    .analytic_path_cache
3694                    .get(&signature)
3695                    .expect("visible analytic path cached after arena rebuild")
3696                    .slot;
3697                slots.insert(signature, slot);
3698            }
3699        } else if !pending.is_empty() {
3700            let meta_buffer = self
3701                .frame_resources
3702                .analytic_path_arena
3703                .meta_buffer
3704                .as_ref()
3705                .expect("analytic path arena metadata buffer initialized");
3706            let contour_buffer = self
3707                .frame_resources
3708                .analytic_path_arena
3709                .contour_buffer
3710                .as_ref()
3711                .expect("analytic path arena contour buffer initialized");
3712            let point_buffer = self
3713                .frame_resources
3714                .analytic_path_arena
3715                .point_buffer
3716                .as_ref()
3717                .expect("analytic path arena point buffer initialized");
3718            let base_slot = self.frame_resources.analytic_path_arena.used_slots as u32;
3719            let base_contour = self.frame_resources.analytic_path_arena.used_contours as u32;
3720            let base_point = self.frame_resources.analytic_path_arena.used_points as u32;
3721            let total_contours = pending
3722                .iter()
3723                .map(|(_, data)| data.contours.len())
3724                .sum::<usize>();
3725            let total_points = pending
3726                .iter()
3727                .map(|(_, data)| data.points.len())
3728                .sum::<usize>();
3729            let mut meta_data = Vec::with_capacity(pending.len());
3730            let mut contour_data = Vec::with_capacity(total_contours);
3731            let mut point_data = Vec::with_capacity(total_points);
3732
3733            for (signature, data) in pending {
3734                let slot = base_slot + meta_data.len() as u32;
3735                let contour_start = base_contour + contour_data.len() as u32;
3736                let point_start = base_point + point_data.len() as u32;
3737                meta_data.push(data.meta(contour_start, point_start));
3738                contour_data.extend_from_slice(&data.contours);
3739                point_data.extend_from_slice(&data.points);
3740                if collect_stats {
3741                    stats.upload_bytes += data.byte_size() as u64;
3742                }
3743                slots.insert(signature, slot);
3744                self.analytic_path_cache.insert(
3745                    signature,
3746                    CachedAnalyticPathGpu {
3747                        data,
3748                        slot,
3749                        last_used_frame: self.frames_rendered,
3750                    },
3751                );
3752            }
3753
3754            if !meta_data.is_empty() {
3755                let meta_offset =
3756                    base_slot as u64 * std::mem::size_of::<AnalyticPathMetaGpu>() as u64;
3757                shared.queue.write_buffer(
3758                    meta_buffer,
3759                    meta_offset,
3760                    bytemuck::cast_slice(&meta_data),
3761                );
3762            }
3763            if !contour_data.is_empty() {
3764                let contour_offset =
3765                    base_contour as u64 * std::mem::size_of::<AnalyticContourGpu>() as u64;
3766                shared.queue.write_buffer(
3767                    contour_buffer,
3768                    contour_offset,
3769                    bytemuck::cast_slice(&contour_data),
3770                );
3771            }
3772            if !point_data.is_empty() {
3773                let point_offset =
3774                    base_point as u64 * std::mem::size_of::<AnalyticPointGpu>() as u64;
3775                shared.queue.write_buffer(
3776                    point_buffer,
3777                    point_offset,
3778                    bytemuck::cast_slice(&point_data),
3779                );
3780            }
3781
3782            self.frame_resources.analytic_path_arena.used_slots += meta_data.len();
3783            self.frame_resources.analytic_path_arena.used_contours += contour_data.len();
3784            self.frame_resources.analytic_path_arena.used_points += point_data.len();
3785        }
3786
3787        let bind_group = self
3788            .frame_resources
3789            .analytic_path_arena
3790            .bind_group
3791            .as_ref()
3792            .expect("analytic path arena bind group initialized")
3793            .clone();
3794        stats.total_time_us = total_started
3795            .map(|started| started.elapsed().as_micros() as u64)
3796            .unwrap_or(0);
3797        Ok((
3798            Some(PreparedAnalyticPathResources { bind_group, slots }),
3799            stats,
3800        ))
3801    }
3802
3803    fn create_surface_state(
3804        &mut self,
3805        window: Arc<Window>,
3806        size: (u32, u32),
3807    ) -> Result<SurfaceState> {
3808        let surface = self
3809            .instance
3810            .create_surface(Arc::clone(&window))
3811            .map_err(|error| Error::new(format!("failed to create wgpu surface: {error}")))?;
3812        self.ensure_shared(Some(&surface))?;
3813
3814        let shared = self
3815            .shared
3816            .as_ref()
3817            .expect("renderer shared state initialized");
3818        let default_capabilities = DisplayCapabilities::default();
3819        let default_color_management = ColorManagementMode::default();
3820        let available_surface_formats = surface.get_capabilities(&shared.adapter).formats;
3821        let (config, output_strategy) = configure_surface(
3822            &surface,
3823            &shared.adapter,
3824            &shared.device,
3825            size,
3826            self.vsync_enabled,
3827            default_capabilities.clone(),
3828            default_color_management,
3829        )?;
3830
3831        Ok(SurfaceState {
3832            window,
3833            surface,
3834            config,
3835            display_capabilities: default_capabilities,
3836            color_management: default_color_management,
3837            output_strategy,
3838            available_surface_formats,
3839        })
3840    }
3841}
3842
3843/// Build the renderer's wgpu instance with the GL backend left out unless the
3844/// environment explicitly asks for it (`WGPU_BACKEND=gl`).
3845///
3846/// Initializing the GL/WGL backend spins up a device thread per instance, and
3847/// concurrent initialization — one renderer per test in the headless harness —
3848/// deadlocks inside some Windows OpenGL drivers (observed as all test threads
3849/// parked on `wgl::create_instance_device` results while the creator threads
3850/// sat inside `nvoglv64.dll`; the same churn also produces access-violation
3851/// crashes). The primary native backends (Vulkan/Metal/DX12) cover every
3852/// platform SUI supports, so GL is opt-in rather than eagerly probed.
3853fn default_wgpu_instance() -> wgpu::Instance {
3854    let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle_from_env();
3855    if std::env::var_os("WGPU_BACKEND").is_none() {
3856        descriptor.backends -= wgpu::Backends::GL;
3857    }
3858    wgpu::Instance::new(descriptor)
3859}
3860
3861impl Default for WgpuRenderer {
3862    fn default() -> Self {
3863        Self {
3864            instance: default_wgpu_instance(),
3865            feathering_enabled: false,
3866            feather_width: DEFAULT_FEATHER_WIDTH,
3867            text_render_mode: TextRenderMode::default(),
3868            text_subpixel_order: TextSubpixelOrder::default(),
3869            text_hinting: TextHinting::default(),
3870            stem_darkening: StemDarkening::default(),
3871            text_coverage_policy: TextCoveragePolicy::default(),
3872            vsync_enabled: true,
3873            runtime_feathering_override: None,
3874            runtime_text_subpixel_order_override: None,
3875            runtime_text_hinting_override: None,
3876            runtime_stem_darkening_override: None,
3877            runtime_text_coverage_policy_override: None,
3878            runtime_diagnostics_enabled: true,
3879            frames_rendered: 0,
3880            capabilities: RendererCapabilities::default(),
3881            last_frames: HashMap::new(),
3882            last_frame_stats: HashMap::new(),
3883            shared: None,
3884            text_engine: None,
3885            image_cache: HashMap::new(),
3886            external_texture_registry: None,
3887            external_image_cache: HashMap::new(),
3888            text_atlas_array: None,
3889            analytic_path_cache: HashMap::new(),
3890            compositors: HashMap::new(),
3891            surfaces: HashMap::new(),
3892            offscreen_targets: HashMap::new(),
3893            intermediate_targets: HashMap::new(),
3894            frame_resources: FrameResources::default(),
3895        }
3896    }
3897}
3898
3899impl fmt::Debug for WgpuRenderer {
3900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3901        f.debug_struct("WgpuRenderer")
3902            .field("feathering_enabled", &self.feathering_enabled)
3903            .field("feather_width", &self.feather_width)
3904            .field("text_coverage_policy", &self.text_coverage_policy)
3905            .field("frames_rendered", &self.frames_rendered)
3906            .field("capabilities", &self.capabilities)
3907            .field("last_frame_count", &self.last_frames.len())
3908            .field("last_frame_stats_count", &self.last_frame_stats.len())
3909            .field("has_device", &self.shared.is_some())
3910            .field("surface_count", &self.surfaces.len())
3911            .finish()
3912    }
3913}
3914
3915impl FrameResources {
3916    fn ensure_stencil(&mut self, device: &wgpu::Device, size: (u32, u32)) {
3917        let needs_recreate = self
3918            .stencil
3919            .as_ref()
3920            .is_none_or(|target| target.size != size);
3921        if !needs_recreate {
3922            return;
3923        }
3924
3925        let texture = device.create_texture(&wgpu::TextureDescriptor {
3926            label: Some("SUI scene stencil"),
3927            size: wgpu::Extent3d {
3928                width: size.0,
3929                height: size.1,
3930                depth_or_array_layers: 1,
3931            },
3932            mip_level_count: 1,
3933            sample_count: 1,
3934            dimension: wgpu::TextureDimension::D2,
3935            format: STENCIL_FORMAT,
3936            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3937            view_formats: &[],
3938        });
3939        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3940        self.stencil = Some(StencilTarget {
3941            texture,
3942            view,
3943            size,
3944        });
3945    }
3946}
3947
3948impl AnalyticPathArena {
3949    fn has_capacity(&self, meta_count: usize, contour_count: usize, point_count: usize) -> bool {
3950        self.bind_group.is_some()
3951            && self.meta_capacity >= meta_count
3952            && self.contour_capacity >= contour_count
3953            && self.point_capacity >= point_count
3954    }
3955
3956    fn ensure_capacity(
3957        &mut self,
3958        device: &wgpu::Device,
3959        layout: &wgpu::BindGroupLayout,
3960        meta_count: usize,
3961        contour_count: usize,
3962        point_count: usize,
3963    ) {
3964        if self.has_capacity(meta_count, contour_count, point_count) {
3965            return;
3966        }
3967
3968        let meta_capacity = grow_analytic_path_capacity(self.meta_capacity, meta_count);
3969        let contour_capacity = grow_analytic_path_capacity(self.contour_capacity, contour_count);
3970        let point_capacity = grow_analytic_path_capacity(self.point_capacity, point_count);
3971
3972        let meta_buffer = device.create_buffer(&wgpu::BufferDescriptor {
3973            label: Some("SUI analytic path metadata arena"),
3974            size: analytic_path_buffer_size::<AnalyticPathMetaGpu>(meta_capacity),
3975            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
3976            mapped_at_creation: false,
3977        });
3978        let contour_buffer = device.create_buffer(&wgpu::BufferDescriptor {
3979            label: Some("SUI analytic path contour arena"),
3980            size: analytic_path_buffer_size::<AnalyticContourGpu>(contour_capacity),
3981            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
3982            mapped_at_creation: false,
3983        });
3984        let point_buffer = device.create_buffer(&wgpu::BufferDescriptor {
3985            label: Some("SUI analytic path point arena"),
3986            size: analytic_path_buffer_size::<AnalyticPointGpu>(point_capacity),
3987            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
3988            mapped_at_creation: false,
3989        });
3990        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
3991            label: Some("SUI analytic path arena bind group"),
3992            layout,
3993            entries: &[
3994                wgpu::BindGroupEntry {
3995                    binding: 0,
3996                    resource: meta_buffer.as_entire_binding(),
3997                },
3998                wgpu::BindGroupEntry {
3999                    binding: 1,
4000                    resource: contour_buffer.as_entire_binding(),
4001                },
4002                wgpu::BindGroupEntry {
4003                    binding: 2,
4004                    resource: point_buffer.as_entire_binding(),
4005                },
4006            ],
4007        });
4008
4009        self.bind_group = Some(bind_group);
4010        self.meta_buffer = Some(meta_buffer);
4011        self.contour_buffer = Some(contour_buffer);
4012        self.point_buffer = Some(point_buffer);
4013        self.meta_capacity = meta_capacity;
4014        self.contour_capacity = contour_capacity;
4015        self.point_capacity = point_capacity;
4016    }
4017}
4018
4019const SHADER_SOURCE: &str = r#"
4020struct VsOut {
4021    @builtin(position) position: vec4<f32>,
4022    @location(0) color: vec4<f32>,
4023    @location(1) local_position: vec2<f32>,
4024    @location(2) rect_params: vec4<f32>,
4025};
4026
4027@vertex
4028fn vs_main(
4029    @location(0) position: vec2<f32>,
4030    @location(1) color: vec4<f32>,
4031    @location(2) tex_coords: vec2<f32>,
4032    @location(3) shader_params: vec4<f32>,
4033) -> VsOut {
4034    var out: VsOut;
4035    out.position = vec4<f32>(position, 0.0, 1.0);
4036    out.color = color;
4037    out.local_position = tex_coords;
4038    out.rect_params = shader_params;
4039    return out;
4040}
4041
4042@fragment
4043fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4044    let feather_width = in.rect_params.z;
4045    let p = in.local_position;
4046    let derivative_width = length(vec2<f32>(fwidth(p.x), fwidth(p.y)));
4047    if feather_width > 0.0 {
4048        let size = max(in.rect_params.xy, vec2<f32>(0.0));
4049        let outside_distance = max(
4050            max(-p.x, p.x - size.x),
4051            max(-p.y, p.y - size.y),
4052        );
4053        let feather = max(feather_width, derivative_width);
4054        let coverage = select(
4055            clamp(1.0 - (outside_distance / max(feather, 1e-4)), 0.0, 1.0),
4056            1.0,
4057            outside_distance <= 0.0,
4058        );
4059        return vec4<f32>(in.color.rgb, in.color.a * coverage);
4060    }
4061    return in.color;
4062}
4063"#;
4064
4065const TEXTURED_SHADER_SOURCE: &str = r#"
4066struct VsOut {
4067    @builtin(position) position: vec4<f32>,
4068    @location(0) color: vec4<f32>,
4069    @location(1) tex_coords: vec2<f32>,
4070};
4071
4072@group(0) @binding(0)
4073var image_sampler: sampler;
4074
4075@group(0) @binding(1)
4076var image_texture: texture_2d<f32>;
4077
4078@vertex
4079fn vs_main(
4080    @location(0) position: vec2<f32>,
4081    @location(1) color: vec4<f32>,
4082    @location(2) tex_coords: vec2<f32>,
4083) -> VsOut {
4084    var out: VsOut;
4085    out.position = vec4<f32>(position, 0.0, 1.0);
4086    out.color = color;
4087    out.tex_coords = tex_coords;
4088    return out;
4089}
4090
4091@fragment
4092fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4093    return textureSample(image_texture, image_sampler, in.tex_coords) * in.color;
4094}
4095"#;
4096
4097const WIDGET_SHADER_SOURCE: &str = r#"
4098struct VsOut {
4099    @builtin(position) position: vec4<f32>,
4100    @location(0) metadata: vec4<f32>,
4101    @location(1) uv: vec2<f32>,
4102    @location(2) params: vec4<f32>,
4103};
4104
4105const KIND_COLOR_WHEEL: u32 = 0u;
4106const KIND_HUE_BAR: u32 = 1u;
4107const KIND_SATURATION_VALUE_PLANE: u32 = 2u;
4108const KIND_SATURATION_BAR: u32 = 3u;
4109const KIND_VALUE_BAR: u32 = 4u;
4110const KIND_ALPHA_BAR: u32 = 5u;
4111const KIND_RGB_CHANNEL_BAR: u32 = 6u;
4112const TAU: f32 = 6.283185307179586;
4113const COLOR_SPACE_LINEAR_SRGB: u32 = 1u;
4114const COLOR_SPACE_DISPLAY_P3: u32 = 2u;
4115const COLOR_SPACE_LINEAR_DISPLAY_P3: u32 = 3u;
4116
4117@vertex
4118fn vs_main(
4119    @location(0) position: vec2<f32>,
4120    @location(1) metadata: vec4<f32>,
4121    @location(2) uv: vec2<f32>,
4122    @location(3) params: vec4<f32>,
4123) -> VsOut {
4124    var out: VsOut;
4125    out.position = vec4<f32>(position, 0.0, 1.0);
4126    out.metadata = metadata;
4127    out.uv = uv;
4128    out.params = params;
4129    return out;
4130}
4131
4132fn srgb_transfer_to_linear(channel: f32) -> f32 {
4133    if channel <= 0.04045 {
4134        return channel / 12.92;
4135    }
4136    return pow((channel + 0.055) / 1.055, 2.4);
4137}
4138
4139fn color_space_index(space: f32) -> u32 {
4140    return u32(space + 0.5);
4141}
4142
4143fn to_linear_srgb(rgb: vec3<f32>, space: f32) -> vec3<f32> {
4144    let index = color_space_index(space);
4145    var linear = rgb;
4146    if index != COLOR_SPACE_LINEAR_SRGB && index != COLOR_SPACE_LINEAR_DISPLAY_P3 {
4147        linear = vec3<f32>(
4148            srgb_transfer_to_linear(rgb.r),
4149            srgb_transfer_to_linear(rgb.g),
4150            srgb_transfer_to_linear(rgb.b),
4151        );
4152    }
4153    if index == COLOR_SPACE_DISPLAY_P3 || index == COLOR_SPACE_LINEAR_DISPLAY_P3 {
4154        return vec3<f32>(
4155            1.2249402 * linear.r - 0.22494018 * linear.g,
4156            -0.042056955 * linear.r + 1.042057 * linear.g,
4157            -0.019637555 * linear.r - 0.07863604 * linear.g + 1.0982736 * linear.b,
4158        );
4159    }
4160    return linear;
4161}
4162
4163fn hsv_to_rgb(hue_value: f32, saturation: f32, value: f32) -> vec3<f32> {
4164    let hue = fract(hue_value) * 6.0;
4165    let sector = floor(hue);
4166    let fraction = hue - sector;
4167    let p = value * (1.0 - saturation);
4168    let q = value * (1.0 - fraction * saturation);
4169    let t = value * (1.0 - (1.0 - fraction) * saturation);
4170    if sector < 1.0 {
4171        return vec3<f32>(value, t, p);
4172    }
4173    if sector < 2.0 {
4174        return vec3<f32>(q, value, p);
4175    }
4176    if sector < 3.0 {
4177        return vec3<f32>(p, value, t);
4178    }
4179    if sector < 4.0 {
4180        return vec3<f32>(p, q, value);
4181    }
4182    if sector < 5.0 {
4183        return vec3<f32>(t, p, value);
4184    }
4185    return vec3<f32>(value, p, q);
4186}
4187
4188fn hsv_to_linear_color(space: f32, hue: f32, saturation: f32, value: f32, alpha: f32) -> vec4<f32> {
4189    return vec4<f32>(to_linear_srgb(hsv_to_rgb(hue, saturation, value), space), clamp(alpha, 0.0, 1.0));
4190}
4191
4192fn hdr_slider_to_value(t: f32, max_value: f32) -> f32 {
4193    if max_value <= 1.0001 {
4194        return t;
4195    }
4196    if t <= 0.5 {
4197        return t * 2.0;
4198    }
4199    return pow(max(max_value, 1.0001), (t - 0.5) / 0.5);
4200}
4201
4202@fragment
4203fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4204    let kind = u32(in.metadata.x + 0.5);
4205    let space = in.metadata.y;
4206    let u = clamp(in.uv.x, 0.0, 1.0);
4207    let v = clamp(in.uv.y, 0.0, 1.0);
4208
4209    if kind == KIND_COLOR_WHEEL {
4210        let centered = vec2<f32>(u * 2.0 - 1.0, v * 2.0 - 1.0);
4211        let distance = length(centered);
4212        let edge = 0.01;
4213        let alpha = smoothstep(0.55, 0.55 + edge, distance) * (1.0 - smoothstep(1.0 - edge, 1.0, distance));
4214        let hue = fract((atan2(centered.y, centered.x) / TAU) + 1.0);
4215        let color = hsv_to_linear_color(0.0, hue, 1.0, 1.0, alpha);
4216        return color;
4217    }
4218
4219    if kind == KIND_HUE_BAR {
4220        return hsv_to_linear_color(0.0, u, 1.0, 1.0, 1.0);
4221    }
4222
4223    if kind == KIND_SATURATION_VALUE_PLANE {
4224        let hue = in.metadata.z;
4225        let max_value = in.metadata.w;
4226        let value = hdr_slider_to_value(1.0 - v, max_value);
4227        return hsv_to_linear_color(space, hue, u, value, 1.0);
4228    }
4229
4230    if kind == KIND_SATURATION_BAR {
4231        let hue = in.metadata.z;
4232        let value = in.metadata.w;
4233        return hsv_to_linear_color(space, hue, u, value, 1.0);
4234    }
4235
4236    if kind == KIND_VALUE_BAR {
4237        let hue = in.metadata.z;
4238        let saturation = in.metadata.w;
4239        let value = hdr_slider_to_value(u, in.params.x);
4240        return hsv_to_linear_color(space, hue, saturation, value, 1.0);
4241    }
4242
4243    if kind == KIND_ALPHA_BAR {
4244        let alpha = u;
4245        return vec4<f32>(to_linear_srgb(in.params.rgb, space), alpha);
4246    }
4247
4248    if kind == KIND_RGB_CHANNEL_BAR {
4249        let channel = u32(in.metadata.z + 0.5);
4250        let max_value = in.metadata.w;
4251        var rgb = in.params.rgb;
4252        if channel == 0u {
4253            rgb.r = max_value * u;
4254        } else if channel == 1u {
4255            rgb.g = max_value * u;
4256        } else {
4257            rgb.b = max_value * u;
4258        }
4259        return vec4<f32>(to_linear_srgb(rgb, space), 1.0);
4260    }
4261
4262    return vec4<f32>(0.0, 0.0, 0.0, 0.0);
4263}
4264"#;
4265
4266const ROUNDED_RECT_SHADER_SOURCE: &str = r#"
4267const RR_MODE_FILL: f32 = 0.0;
4268const RR_MODE_SHADOW: f32 = 1.0;
4269struct VsOut {
4270    @builtin(position) position: vec4<f32>,
4271    @location(0) color: vec4<f32>, @location(1) local: vec2<f32>,
4272    @location(2) p0: vec4<f32>, @location(3) radii: vec4<f32>,
4273    @location(4) p2: vec4<f32>, @location(5) border_color: vec4<f32>,
4274};
4275@vertex
4276fn vs_main(@location(0) position: vec2<f32>, @location(1) color: vec4<f32>,
4277    @location(2) local: vec2<f32>, @location(3) p0: vec4<f32>, @location(4) radii: vec4<f32>,
4278    @location(5) p2: vec4<f32>, @location(6) border_color: vec4<f32>) -> VsOut {
4279    var out: VsOut; out.position = vec4<f32>(position, 0.0, 1.0);
4280    out.color = color; out.local = local; out.p0 = p0; out.radii = radii; out.p2 = p2; out.border_color = border_color;
4281    return out;
4282}
4283fn sd_round_box(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>) -> f32 {
4284    let rt = select(r.x, r.y, p.x > 0.0);
4285    let rb = select(r.w, r.z, p.x > 0.0);
4286    let rr = select(rt, rb, p.y > 0.0);
4287    let q = abs(p) - b + vec2<f32>(rr, rr);
4288    return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - rr;
4289}
4290fn gaussian_box_coverage(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>, sigma: f32) -> f32 {
4291    let s = max(sigma, 1e-3); let d = sd_round_box(p, b, r); let edge = 1.4142136 * s;
4292    return 1.0 - smoothstep(-edge, edge, d);
4293}
4294@fragment
4295fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4296    let half = max(in.p0.xy, vec2<f32>(0.0));
4297    let mode = in.p0.z; let feather = in.p0.w;
4298    let radii = clamp(in.radii, vec4<f32>(0.0), vec4<f32>(min(half.x, half.y)));
4299    let p = in.local;
4300    // Derivatives must execute in uniform control flow on WebGPU. Compute the
4301    // fill edge before selecting the shadow path; the shadow branch simply
4302    // leaves the derivative result unused.
4303    let d = sd_round_box(p, half, radii);
4304    let aa = max(feather, fwidth(d));
4305    if (mode == RR_MODE_SHADOW) {
4306        let sigma = in.p2.y;
4307        let pp = p - vec2<f32>(in.p2.z, in.p2.w);
4308        let cov = gaussian_box_coverage(pp, half, radii, sigma);
4309        return vec4<f32>(in.color.rgb, in.color.a * cov);
4310    }
4311    let fill_cov = clamp(0.5 - d / max(aa, 1e-4), 0.0, 1.0);
4312    let bw = in.p2.x;
4313    if (bw > 0.0) {
4314        let inner_cov = clamp(0.5 - (d + bw) / max(aa, 1e-4), 0.0, 1.0);
4315        let ring = clamp(fill_cov - inner_cov, 0.0, 1.0);
4316        let interior = inner_cov;
4317        let a = in.border_color.a * ring + in.color.a * interior;
4318        if (a <= 0.0) { return vec4<f32>(0.0); }
4319        let rgb = in.border_color.rgb * (in.border_color.a * ring) + in.color.rgb * (in.color.a * interior);
4320        return vec4<f32>(rgb / a, a);
4321    }
4322    return vec4<f32>(in.color.rgb, in.color.a * fill_cov);
4323}
4324"#;
4325
4326// Linear-gradient brush. The gradient is packed entirely into vertex attributes
4327// (bind-group-free, like the rounded-rect pipeline): two stops carried in `color`
4328// (stop 0, linear) and `border_color` (stop 1, linear); the gradient axis end-points
4329// (rect-local) in p2 = [start.x, start.y, end.x, end.y]. Coverage reuses the rounded
4330// rect SDF so the same pipeline fills both sharp FillRect (radii = 0) and rounded fills.
4331const GRADIENT_RECT_SHADER_SOURCE: &str = r#"
4332struct VsOut {
4333    @builtin(position) position: vec4<f32>,
4334    @location(0) stop0: vec4<f32>, @location(1) local: vec2<f32>,
4335    @location(2) p0: vec4<f32>, @location(3) radii: vec4<f32>,
4336    @location(4) axis: vec4<f32>, @location(5) stop1: vec4<f32>,
4337};
4338@vertex
4339fn vs_main(@location(0) position: vec2<f32>, @location(1) stop0: vec4<f32>,
4340    @location(2) local: vec2<f32>, @location(3) p0: vec4<f32>, @location(4) radii: vec4<f32>,
4341    @location(5) axis: vec4<f32>, @location(6) stop1: vec4<f32>) -> VsOut {
4342    var out: VsOut; out.position = vec4<f32>(position, 0.0, 1.0);
4343    out.stop0 = stop0; out.local = local; out.p0 = p0; out.radii = radii; out.axis = axis; out.stop1 = stop1;
4344    return out;
4345}
4346fn sd_round_box(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>) -> f32 {
4347    let rt = select(r.x, r.y, p.x > 0.0);
4348    let rb = select(r.w, r.z, p.x > 0.0);
4349    let rr = select(rt, rb, p.y > 0.0);
4350    let q = abs(p) - b + vec2<f32>(rr, rr);
4351    return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - rr;
4352}
4353@fragment
4354fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4355    let half = max(in.p0.xy, vec2<f32>(0.0));
4356    let feather = in.p0.w;
4357    let radii = clamp(in.radii, vec4<f32>(0.0), vec4<f32>(min(half.x, half.y)));
4358    let p = in.local; let d = sd_round_box(p, half, radii);
4359    let aa = max(feather, fwidth(d));
4360    let fill_cov = clamp(0.5 - d / max(aa, 1e-4), 0.0, 1.0);
4361    let a = in.axis.xy; let b = in.axis.zw;
4362    let ab = b - a; let denom = max(dot(ab, ab), 1e-6);
4363    let t = clamp(dot(in.local - a, ab) / denom, 0.0, 1.0);
4364    let col = mix(in.stop0, in.stop1, t);
4365    return vec4<f32>(col.rgb, col.a * fill_cov);
4366}
4367"#;
4368
4369const TEXT_ATLAS_SHADER_SOURCE: &str = r#"
4370struct VsOut {
4371    @builtin(position) position: vec4<f32>,
4372    @location(0) color: vec4<f32>,
4373    @location(1) tex_coords: vec2<f32>,
4374    @location(2) metadata: vec4<f32>,
4375    @location(3) @interpolate(flat) layer: u32,
4376    @location(4) uv_min: vec2<f32>,
4377    @location(5) uv_max: vec2<f32>,
4378};
4379
4380@group(0) @binding(0)
4381var text_atlas_sampler: sampler;
4382
4383@group(0) @binding(1)
4384var text_atlas_texture: texture_2d_array<f32>;
4385
4386@vertex
4387fn vs_main(
4388    @location(0) local_pos: vec2<f32>,
4389    @location(1) top_left: vec2<f32>,
4390    @location(2) x_axis: vec2<f32>,
4391    @location(3) y_axis: vec2<f32>,
4392    @location(4) uv_min: vec2<f32>,
4393    @location(5) uv_max: vec2<f32>,
4394    @location(6) color: vec4<f32>,
4395    @location(7) metadata: vec4<f32>,
4396    @location(8) layer: u32,
4397) -> VsOut {
4398    var out: VsOut;
4399    out.position = vec4<f32>(top_left + local_pos.x * x_axis + local_pos.y * y_axis, 0.0, 1.0);
4400    out.color = color;
4401    out.tex_coords = uv_min + local_pos * (uv_max - uv_min);
4402    out.metadata = metadata;
4403    out.layer = layer;
4404    out.uv_min = uv_min;
4405    out.uv_max = uv_max;
4406    return out;
4407}
4408
4409fn srgb_to_linear(color: vec3<f32>) -> vec3<f32> {
4410    let low = color / 12.92;
4411    let high = pow((color + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
4412    return select(high, low, color <= vec3<f32>(0.04045));
4413}
4414
4415fn apply_text_coverage(coverage: f32, policy: f32, parameter: f32) -> f32 {
4416    let c = clamp(coverage, 0.0, 1.0);
4417    if policy < 0.5 {
4418        return c;
4419    }
4420    if policy < 1.5 {
4421        return pow(c, max(parameter, 1e-4));
4422    }
4423    if policy < 2.5 {
4424        let amount = clamp(parameter, 0.0, 1.0);
4425        return c + (c * (1.0 - c) * amount);
4426    }
4427    if policy < 3.5 {
4428        return (2.0 * c) - (c * c);
4429    }
4430    return c;
4431}
4432
4433@fragment
4434fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4435    // Clamp the sample point to the glyph's half-texel-inset UV rect so bilinear taps at the quad
4436    // edges can't reach into neighbouring glyphs (or the padding) at non-integer scales.
4437    let atlas_half_texel = 0.5 / vec2<f32>(textureDimensions(text_atlas_texture));
4438    let clamped_uv = clamp(in.tex_coords, in.uv_min + atlas_half_texel, in.uv_max - atlas_half_texel);
4439    let sampled = textureSample(text_atlas_texture, text_atlas_sampler, clamped_uv, i32(in.layer));
4440    if in.color.a < 0.0 {
4441        let opacity = -in.color.a;
4442        let alpha = sampled.a * opacity;
4443        // Color/bitmap emoji glyphs carry their own RGB. Linearize the stored sRGB and premultiply.
4444        return vec4<f32>(srgb_to_linear(sampled.rgb) * alpha, alpha);
4445    }
4446
4447    if in.metadata.x > 0.5 {
4448        let coverage = vec3<f32>(
4449            apply_text_coverage(sampled.r, in.metadata.z, in.metadata.w),
4450            apply_text_coverage(sampled.g, in.metadata.z, in.metadata.w),
4451            apply_text_coverage(sampled.b, in.metadata.z, in.metadata.w),
4452        );
4453        let max_coverage = max(max(coverage.r, coverage.g), coverage.b);
4454        let premul = in.color.rgb * coverage * in.color.a;
4455        return vec4<f32>(premul, in.color.a * max_coverage);
4456    }
4457
4458    if in.metadata.y > 0.5 {
4459        let coverage = apply_text_coverage(
4460            (sampled.r + sampled.g + sampled.b) / 3.0,
4461            in.metadata.z,
4462            in.metadata.w,
4463        );
4464        let alpha = in.color.a * coverage;
4465        return vec4<f32>(in.color.rgb * alpha, alpha);
4466    }
4467
4468    let coverage = apply_text_coverage(sampled.a, in.metadata.z, in.metadata.w);
4469    let alpha = in.color.a * coverage;
4470    return vec4<f32>(in.color.rgb * alpha, alpha);
4471}
4472"#;
4473
4474const TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE: &str = r#"
4475enable dual_source_blending;
4476
4477struct VsOut {
4478    @builtin(position) position: vec4<f32>,
4479    @location(0) color: vec4<f32>,
4480    @location(1) tex_coords: vec2<f32>,
4481    @location(2) metadata: vec4<f32>,
4482    @location(3) @interpolate(flat) layer: u32,
4483    @location(4) uv_min: vec2<f32>,
4484    @location(5) uv_max: vec2<f32>,
4485};
4486
4487struct FragmentOutput {
4488    @location(0) @blend_src(0) foreground: vec4<f32>,
4489    @location(0) @blend_src(1) alpha: vec4<f32>,
4490};
4491
4492@group(0) @binding(0)
4493var text_atlas_sampler: sampler;
4494
4495@group(0) @binding(1)
4496var text_atlas_texture: texture_2d_array<f32>;
4497
4498@vertex
4499fn vs_main(
4500    @location(0) local_pos: vec2<f32>,
4501    @location(1) top_left: vec2<f32>,
4502    @location(2) x_axis: vec2<f32>,
4503    @location(3) y_axis: vec2<f32>,
4504    @location(4) uv_min: vec2<f32>,
4505    @location(5) uv_max: vec2<f32>,
4506    @location(6) color: vec4<f32>,
4507    @location(7) metadata: vec4<f32>,
4508    @location(8) layer: u32,
4509) -> VsOut {
4510    var out: VsOut;
4511    out.position = vec4<f32>(top_left + local_pos.x * x_axis + local_pos.y * y_axis, 0.0, 1.0);
4512    out.color = color;
4513    out.tex_coords = uv_min + local_pos * (uv_max - uv_min);
4514    out.metadata = metadata;
4515    out.layer = layer;
4516    out.uv_min = uv_min;
4517    out.uv_max = uv_max;
4518    return out;
4519}
4520
4521fn srgb_to_linear(color: vec3<f32>) -> vec3<f32> {
4522    let low = color / 12.92;
4523    let high = pow((color + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
4524    return select(high, low, color <= vec3<f32>(0.04045));
4525}
4526
4527fn apply_text_coverage(coverage: f32, policy: f32, parameter: f32) -> f32 {
4528    let c = clamp(coverage, 0.0, 1.0);
4529    if policy < 0.5 {
4530        return c;
4531    }
4532    if policy < 1.5 {
4533        return pow(c, max(parameter, 1e-4));
4534    }
4535    if policy < 2.5 {
4536        let amount = clamp(parameter, 0.0, 1.0);
4537        return c + (c * (1.0 - c) * amount);
4538    }
4539    if policy < 3.5 {
4540        return (2.0 * c) - (c * c);
4541    }
4542    return c;
4543}
4544
4545fn dual_source(foreground: vec3<f32>, alpha: vec3<f32>) -> FragmentOutput {
4546    var out: FragmentOutput;
4547    let source_alpha = max(max(alpha.r, alpha.g), alpha.b);
4548    out.foreground = vec4<f32>(foreground, source_alpha);
4549    out.alpha = vec4<f32>(alpha, 1.0);
4550    return out;
4551}
4552
4553@fragment
4554fn fs_main(in: VsOut) -> FragmentOutput {
4555    // Clamp the sample point to the glyph's half-texel-inset UV rect so bilinear taps at the quad
4556    // edges can't reach into neighbouring glyphs (or the padding) at non-integer scales.
4557    let atlas_half_texel = 0.5 / vec2<f32>(textureDimensions(text_atlas_texture));
4558    let clamped_uv = clamp(in.tex_coords, in.uv_min + atlas_half_texel, in.uv_max - atlas_half_texel);
4559    let sampled = textureSample(text_atlas_texture, text_atlas_sampler, clamped_uv, i32(in.layer));
4560    if in.color.a < 0.0 {
4561        let opacity = -in.color.a;
4562        // Color/bitmap emoji glyphs carry their own RGB. Linearize the stored sRGB before
4563        // premultiplying.
4564        return dual_source(srgb_to_linear(sampled.rgb), vec3<f32>(sampled.a * opacity));
4565    }
4566
4567    if in.metadata.x > 0.5 {
4568        let coverage = vec3<f32>(
4569            apply_text_coverage(sampled.r, in.metadata.z, in.metadata.w),
4570            apply_text_coverage(sampled.g, in.metadata.z, in.metadata.w),
4571            apply_text_coverage(sampled.b, in.metadata.z, in.metadata.w),
4572        );
4573        return dual_source(in.color.rgb, coverage * in.color.a);
4574    }
4575
4576    if in.metadata.y > 0.5 {
4577        let coverage = apply_text_coverage(
4578            (sampled.r + sampled.g + sampled.b) / 3.0,
4579            in.metadata.z,
4580            in.metadata.w,
4581        );
4582        return dual_source(in.color.rgb, vec3<f32>(coverage * in.color.a));
4583    }
4584
4585    let coverage = apply_text_coverage(sampled.a, in.metadata.z, in.metadata.w);
4586    return dual_source(in.color.rgb, vec3<f32>(coverage * in.color.a));
4587}
4588"#;
4589
4590const ANALYTIC_PATH_SHADER_SOURCE: &str = r#"
4591struct VsOut {
4592    @builtin(position) position: vec4<f32>,
4593    @location(0) color: vec4<f32>,
4594    @location(1) scene_position: vec2<f32>,
4595    @location(2) @interpolate(flat) path_index: u32,
4596};
4597
4598struct AnalyticPathMeta {
4599    contour_start: u32,
4600    contour_count: u32,
4601    point_start: u32,
4602    mode: u32,
4603    feather_width: f32,
4604    stroke_width: f32,
4605    _pad0: vec2<f32>,
4606};
4607
4608struct AnalyticContour {
4609    start: u32,
4610    len: u32,
4611    flags: u32,
4612    _pad0: u32,
4613};
4614
4615const ANALYTIC_CONTOUR_FLAG_CLOSED: u32 = 1u;
4616const ANALYTIC_PATH_MODE_FILL: u32 = 0u;
4617const ANALYTIC_PATH_MODE_STROKE: u32 = 1u;
4618
4619struct AnalyticPoint {
4620    position: vec2<f32>,
4621    _pad: vec2<f32>,
4622};
4623
4624@group(0) @binding(0)
4625var<storage, read> path_metas: array<AnalyticPathMeta>;
4626
4627@group(0) @binding(1)
4628var<storage, read> contours: array<AnalyticContour>;
4629
4630@group(0) @binding(2)
4631var<storage, read> points: array<AnalyticPoint>;
4632
4633@vertex
4634fn vs_main(
4635    @location(0) position: vec2<f32>,
4636    @location(1) color: vec4<f32>,
4637    @location(2) scene_position: vec2<f32>,
4638    @location(3) shader_params: vec4<f32>,
4639) -> VsOut {
4640    var out: VsOut;
4641    out.position = vec4<f32>(position, 0.0, 1.0);
4642    out.color = color;
4643    out.scene_position = scene_position;
4644    out.path_index = u32(shader_params.x + 0.5);
4645    return out;
4646}
4647
4648fn segment_distance(point: vec2<f32>, a: vec2<f32>, b: vec2<f32>) -> f32 {
4649    let ab = b - a;
4650    let denom = max(dot(ab, ab), 1e-5);
4651    let t = clamp(dot(point - a, ab) / denom, 0.0, 1.0);
4652    return length(point - (a + (ab * t)));
4653}
4654
4655@fragment
4656fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4657    let path_meta = path_metas[in.path_index];
4658    if path_meta.contour_count == 0u {
4659        return vec4<f32>(0.0, 0.0, 0.0, 0.0);
4660    }
4661
4662    let point = in.scene_position;
4663    var inside = false;
4664    var min_distance = 1e9;
4665
4666    for (var contour_index = 0u; contour_index < path_meta.contour_count; contour_index = contour_index + 1u) {
4667        let contour = contours[path_meta.contour_start + contour_index];
4668        if contour.len < 2u {
4669            continue;
4670        }
4671
4672        let closed = (contour.flags & ANALYTIC_CONTOUR_FLAG_CLOSED) != 0u;
4673        let point_start = path_meta.point_start + contour.start;
4674        var previous = select(
4675            points[point_start].position,
4676            points[point_start + contour.len - 1u].position,
4677            closed,
4678        );
4679        var start_index = select(1u, 0u, closed);
4680        for (var point_index = start_index; point_index < contour.len; point_index = point_index + 1u) {
4681            let current = points[point_start + point_index].position;
4682                let denom = previous.y - current.y;
4683                let safe_denom = select(
4684                    denom,
4685                    select(-1e-5, 1e-5, denom >= 0.0),
4686                    abs(denom) < 1e-5,
4687                );
4688            let intersects = ((current.y > point.y) != (previous.y > point.y))
4689                && (point.x < (((previous.x - current.x) * (point.y - current.y))
4690                / safe_denom) + current.x);
4691            if intersects {
4692                inside = !inside;
4693            }
4694
4695            min_distance = min(min_distance, segment_distance(point, previous, current));
4696            previous = current;
4697        }
4698    }
4699
4700    let derivative_width = length(vec2<f32>(fwidth(point.x), fwidth(point.y)));
4701    let feather = max(path_meta.feather_width, derivative_width);
4702    var coverage = 0.0;
4703
4704    if path_meta.mode == ANALYTIC_PATH_MODE_FILL {
4705        let signed_distance = select(min_distance, -min_distance, inside);
4706        coverage = clamp(0.5 - (signed_distance / max(feather, 1e-4)), 0.0, 1.0);
4707    } else {
4708        let half_width = max(0.0, 0.5 * path_meta.stroke_width);
4709        let edge_distance = min_distance - half_width;
4710        coverage = clamp(0.5 - (edge_distance / max(feather, 1e-4)), 0.0, 1.0);
4711    }
4712
4713    return vec4<f32>(in.color.rgb, in.color.a * coverage);
4714}
4715"#;
4716
4717const OUTPUT_TRANSFORM_SHADER_SOURCE: &str = r#"
4718struct VsOut {
4719    @builtin(position) position: vec4<f32>,
4720}
4721
4722struct OutputUniform {
4723    tone_mapping_mode: u32,
4724    encode_srgb: u32,
4725    output_primaries: u32,
4726    _padding2: u32,
4727    sdr_content_scale: f32,
4728    _padding3: u32,
4729    _padding4: u32,
4730    _padding5: u32,
4731}
4732
4733@group(0) @binding(0)
4734var scene_texture: texture_2d<f32>;
4735
4736@group(0) @binding(1)
4737var<uniform> output_uniform: OutputUniform;
4738
4739@vertex
4740fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VsOut {
4741    var positions = array<vec2<f32>, 3>(
4742        vec2<f32>(-1.0, -3.0),
4743        vec2<f32>(-1.0, 1.0),
4744        vec2<f32>(3.0, 1.0),
4745    );
4746    var out: VsOut;
4747    out.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
4748    return out;
4749}
4750
4751fn tone_map(color: vec3<f32>) -> vec3<f32> {
4752    let scaled = max(color, vec3<f32>(0.0)) * output_uniform.sdr_content_scale;
4753    switch output_uniform.tone_mapping_mode {
4754        case 0u: {
4755            return scaled;
4756        }
4757        case 2u: {
4758            return scaled / (vec3<f32>(1.0) + scaled);
4759        }
4760        default: {
4761            return clamp(scaled, vec3<f32>(0.0), vec3<f32>(1.0));
4762        }
4763    }
4764}
4765
4766fn linear_srgb_to_output_primaries(color: vec3<f32>) -> vec3<f32> {
4767    if output_uniform.output_primaries == 1u {
4768        return vec3<f32>(
4769            0.82246196 * color.r + 0.17753802 * color.g,
4770            0.0331942 * color.r + 0.96680576 * color.g,
4771            0.01708263 * color.r + 0.07239743 * color.g + 0.91051996 * color.b,
4772        );
4773    }
4774    return color;
4775}
4776
4777fn linear_to_srgb_channel(channel: f32) -> f32 {
4778    let value = max(channel, 0.0);
4779    if value <= 0.0031308 {
4780        return value * 12.92;
4781    }
4782    return (1.055 * pow(value, 1.0 / 2.4)) - 0.055;
4783}
4784
4785fn encode_for_output(color: vec3<f32>) -> vec3<f32> {
4786    if output_uniform.encode_srgb == 0u {
4787        return color;
4788    }
4789    return vec3<f32>(
4790        linear_to_srgb_channel(color.r),
4791        linear_to_srgb_channel(color.g),
4792        linear_to_srgb_channel(color.b),
4793    );
4794}
4795
4796@fragment
4797fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
4798    let dims = textureDimensions(scene_texture);
4799    let max_coord = vec2<i32>(max(vec2<u32>(1u), dims) - vec2<u32>(1u));
4800    let coords = clamp(vec2<i32>(position.xy), vec2<i32>(0), max_coord);
4801    let color = textureLoad(scene_texture, coords, 0);
4802    return vec4<f32>(
4803        encode_for_output(linear_srgb_to_output_primaries(tone_map(color.rgb))),
4804        clamp(color.a, 0.0, 1.0),
4805    );
4806}
4807"#;
4808
4809#[cfg(test)]
4810mod tests {
4811    use super::{
4812        ANALYTIC_PATH_SHADER_SOURCE, CachedGlyphAtlas, CachedGlyphMesh, ClipState,
4813        ColorManagementMode, CompositionContainerId, DEFAULT_FEATHER_WIDTH, DebugCaptureArtifact,
4814        DebugCaptureEncoding, DebugCaptureRequest, DebugCaptureStage, DebugSdrVisualization,
4815        DisplayCapabilities, DisplayColorPrimaries, DisplayTransferFunction, DrawOp, DrawOpArena,
4816        DrawOpKind, DynamicRangeMode, GlyphCacheKey, GlyphFaceCacheKey, GlyphSubpixelOffsetKey,
4817        HdrRgbaImage, OutputStrategy, PacketRebuildReason, PreparedClipPath, PreparedDrawBatch,
4818        PreparedDrawKind, PreparedFrameBatches, PreparedPassBatch, PreparedVertices,
4819        RendererFrameStats, RequestedColorManagementMode, RequestedDynamicRangeMode,
4820        RequestedOutputColorPrimaries, RequestedToneMappingMode, RetainedCompositorFrameStats,
4821        RetainedCompositorState, RetainedPacketId, RetainedPacketRebuildStats, RgbaImage,
4822        ScissorRect, StemDarkening, SwashImageContent, SwashSource, SwashStrikeWith,
4823        TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE, TEXT_ATLAS_SHADER_SOURCE, TextAtlasColorMode,
4824        TextAtlasPages, TextCoveragePolicy, TextEngine, TextHinting, TextRenderMode,
4825        TextSubpixelOrder, VERTEX_SIZE, Vertex, WgpuExternalTextureRegistry, WgpuRenderer,
4826        append_cached_path_mesh, batch_draw_ops, build_vertices, decode_rgba16f_pixels,
4827        encode_hdr_debug_artifact, hdr_image_to_sdr_rgba, prepare_frame_batches,
4828        scene::{
4829            CachedDrawBatch, CachedPassBatch, allows_lcd_text, append_cached_glyph_atlas,
4830            apply_output_transform_for_testing, apply_stem_darkening_to_coverage,
4831            convert_subpixel_texel_for_mode, glyph_raster_offset, glyph_subpixel_offset,
4832            output_transform_requires_intermediate, prepare_cached_passes, select_output_strategy,
4833            swash_image_to_rgba, tone_map_linear_color,
4834        },
4835        shader_color, strip_padded_readback_rows, to_ndc,
4836    };
4837    use std::sync::Arc;
4838    use sui_core::{
4839        Color, FontHandle, ImageHandle, Path, PathBuilder, Point, Rect, Size, Transform, Vector,
4840        WidgetId, WindowId,
4841    };
4842    use sui_scene::{
4843        Border, Brush, GradientStop, ImageRegistry, ImageSampling, ImageSource,
4844        LayerCompositionMode, RegisteredImage, Scene, SceneCommand, SceneFrame, SceneLayer,
4845        SceneLayerDescriptor, SceneLayerId, SceneLayerUpdate, SceneLayerUpdateKind, ShadowParams,
4846        StrokeStyle, TextRenderCoveragePolicy, TextRenderPolicy, WidgetShader,
4847    };
4848    use sui_text::{
4849        FontRegistry, RegisteredFont, ShapedGlyph, ShapedText, ShapedTextWindow,
4850        TextLayoutRegistry, TextRun, TextStyle, TextSystem,
4851    };
4852
4853    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4854    enum LayerCachePolicy {
4855        Auto,
4856        Direct,
4857        Cached,
4858    }
4859
4860    trait TestSceneLayerDescriptorExt {
4861        fn with_cache_policy(self, _cache_policy: LayerCachePolicy) -> Self;
4862    }
4863
4864    impl TestSceneLayerDescriptorExt for SceneLayerDescriptor {
4865        fn with_cache_policy(self, _cache_policy: LayerCachePolicy) -> Self {
4866            self
4867        }
4868    }
4869
4870    #[test]
4871    fn retained_packet_rebuild_stats_record_each_reason_and_preserve_grouping() {
4872        let mut rebuilds = RetainedPacketRebuildStats::default();
4873
4874        rebuilds.record_reason(PacketRebuildReason::NewPacket);
4875        rebuilds.record_reason(PacketRebuildReason::CoordinateSpace);
4876        rebuilds.record_reason(PacketRebuildReason::Signature);
4877        rebuilds.record_reason(PacketRebuildReason::Scene);
4878        rebuilds.record_reason(PacketRebuildReason::State);
4879
4880        assert_eq!(rebuilds, RetainedPacketRebuildStats::new(1, 1, 1, 1, 1));
4881        assert_eq!(rebuilds.total_count(), 5);
4882    }
4883
4884    #[test]
4885    fn renderer_frame_stats_with_compositor_stats_preserves_grouped_packet_rebuilds() {
4886        let stats = RendererFrameStats::from_prepared_counts(1, 2, 3).with_compositor_stats(
4887            RetainedCompositorFrameStats {
4888                packet_rebuilds: RetainedPacketRebuildStats::new(2, 3, 5, 7, 11),
4889                ..Default::default()
4890            },
4891        );
4892
4893        assert_eq!(
4894            stats.retained_packet_rebuilds,
4895            RetainedPacketRebuildStats::new(2, 3, 5, 7, 11)
4896        );
4897    }
4898
4899    #[test]
4900    fn debug_capture_stage_helpers_classify_hdr_and_final_outputs() {
4901        assert!(DebugCaptureStage::HdrIntermediate.is_hdr_capable());
4902        assert!(DebugCaptureStage::HdrIntermediate.uses_hdr_intermediate());
4903        assert!(!DebugCaptureStage::FinalComposed.is_hdr_capable());
4904        assert!(!DebugCaptureStage::FinalComposed.uses_hdr_intermediate());
4905
4906        assert_eq!(
4907            DebugCaptureStage::default(),
4908            DebugCaptureStage::FinalComposed
4909        );
4910        assert_eq!(DebugCaptureEncoding::default(), DebugCaptureEncoding::Png);
4911        assert_eq!(
4912            DebugSdrVisualization::default(),
4913            DebugSdrVisualization::ToneMappedColor
4914        );
4915        assert_eq!(
4916            DebugCaptureRequest::default(),
4917            DebugCaptureRequest {
4918                stage: DebugCaptureStage::FinalComposed,
4919                encoding: DebugCaptureEncoding::Png,
4920                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
4921            }
4922        );
4923    }
4924
4925    #[test]
4926    fn strip_padded_float_readback_rows_preserves_pixel_order() {
4927        let mapped = vec![1u8, 2, 3, 4, 9, 9, 9, 9, 5, 6, 7, 8, 8, 8, 8, 8];
4928        let stripped = strip_padded_readback_rows(&mapped, 4, 8, 2);
4929        assert_eq!(stripped, vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
4930    }
4931
4932    #[test]
4933    fn decode_rgba16f_pixels_converts_half_float_channels_to_f32() {
4934        let samples = [0.0f32, 1.0, 2.0, 0.5, 4.0, 8.0, 0.25, 1.0];
4935        let mut raw = Vec::new();
4936        for sample in samples {
4937            raw.extend_from_slice(&half::f16::from_f32(sample).to_bits().to_le_bytes());
4938        }
4939        let decoded = decode_rgba16f_pixels(&raw);
4940        assert_eq!(decoded.len(), 8);
4941        for (actual, expected) in decoded.into_iter().zip(samples) {
4942            assert!(
4943                (actual - expected).abs() < 0.001,
4944                "expected {expected}, got {actual}"
4945            );
4946        }
4947    }
4948
4949    #[test]
4950    fn hdr_png_capture_normalizes_native_hdr_reference_white() {
4951        let image = HdrRgbaImage::new(
4952            3,
4953            1,
4954            vec![
4955                2.5, 2.5, 2.5, 1.0, //
4956                1.25, 1.25, 1.25, 0.5, //
4957                5.0, 0.0, 0.0, 1.0,
4958            ],
4959        )
4960        .unwrap();
4961
4962        let sdr = hdr_image_to_sdr_rgba(
4963            &image,
4964            DebugSdrVisualization::ToneMappedColor,
4965            2.5,
4966            DisplayColorPrimaries::Srgb,
4967        )
4968        .unwrap();
4969
4970        assert_rgba_channels_near(
4971            &sdr.pixels()[0..4],
4972            [255, 255, 255, 255],
4973            RGBA_CHANNEL_TOLERANCE,
4974        );
4975        assert!(sdr.pixels()[4] < 255);
4976        assert!(
4977            sdr.pixels()[4].abs_diff(sdr.pixels()[5]) <= RGBA_CHANNEL_TOLERANCE,
4978            "normalized grayscale channels differed by more than {RGBA_CHANNEL_TOLERANCE}: got {} and {}",
4979            sdr.pixels()[4],
4980            sdr.pixels()[5]
4981        );
4982        assert!(
4983            sdr.pixels()[7].abs_diff(128) <= RGBA_CHANNEL_TOLERANCE,
4984            "alpha channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 128",
4985            sdr.pixels()[7]
4986        );
4987        assert_rgba_channels_near(
4988            &sdr.pixels()[8..12],
4989            [255, 0, 0, 255],
4990            RGBA_CHANNEL_TOLERANCE,
4991        );
4992    }
4993
4994    #[test]
4995    fn hdr_png_capture_preserves_srgb_bytes_after_hdr_scale_and_half_readback() {
4996        let reference_white = 203.0 / 80.0;
4997        let mut pixels = Vec::with_capacity(256 * 4);
4998        let mut expected = Vec::with_capacity(256 * 4);
4999
5000        for value in 0..=255u8 {
5001            let encoded = value as f32 / 255.0;
5002            let linear = shader_color(Color::srgba(encoded, encoded, encoded, 1.0));
5003            let captured = half::f16::from_f32(linear[0] * reference_white).to_f32();
5004            pixels.extend_from_slice(&[captured, captured, captured, 1.0]);
5005            expected.extend_from_slice(&[value, value, value, 255]);
5006        }
5007
5008        let image = HdrRgbaImage::new(256, 1, pixels).unwrap();
5009        let sdr = hdr_image_to_sdr_rgba(
5010            &image,
5011            DebugSdrVisualization::ToneMappedColor,
5012            reference_white,
5013            DisplayColorPrimaries::Srgb,
5014        )
5015        .unwrap();
5016
5017        assert_rgba_pixels_near(sdr.pixels(), expected.as_slice(), RGBA_CHANNEL_TOLERANCE);
5018    }
5019
5020    #[test]
5021    fn sdr_png_capture_transform_preserves_srgb_bytes_regardless_of_sdr_brightness() {
5022        let strategy = OutputStrategy::SdrSurface {
5023            format: wgpu::TextureFormat::Bgra8UnormSrgb,
5024        };
5025
5026        for value in 0..=255u8 {
5027            let encoded = value as f32 / 255.0;
5028            let transformed = apply_output_transform_for_testing(
5029                shader_color(Color::srgba(encoded, encoded, encoded, 1.0)),
5030                strategy,
5031                RequestedToneMappingMode::Clamp,
5032                10_000.0,
5033                None,
5034            );
5035            let captured = super::linear_to_srgb_capture_u8(transformed[0]);
5036            assert_eq!(captured, value, "sRGB byte {value} should round-trip");
5037        }
5038
5039        let clipped = apply_output_transform_for_testing(
5040            [4.0, 2.0, 0.5, 1.0],
5041            strategy,
5042            RequestedToneMappingMode::Clamp,
5043            10_000.0,
5044            None,
5045        );
5046        assert_eq!(super::linear_to_srgb_capture_u8(clipped[0]), 255);
5047        assert_eq!(super::linear_to_srgb_capture_u8(clipped[1]), 255);
5048        assert_eq!(super::linear_to_srgb_capture_u8(clipped[2]), 188);
5049    }
5050
5051    #[test]
5052    fn sdr_png_capture_readback_preserves_srgb_bytes_and_clips_hdr() {
5053        let window_id = WindowId::new(4520);
5054        let viewport = Size::new(32.0, 16.0);
5055        let mut scene = Scene::new();
5056        scene.push(SceneCommand::Clear(Color::srgba(0.0, 0.0, 0.0, 1.0)));
5057        scene.push(SceneCommand::FillRect {
5058            rect: Rect::new(0.0, 0.0, 16.0, 16.0),
5059            brush: Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0).into(),
5060        });
5061        scene.push(SceneCommand::FillRect {
5062            rect: Rect::new(16.0, 0.0, 16.0, 16.0),
5063            brush: Color::linear_rgba(4.0, 2.0, 0.5, 1.0).into(),
5064        });
5065
5066        let frame = SceneFrame {
5067            window_id,
5068            viewport,
5069            surface_size: viewport,
5070            scale_factor: 1.0,
5071            dirty_regions: Vec::new(),
5072            layer_updates: Vec::new(),
5073            scene,
5074            font_registry: Arc::new(FontRegistry::new()),
5075            image_registry: Arc::new(ImageRegistry::new()),
5076            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5077        };
5078
5079        let mut renderer = WgpuRenderer::new();
5080        renderer.render(&frame).unwrap();
5081        let image = renderer.capture_last_frame_rgba(window_id).unwrap();
5082
5083        assert_rgba_pixel_near(&image, 8, 8, [66, 42, 213, 255], RGBA_CHANNEL_TOLERANCE);
5084        assert_rgba_pixel_near(
5085            &image,
5086            24,
5087            8,
5088            [255, 255, super::linear_to_srgb_capture_u8(0.5), 255],
5089            RGBA_CHANNEL_TOLERANCE,
5090        );
5091    }
5092
5093    #[test]
5094    fn headless_intermediate_accepts_stencil_clip_mask_pipeline() {
5095        let window_id = WindowId::new(4521);
5096        let viewport = Size::new(32.0, 24.0);
5097        let mut scene = Scene::new();
5098        scene.push(SceneCommand::Clear(Color::BLACK));
5099        scene.push(SceneCommand::PushClipPath {
5100            path: Path::rounded_rect(Rect::new(4.0, 4.0, 24.0, 16.0), 6.0),
5101        });
5102        scene.push(SceneCommand::FillRect {
5103            rect: Rect::new(0.0, 0.0, 32.0, 24.0),
5104            brush: Color::WHITE.into(),
5105        });
5106        scene.push(SceneCommand::PopClip);
5107
5108        let frame = SceneFrame {
5109            window_id,
5110            viewport,
5111            surface_size: viewport,
5112            scale_factor: 1.0,
5113            dirty_regions: Vec::new(),
5114            layer_updates: Vec::new(),
5115            scene,
5116            font_registry: Arc::new(FontRegistry::new()),
5117            image_registry: Arc::new(ImageRegistry::new()),
5118            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5119        };
5120
5121        let mut renderer = WgpuRenderer::new();
5122        renderer.render(&frame).unwrap();
5123        let image = renderer.capture_last_frame_rgba(window_id).unwrap();
5124        assert_rgba_pixel_near(&image, 16, 12, [255, 255, 255, 255], RGBA_CHANNEL_TOLERANCE);
5125        assert_rgba_pixel_near(&image, 0, 0, [0, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
5126    }
5127
5128    #[test]
5129    fn hdr_png_capture_converts_display_p3_final_output_back_to_srgb() {
5130        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0);
5131        let strategy = OutputStrategy::HdrNativeSurface {
5132            format: wgpu::TextureFormat::Rgba16Float,
5133            primaries: DisplayColorPrimaries::DisplayP3,
5134            transfer: DisplayTransferFunction::LinearExtended,
5135        };
5136        let transformed = apply_output_transform_for_testing(
5137            shader_color(color),
5138            strategy,
5139            RequestedToneMappingMode::Automatic,
5140            203.0,
5141            None,
5142        );
5143        let image = HdrRgbaImage::new(
5144            1,
5145            1,
5146            vec![
5147                transformed[0],
5148                transformed[1],
5149                transformed[2],
5150                transformed[3],
5151            ],
5152        )
5153        .unwrap();
5154
5155        let sdr = hdr_image_to_sdr_rgba(
5156            &image,
5157            DebugSdrVisualization::ToneMappedColor,
5158            203.0 / 80.0,
5159            DisplayColorPrimaries::DisplayP3,
5160        )
5161        .unwrap();
5162
5163        assert_rgba_channels_near(
5164            &sdr.pixels()[0..4],
5165            [66, 42, 213, 255],
5166            RGBA_CHANNEL_TOLERANCE,
5167        );
5168    }
5169
5170    #[test]
5171    fn hdr_png_capture_visualizations_use_sdr_reference_white() {
5172        let image = HdrRgbaImage::new(
5173            2,
5174            1,
5175            vec![
5176                2.0, 2.0, 2.0, 1.0, //
5177                2.01, 0.0, 0.0, 1.0,
5178            ],
5179        )
5180        .unwrap();
5181
5182        let mask = hdr_image_to_sdr_rgba(
5183            &image,
5184            DebugSdrVisualization::ClipMask,
5185            2.0,
5186            DisplayColorPrimaries::Srgb,
5187        )
5188        .unwrap();
5189        assert_rgba_channels_near(&mask.pixels()[0..4], [0, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
5190        assert_rgba_channels_near(
5191            &mask.pixels()[4..8],
5192            [255, 64, 64, 255],
5193            RGBA_CHANNEL_TOLERANCE,
5194        );
5195
5196        let heatmap = hdr_image_to_sdr_rgba(
5197            &image,
5198            DebugSdrVisualization::HeadroomHeatmap,
5199            2.0,
5200            DisplayColorPrimaries::Srgb,
5201        )
5202        .unwrap();
5203        assert!(heatmap.pixels()[4] >= heatmap.pixels()[0]);
5204        assert!(
5205            heatmap.pixels()[7].abs_diff(255) <= RGBA_CHANNEL_TOLERANCE,
5206            "heatmap alpha channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 255",
5207            heatmap.pixels()[7]
5208        );
5209    }
5210
5211    #[test]
5212    fn hdr_debug_artifact_encoding_preserves_exr_and_maps_png_to_sdr() {
5213        let image = HdrRgbaImage::new(1, 1, vec![2.5, 1.25, 0.0, 1.0]).unwrap();
5214
5215        let png = encode_hdr_debug_artifact(
5216            image.clone(),
5217            DebugCaptureRequest {
5218                stage: DebugCaptureStage::FinalComposed,
5219                encoding: DebugCaptureEncoding::Png,
5220                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
5221            },
5222            2.5,
5223            DisplayColorPrimaries::Srgb,
5224        )
5225        .unwrap();
5226        let DebugCaptureArtifact::SdrRgba8(png) = png else {
5227            panic!("PNG HDR debug capture should be converted to SDR RGBA");
5228        };
5229        assert!(
5230            png.pixels()[0].abs_diff(255) <= RGBA_CHANNEL_TOLERANCE,
5231            "PNG red channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 255",
5232            png.pixels()[0]
5233        );
5234        assert!(png.pixels()[1] < 255);
5235
5236        let exr = encode_hdr_debug_artifact(
5237            image,
5238            DebugCaptureRequest {
5239                stage: DebugCaptureStage::FinalComposed,
5240                encoding: DebugCaptureEncoding::Exr,
5241                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
5242            },
5243            2.5,
5244            DisplayColorPrimaries::Srgb,
5245        )
5246        .unwrap();
5247        let DebugCaptureArtifact::HdrLinearRgbaF32(exr) = exr else {
5248            panic!("EXR HDR debug capture should preserve HDR linear RGBA");
5249        };
5250        assert_eq!(exr.pixels()[0], 2.5);
5251    }
5252
5253    fn load_test_font() -> RegisteredFont {
5254        let mut font_db = fontdb::Database::new();
5255        font_db.load_system_fonts();
5256        let families = [fontdb::Family::SansSerif];
5257        let font_id = font_db
5258            .query(&fontdb::Query {
5259                families: &families,
5260                weight: fontdb::Weight::NORMAL,
5261                stretch: fontdb::Stretch::Normal,
5262                style: fontdb::Style::Normal,
5263            })
5264            .or_else(|| font_db.faces().next().map(|face| face.id))
5265            .expect("system font available for renderer tests");
5266
5267        font_db
5268            .with_face_data(font_id, |font_data, face_index| {
5269                RegisteredFont::from_bytes(font_data.to_vec()).with_face_index(face_index)
5270            })
5271            .expect("font data should be readable from system font database")
5272    }
5273
5274    fn content_update(widget_id: WidgetId) -> SceneLayerUpdate {
5275        SceneLayerUpdate::from_descriptor(
5276            SceneLayerUpdateKind::Content,
5277            SceneLayerDescriptor::new(SceneLayerId::from_widget(widget_id), widget_id, Rect::ZERO),
5278        )
5279        .with_damage(Rect::ZERO)
5280    }
5281
5282    fn content_updates<const N: usize>(widget_ids: [WidgetId; N]) -> Vec<SceneLayerUpdate> {
5283        widget_ids.into_iter().map(content_update).collect()
5284    }
5285
5286    fn prepare_with_compositor(
5287        frame: &SceneFrame,
5288        text_engine: &mut TextEngine,
5289        compositor: &mut RetainedCompositorState,
5290    ) -> sui_core::Result<DrawOpArena> {
5291        compositor.prepare_frame(frame, text_engine, DEFAULT_FEATHER_WIDTH)
5292    }
5293
5294    fn packet_signature(
5295        compositor: &RetainedCompositorState,
5296        container: CompositionContainerId,
5297    ) -> u64 {
5298        compositor.packets[&RetainedPacketId {
5299            container,
5300            segment_index: 0,
5301        }]
5302            .signature
5303    }
5304
5305    const RGBA_CHANNEL_TOLERANCE: u8 = 1;
5306
5307    fn rgba_channels_match_with_tolerance(left: &[u8], right: &[u8], tolerance: u8) -> bool {
5308        left.iter()
5309            .zip(right.iter())
5310            .all(|(left, right)| left.abs_diff(*right) <= tolerance)
5311    }
5312
5313    fn assert_rgba_images_match(left: &super::RgbaImage, right: &super::RgbaImage) {
5314        assert_eq!(left.width(), right.width(), "image widths differ");
5315        assert_eq!(left.height(), right.height(), "image heights differ");
5316
5317        let mut diff_count = 0usize;
5318        let mut diff_bounds: Option<(u32, u32, u32, u32)> = None;
5319        let mut max_channel_diff = 0u8;
5320        let width = left.width();
5321        for (index, (left_px, right_px)) in left
5322            .pixels()
5323            .chunks_exact(4)
5324            .zip(right.pixels().chunks_exact(4))
5325            .enumerate()
5326        {
5327            let pixel_max_channel_diff = left_px
5328                .iter()
5329                .zip(right_px.iter())
5330                .map(|(left, right)| left.abs_diff(*right))
5331                .max()
5332                .unwrap_or(0);
5333            max_channel_diff = max_channel_diff.max(pixel_max_channel_diff);
5334            if pixel_max_channel_diff > RGBA_CHANNEL_TOLERANCE {
5335                diff_count += 1;
5336                let x = (index as u32) % width;
5337                let y = (index as u32) / width;
5338                diff_bounds = Some(match diff_bounds {
5339                    Some((min_x, min_y, max_x, max_y)) => {
5340                        (min_x.min(x), min_y.min(y), max_x.max(x), max_y.max(y))
5341                    }
5342                    None => (x, y, x, y),
5343                });
5344            }
5345        }
5346
5347        if diff_count != 0 {
5348            let (min_x, min_y, max_x, max_y) = diff_bounds.expect("diff bounds present");
5349            panic!(
5350                "images differ beyond {RGBA_CHANNEL_TOLERANCE} channel value at {} pixels within bounds ({}, {})..({}, {}); max channel diff {}",
5351                diff_count, min_x, min_y, max_x, max_y, max_channel_diff
5352            );
5353        }
5354    }
5355
5356    fn rgba_image_diff_count(left: &super::RgbaImage, right: &super::RgbaImage) -> usize {
5357        assert_eq!(left.width(), right.width(), "image widths differ");
5358        assert_eq!(left.height(), right.height(), "image heights differ");
5359
5360        left.pixels()
5361            .chunks_exact(4)
5362            .zip(right.pixels().chunks_exact(4))
5363            .filter(|(left_px, right_px)| {
5364                !rgba_channels_match_with_tolerance(left_px, right_px, RGBA_CHANNEL_TOLERANCE)
5365            })
5366            .count()
5367    }
5368
5369    fn ink_pixel_count(image: &super::RgbaImage, rect: Rect) -> usize {
5370        let min_x = rect.x().floor().max(0.0) as u32;
5371        let min_y = rect.y().floor().max(0.0) as u32;
5372        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5373        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5374        let pixels = image.pixels();
5375        let width = image.width() as usize;
5376
5377        let mut count = 0usize;
5378        for y in min_y..max_y {
5379            for x in min_x..max_x {
5380                let index = ((y as usize * width) + x as usize) * 4;
5381                let red = pixels[index] as i32;
5382                let green = pixels[index + 1] as i32;
5383                let blue = pixels[index + 2] as i32;
5384                let alpha = pixels[index + 3] as i32;
5385                if alpha > 0 && (red + green + blue) < 680 {
5386                    count += 1;
5387                }
5388            }
5389        }
5390        count
5391    }
5392
5393    fn non_white_pixel_count(image: &super::RgbaImage, rect: Rect) -> usize {
5394        let min_x = rect.x().floor().max(0.0) as u32;
5395        let min_y = rect.y().floor().max(0.0) as u32;
5396        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5397        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5398        let pixels = image.pixels();
5399        let width = image.width() as usize;
5400
5401        let mut count = 0usize;
5402        for y in min_y..max_y {
5403            for x in min_x..max_x {
5404                let index = ((y as usize * width) + x as usize) * 4;
5405                if !rgba_channels_match_with_tolerance(
5406                    &pixels[index..index + 4],
5407                    &[255, 255, 255, 255],
5408                    RGBA_CHANNEL_TOLERANCE,
5409                ) {
5410                    count += 1;
5411                }
5412            }
5413        }
5414        count
5415    }
5416
5417    fn non_white_row_count(image: &super::RgbaImage, rect: Rect) -> usize {
5418        let min_x = rect.x().floor().max(0.0) as u32;
5419        let min_y = rect.y().floor().max(0.0) as u32;
5420        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5421        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5422        let pixels = image.pixels();
5423        let width = image.width() as usize;
5424
5425        let mut rows = 0usize;
5426        for y in min_y..max_y {
5427            let mut row_has_ink = false;
5428            for x in min_x..max_x {
5429                let index = ((y as usize * width) + x as usize) * 4;
5430                if !rgba_channels_match_with_tolerance(
5431                    &pixels[index..index + 4],
5432                    &[255, 255, 255, 255],
5433                    RGBA_CHANNEL_TOLERANCE,
5434                ) {
5435                    row_has_ink = true;
5436                    break;
5437                }
5438            }
5439            rows += row_has_ink as usize;
5440        }
5441        rows
5442    }
5443
5444    fn rgba_pixel(image: &super::RgbaImage, x: u32, y: u32) -> [u8; 4] {
5445        let width = image.width() as usize;
5446        let index = ((y as usize * width) + x as usize) * 4;
5447        let pixels = image.pixels();
5448        [
5449            pixels[index],
5450            pixels[index + 1],
5451            pixels[index + 2],
5452            pixels[index + 3],
5453        ]
5454    }
5455
5456    fn assert_rgba_pixel_near(
5457        image: &super::RgbaImage,
5458        x: u32,
5459        y: u32,
5460        expected: [u8; 4],
5461        tolerance: u8,
5462    ) {
5463        let actual = rgba_pixel(image, x, y);
5464        for channel in 0..4 {
5465            assert!(
5466                actual[channel].abs_diff(expected[channel]) <= tolerance,
5467                "pixel ({x}, {y}) channel {channel} differed by more than {tolerance}: got {}, expected {}",
5468                actual[channel],
5469                expected[channel]
5470            );
5471        }
5472    }
5473
5474    fn assert_rgba_channels_near(actual: &[u8], expected: [u8; 4], tolerance: u8) {
5475        assert_eq!(
5476            actual.len(),
5477            4,
5478            "expected exactly one RGBA pixel, got {} channels",
5479            actual.len()
5480        );
5481        for channel in 0..4 {
5482            assert!(
5483                actual[channel].abs_diff(expected[channel]) <= tolerance,
5484                "channel {channel} differed by more than {tolerance}: got {}, expected {}",
5485                actual[channel],
5486                expected[channel]
5487            );
5488        }
5489    }
5490
5491    fn assert_rgba_pixels_near(actual: &[u8], expected: &[u8], tolerance: u8) {
5492        assert_eq!(
5493            actual.len(),
5494            expected.len(),
5495            "RGBA buffer length mismatch: got {}, expected {}",
5496            actual.len(),
5497            expected.len()
5498        );
5499        assert_eq!(
5500            actual.len() % 4,
5501            0,
5502            "RGBA buffer length must be divisible by 4"
5503        );
5504
5505        for (pixel_index, (actual_pixel, expected_pixel)) in actual
5506            .chunks_exact(4)
5507            .zip(expected.chunks_exact(4))
5508            .enumerate()
5509        {
5510            for channel in 0..4 {
5511                assert!(
5512                    actual_pixel[channel].abs_diff(expected_pixel[channel]) <= tolerance,
5513                    "pixel {pixel_index} channel {channel} differed by more than {tolerance}: got {}, expected {}",
5514                    actual_pixel[channel],
5515                    expected_pixel[channel]
5516                );
5517            }
5518        }
5519    }
5520
5521    #[test]
5522    fn renderer_draws_widget_shader_rect_gradient() {
5523        let mut scene = Scene::new();
5524        scene.push(SceneCommand::DrawShaderRect {
5525            rect: Rect::new(0.0, 0.0, 96.0, 24.0),
5526            shader: WidgetShader::ColorPickerHueBar,
5527        });
5528
5529        let frame = SceneFrame {
5530            window_id: WindowId::new(240),
5531            viewport: Size::new(96.0, 24.0),
5532            surface_size: Size::new(96.0, 24.0),
5533            scale_factor: 1.0,
5534            dirty_regions: Vec::new(),
5535            layer_updates: Vec::new(),
5536            scene,
5537            font_registry: Arc::new(FontRegistry::new()),
5538            image_registry: Arc::new(ImageRegistry::new()),
5539            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5540        };
5541
5542        let mut renderer = WgpuRenderer::default();
5543        renderer.render(&frame).unwrap();
5544        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
5545        let left = rgba_pixel(&pixels, 4, 12);
5546        let right = rgba_pixel(&pixels, 72, 12);
5547
5548        assert!(left[3] > 200);
5549        assert!(right[3] > 200);
5550        assert_ne!(left, right);
5551    }
5552
5553    fn build_translucent_scroll_child_frame(
5554        window_id: WindowId,
5555        scroll_cache_policy: LayerCachePolicy,
5556        child_cache_policy: LayerCachePolicy,
5557        child_y: f32,
5558        update_kind: SceneLayerUpdateKind,
5559    ) -> SceneFrame {
5560        let shell_id = WidgetId::new(210);
5561        let scroll_id = WidgetId::new(211);
5562        let child_id = WidgetId::new(212);
5563        let scroll_bounds = Rect::new(24.0, 24.0, 382.0, 292.0);
5564        let child_bounds = Rect::new(42.0, child_y, 360.0, 220.0);
5565        let selected_row = Rect::new(42.0, child_y + 32.0, 360.0, 28.0);
5566        let thumb = Rect::new(396.0, child_y + 14.0, 4.0, 58.0);
5567
5568        let shell_descriptor = SceneLayerDescriptor::new(
5569            SceneLayerId::from_widget(shell_id),
5570            shell_id,
5571            Rect::new(0.0, 0.0, 430.0, 360.0),
5572        )
5573        .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
5574        .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
5575        .with_cache_policy(LayerCachePolicy::Direct);
5576
5577        let scroll_descriptor = SceneLayerDescriptor::new(
5578            SceneLayerId::from_widget(scroll_id),
5579            scroll_id,
5580            scroll_bounds,
5581        )
5582        .with_content_bounds(scroll_bounds)
5583        .with_paint_bounds(scroll_bounds)
5584        .with_cache_policy(scroll_cache_policy)
5585        .with_composition_mode(LayerCompositionMode::Scroll);
5586
5587        let child_descriptor =
5588            SceneLayerDescriptor::new(SceneLayerId::from_widget(child_id), child_id, child_bounds)
5589                .with_content_bounds(child_bounds)
5590                .with_paint_bounds(child_bounds)
5591                .with_cache_policy(child_cache_policy);
5592
5593        let mut child_scene = Scene::new();
5594        child_scene.push(SceneCommand::FillRect {
5595            rect: child_bounds,
5596            brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
5597        });
5598        child_scene.push(SceneCommand::PushClip { rect: child_bounds });
5599        child_scene.push(SceneCommand::FillPath {
5600            path: Path::rounded_rect(selected_row, 6.0),
5601            brush: Color::rgba(0.09, 0.40, 0.92, 0.14).into(),
5602        });
5603        child_scene.push(SceneCommand::FillRect {
5604            rect: Rect::new(58.0, child_y + 40.0, 172.0, 12.0),
5605            brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
5606        });
5607        child_scene.push(SceneCommand::FillRect {
5608            rect: Rect::new(58.0, child_y + 64.0, 140.0, 10.0),
5609            brush: Color::rgba(0.45, 0.52, 0.61, 1.0).into(),
5610        });
5611        child_scene.push(SceneCommand::PopClip);
5612        child_scene.push(SceneCommand::FillPath {
5613            path: Path::rounded_rect(thumb, 2.0),
5614            brush: Color::rgba(0.54, 0.60, 0.68, 0.75).into(),
5615        });
5616
5617        let mut scroll_scene = Scene::new();
5618        scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5619            child_descriptor.clone(),
5620            child_scene,
5621        )));
5622
5623        let mut shell_scene = Scene::new();
5624        shell_scene.push(SceneCommand::FillRect {
5625            rect: Rect::new(0.0, 0.0, 430.0, 360.0),
5626            brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
5627        });
5628        shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5629            scroll_descriptor.clone(),
5630            scroll_scene,
5631        )));
5632
5633        let mut scene = Scene::new();
5634        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5635            shell_descriptor,
5636            shell_scene,
5637        )));
5638
5639        let update_damage = if update_kind == SceneLayerUpdateKind::Transform {
5640            Rect::new(42.0, 0.0, 360.0, 320.0)
5641        } else {
5642            child_bounds
5643        };
5644
5645        SceneFrame {
5646            window_id,
5647            viewport: Size::new(430.0, 360.0),
5648            surface_size: Size::new(430.0, 360.0),
5649            scale_factor: 1.0,
5650            dirty_regions: Vec::new(),
5651            layer_updates: vec![
5652                SceneLayerUpdate::from_descriptor(update_kind, child_descriptor)
5653                    .with_damage(update_damage),
5654            ],
5655            scene,
5656            font_registry: Arc::new(FontRegistry::new()),
5657            image_registry: Arc::new(ImageRegistry::new()),
5658            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5659        }
5660    }
5661
5662    fn logical_x_from_ndc(ndc_x: f32, viewport: Size) -> f32 {
5663        ((ndc_x + 1.0) * 0.5) * viewport.width
5664    }
5665
5666    fn logical_y_from_ndc(ndc_y: f32, viewport: Size) -> f32 {
5667        ((1.0 - ndc_y) * 0.5) * viewport.height
5668    }
5669
5670    const PHYSICAL_PIXEL_ALIGNMENT_EPSILON: f32 = 0.005;
5671
5672    fn is_physically_pixel_aligned(value: f32, scale_factor: f32) -> bool {
5673        let physical = value * scale_factor;
5674        (physical - physical.round()).abs() <= PHYSICAL_PIXEL_ALIGNMENT_EPSILON
5675    }
5676
5677    #[test]
5678    fn build_vertices_applies_clip_and_transform_to_fill_rects() {
5679        let mut scene = Scene::new();
5680        scene.push(SceneCommand::PushTransform {
5681            transform: Transform::translation(10.0, 5.0),
5682        });
5683        scene.push(SceneCommand::PushClip {
5684            rect: Rect::new(0.0, 0.0, 16.0, 12.0),
5685        });
5686        scene.push(SceneCommand::FillRect {
5687            rect: Rect::new(4.0, 3.0, 20.0, 10.0),
5688            brush: Color::WHITE.into(),
5689        });
5690
5691        let mut text_engine = TextEngine::new().unwrap();
5692        let vertices = build_vertices(
5693            &SceneFrame {
5694                window_id: WindowId::new(1),
5695                viewport: Size::new(100.0, 100.0),
5696                surface_size: Size::new(100.0, 100.0),
5697                scale_factor: 1.0,
5698                dirty_regions: Vec::new(),
5699                layer_updates: Vec::new(),
5700                scene,
5701                font_registry: Arc::new(FontRegistry::new()),
5702                image_registry: Arc::new(ImageRegistry::new()),
5703                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5704            },
5705            &mut text_engine,
5706        )
5707        .unwrap();
5708
5709        let expected_min = to_ndc(13.0, 7.0, Size::new(100.0, 100.0));
5710        let expected_max = to_ndc(26.0, 17.0, Size::new(100.0, 100.0));
5711
5712        assert_eq!(vertices.len(), 6);
5713        assert!(
5714            vertices
5715                .iter()
5716                .any(|vertex| vertex.position == expected_min)
5717        );
5718        assert!(
5719            vertices
5720                .iter()
5721                .any(|vertex| vertex.position == expected_max)
5722        );
5723        assert!(
5724            vertices
5725                .iter()
5726                .all(|vertex| vertex.shader_params == [10.0, 5.0, 0.0, DEFAULT_FEATHER_WIDTH])
5727        );
5728        assert!(
5729            vertices
5730                .iter()
5731                .any(|vertex| vertex.tex_coords == [-11.0, -6.0])
5732        );
5733        assert!(
5734            vertices
5735                .iter()
5736                .any(|vertex| vertex.tex_coords == [2.0, 4.0])
5737        );
5738    }
5739
5740    #[test]
5741    fn build_vertices_supports_text_and_stroke_primitives() {
5742        let mut scene = Scene::new();
5743        scene.push(SceneCommand::DrawText(TextRun {
5744            rect: Rect::new(4.0, 6.0, 80.0, 24.0),
5745            text: "scene".to_string(),
5746            style: TextStyle::new(Color::WHITE),
5747        }));
5748        scene.push(SceneCommand::StrokeRect {
5749            rect: Rect::new(2.0, 2.0, 20.0, 10.0),
5750            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
5751            stroke: StrokeStyle::new(2.0),
5752        });
5753
5754        let mut text_engine = TextEngine::new().unwrap();
5755        let vertices = build_vertices(
5756            &SceneFrame {
5757                window_id: WindowId::new(2),
5758                viewport: Size::new(100.0, 80.0),
5759                surface_size: Size::new(100.0, 80.0),
5760                scale_factor: 1.0,
5761                dirty_regions: Vec::new(),
5762                layer_updates: Vec::new(),
5763                scene,
5764                font_registry: Arc::new(FontRegistry::new()),
5765                image_registry: Arc::new(ImageRegistry::new()),
5766                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5767            },
5768            &mut text_engine,
5769        )
5770        .unwrap();
5771
5772        assert!(!vertices.is_empty());
5773        assert!(vertices.len() >= 30);
5774    }
5775
5776    #[test]
5777    fn build_vertices_supports_non_rect_paths() {
5778        let mut triangle = Path::builder();
5779        triangle
5780            .move_to(Point::new(10.0, 10.0))
5781            .line_to(Point::new(40.0, 10.0))
5782            .line_to(Point::new(24.0, 36.0))
5783            .close();
5784
5785        let mut curve = Path::builder();
5786        curve
5787            .move_to(Point::new(8.0, 44.0))
5788            .quad_to(Point::new(24.0, 24.0), Point::new(48.0, 44.0));
5789
5790        let mut scene = Scene::new();
5791        scene.push(SceneCommand::FillPath {
5792            path: triangle.build(),
5793            brush: Color::rgba(0.2, 0.8, 0.4, 1.0).into(),
5794        });
5795        scene.push(SceneCommand::StrokePath {
5796            path: curve.build(),
5797            brush: Color::rgba(0.9, 0.4, 0.2, 1.0).into(),
5798            stroke: StrokeStyle::new(3.0),
5799        });
5800
5801        let mut text_engine = TextEngine::new().unwrap();
5802        let vertices = build_vertices(
5803            &SceneFrame {
5804                window_id: WindowId::new(5),
5805                viewport: Size::new(80.0, 60.0),
5806                surface_size: Size::new(80.0, 60.0),
5807                scale_factor: 1.0,
5808                dirty_regions: Vec::new(),
5809                layer_updates: Vec::new(),
5810                scene,
5811                font_registry: Arc::new(FontRegistry::new()),
5812                image_registry: Arc::new(ImageRegistry::new()),
5813                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5814            },
5815            &mut text_engine,
5816        )
5817        .unwrap();
5818
5819        assert!(!vertices.is_empty());
5820        assert!(vertices.len() >= 12);
5821    }
5822
5823    #[test]
5824    fn shader_color_linearizes_srgb_inputs() {
5825        let rgba = shader_color(Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0));
5826
5827        assert!((rgba[0] - 0.05448).abs() < 0.0001);
5828        assert!((rgba[1] - 0.02315).abs() < 0.0001);
5829        assert!((rgba[2] - 0.66539).abs() < 0.0001);
5830        assert_eq!(rgba[3], 1.0);
5831    }
5832
5833    #[test]
5834    fn shader_color_converts_display_p3_primaries_into_linear_srgb_working_space() {
5835        let rgba = shader_color(Color::display_p3(1.0, 0.0, 0.0, 1.0));
5836
5837        assert!((rgba[0] - 1.22494).abs() < 0.0001);
5838        assert!((rgba[1] + 0.04205).abs() < 0.0001);
5839        assert!((rgba[2] + 0.01963).abs() < 0.0001);
5840        assert_eq!(rgba[3], 1.0);
5841    }
5842
5843    #[test]
5844    fn shader_color_preserves_extended_linear_srgb_values_for_hdr_content() {
5845        let rgba = shader_color(Color::linear_rgba(2.0, 4.0, 8.0, 1.0));
5846
5847        assert_eq!(rgba, [2.0, 4.0, 8.0, 1.0]);
5848    }
5849
5850    #[test]
5851    fn select_output_strategy_prefers_wide_gamut_when_requested_and_supported() {
5852        let strategy = select_output_strategy(
5853            &[wgpu::TextureFormat::Bgra8UnormSrgb],
5854            DisplayCapabilities {
5855                supports_wide_gamut: true,
5856                preferred_primaries: DisplayColorPrimaries::DisplayP3,
5857                ..DisplayCapabilities::default()
5858            },
5859            ColorManagementMode {
5860                mode: RequestedColorManagementMode::PreferWideGamut,
5861                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
5862                dynamic_range: RequestedDynamicRangeMode::Automatic,
5863                tone_mapping: RequestedToneMappingMode::Automatic,
5864                ..ColorManagementMode::default()
5865            },
5866        );
5867
5868        assert_eq!(
5869            strategy,
5870            OutputStrategy::WideGamutSurface {
5871                format: wgpu::TextureFormat::Bgra8UnormSrgb,
5872                primaries: DisplayColorPrimaries::DisplayP3,
5873            }
5874        );
5875    }
5876
5877    #[test]
5878    fn select_output_strategy_automatic_uses_wide_gamut_when_supported() {
5879        let strategy = select_output_strategy(
5880            &[wgpu::TextureFormat::Bgra8UnormSrgb],
5881            DisplayCapabilities {
5882                supports_wide_gamut: true,
5883                preferred_primaries: DisplayColorPrimaries::DisplayP3,
5884                ..DisplayCapabilities::default()
5885            },
5886            ColorManagementMode::default(),
5887        );
5888
5889        assert_eq!(
5890            strategy,
5891            OutputStrategy::WideGamutSurface {
5892                format: wgpu::TextureFormat::Bgra8UnormSrgb,
5893                primaries: DisplayColorPrimaries::DisplayP3,
5894            }
5895        );
5896    }
5897
5898    #[test]
5899    fn select_output_strategy_automatic_uses_native_hdr_when_supported() {
5900        let strategy = select_output_strategy(
5901            &[
5902                wgpu::TextureFormat::Rgba16Float,
5903                wgpu::TextureFormat::Bgra8UnormSrgb,
5904            ],
5905            DisplayCapabilities {
5906                supports_wide_gamut: true,
5907                supports_hdr: true,
5908                preferred_primaries: DisplayColorPrimaries::Srgb,
5909                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
5910                native_hdr_presentation_supported: true,
5911                ..DisplayCapabilities::default()
5912            },
5913            ColorManagementMode::default(),
5914        );
5915
5916        assert_eq!(
5917            strategy,
5918            OutputStrategy::HdrNativeSurface {
5919                format: wgpu::TextureFormat::Rgba16Float,
5920                primaries: DisplayColorPrimaries::Srgb,
5921                transfer: DisplayTransferFunction::LinearExtended,
5922            }
5923        );
5924    }
5925
5926    #[test]
5927    fn select_output_strategy_automatic_ignores_float16_without_native_hdr_support() {
5928        let strategy = select_output_strategy(
5929            &[
5930                wgpu::TextureFormat::Rgba16Float,
5931                wgpu::TextureFormat::Bgra8UnormSrgb,
5932            ],
5933            DisplayCapabilities {
5934                supports_wide_gamut: true,
5935                supports_hdr: false,
5936                preferred_primaries: DisplayColorPrimaries::DisplayP3,
5937                preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
5938                native_hdr_presentation_supported: false,
5939                ..DisplayCapabilities::default()
5940            },
5941            ColorManagementMode::default(),
5942        );
5943
5944        assert_eq!(
5945            strategy,
5946            OutputStrategy::WideGamutSurface {
5947                format: wgpu::TextureFormat::Bgra8UnormSrgb,
5948                primaries: DisplayColorPrimaries::DisplayP3,
5949            }
5950        );
5951    }
5952
5953    #[test]
5954    fn select_output_strategy_hdr_support_without_native_uses_sdr_despite_float16() {
5955        let strategy = select_output_strategy(
5956            &[
5957                wgpu::TextureFormat::Rgba16Float,
5958                wgpu::TextureFormat::Bgra8UnormSrgb,
5959            ],
5960            DisplayCapabilities {
5961                supports_wide_gamut: true,
5962                supports_hdr: true,
5963                preferred_primaries: DisplayColorPrimaries::Srgb,
5964                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
5965                native_hdr_presentation_supported: false,
5966                ..DisplayCapabilities::default()
5967            },
5968            ColorManagementMode::default(),
5969        );
5970
5971        assert_eq!(
5972            strategy,
5973            OutputStrategy::SdrSurface {
5974                format: wgpu::TextureFormat::Bgra8UnormSrgb,
5975            }
5976        );
5977    }
5978
5979    #[test]
5980    fn select_output_strategy_automatic_hdr_falls_back_to_sdr_without_native_hdr() {
5981        let strategy = select_output_strategy(
5982            &[wgpu::TextureFormat::Bgra8UnormSrgb],
5983            DisplayCapabilities {
5984                supports_wide_gamut: true,
5985                supports_hdr: true,
5986                preferred_primaries: DisplayColorPrimaries::DisplayP3,
5987                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
5988                native_hdr_presentation_supported: false,
5989                ..DisplayCapabilities::default()
5990            },
5991            ColorManagementMode::default(),
5992        );
5993
5994        assert_eq!(
5995            strategy,
5996            OutputStrategy::SdrSurface {
5997                format: wgpu::TextureFormat::Bgra8UnormSrgb,
5998            }
5999        );
6000    }
6001
6002    #[test]
6003    fn select_output_strategy_explicit_sdr_disables_automatic_hdr() {
6004        let strategy = select_output_strategy(
6005            &[
6006                wgpu::TextureFormat::Rgba16Float,
6007                wgpu::TextureFormat::Bgra8UnormSrgb,
6008            ],
6009            DisplayCapabilities {
6010                supports_wide_gamut: true,
6011                supports_hdr: true,
6012                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6013                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6014                native_hdr_presentation_supported: false,
6015                ..DisplayCapabilities::default()
6016            },
6017            ColorManagementMode {
6018                dynamic_range: RequestedDynamicRangeMode::StandardDynamicRange,
6019                ..ColorManagementMode::default()
6020            },
6021        );
6022
6023        assert_eq!(
6024            strategy,
6025            OutputStrategy::WideGamutSurface {
6026                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6027                primaries: DisplayColorPrimaries::DisplayP3,
6028            }
6029        );
6030    }
6031
6032    #[test]
6033    fn select_output_strategy_uses_sdr_when_hdr_is_requested_without_native_support() {
6034        let strategy = select_output_strategy(
6035            &[wgpu::TextureFormat::Bgra8UnormSrgb],
6036            DisplayCapabilities {
6037                supports_wide_gamut: true,
6038                supports_hdr: true,
6039                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6040                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6041                native_hdr_presentation_supported: false,
6042                ..DisplayCapabilities::default()
6043            },
6044            ColorManagementMode {
6045                mode: RequestedColorManagementMode::PreferHdr,
6046                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
6047                dynamic_range: RequestedDynamicRangeMode::HighDynamicRange,
6048                tone_mapping: RequestedToneMappingMode::Automatic,
6049                ..ColorManagementMode::default()
6050            },
6051        );
6052
6053        assert_eq!(
6054            strategy,
6055            OutputStrategy::SdrSurface {
6056                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6057            }
6058        );
6059    }
6060
6061    #[test]
6062    fn select_output_strategy_uses_native_hdr_scrgb_surface_when_supported() {
6063        let strategy = select_output_strategy(
6064            &[
6065                wgpu::TextureFormat::Rgba16Float,
6066                wgpu::TextureFormat::Bgra8UnormSrgb,
6067            ],
6068            DisplayCapabilities {
6069                supports_wide_gamut: true,
6070                supports_hdr: true,
6071                preferred_primaries: DisplayColorPrimaries::Srgb,
6072                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6073                native_hdr_presentation_supported: true,
6074                ..DisplayCapabilities::default()
6075            },
6076            ColorManagementMode {
6077                mode: RequestedColorManagementMode::PreferHdr,
6078                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
6079                dynamic_range: RequestedDynamicRangeMode::HighDynamicRange,
6080                tone_mapping: RequestedToneMappingMode::Automatic,
6081                ..ColorManagementMode::default()
6082            },
6083        );
6084
6085        assert_eq!(
6086            strategy,
6087            OutputStrategy::HdrNativeSurface {
6088                format: wgpu::TextureFormat::Rgba16Float,
6089                primaries: DisplayColorPrimaries::Srgb,
6090                transfer: DisplayTransferFunction::LinearExtended,
6091            }
6092        );
6093    }
6094
6095    #[test]
6096    fn hdr_output_transform_requires_intermediate_for_hdr_strategies() {
6097        assert!(output_transform_requires_intermediate(
6098            OutputStrategy::HdrIntermediateThenToneMap {
6099                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6100                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6101                primaries: DisplayColorPrimaries::DisplayP3,
6102            }
6103        ));
6104        assert!(output_transform_requires_intermediate(
6105            OutputStrategy::HdrNativeSurface {
6106                format: wgpu::TextureFormat::Rgba16Float,
6107                primaries: DisplayColorPrimaries::DisplayP3,
6108                transfer: DisplayTransferFunction::LinearExtended,
6109            }
6110        ));
6111        assert!(!output_transform_requires_intermediate(
6112            OutputStrategy::SdrSurface {
6113                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6114            }
6115        ));
6116    }
6117
6118    #[test]
6119    fn wide_gamut_output_transform_runs_even_for_srgb_surface_formats() {
6120        assert!(output_transform_requires_intermediate(
6121            OutputStrategy::WideGamutSurface {
6122                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6123                primaries: DisplayColorPrimaries::DisplayP3,
6124            }
6125        ));
6126    }
6127
6128    #[test]
6129    fn reinhard_tone_mapping_compresses_extended_linear_values() {
6130        let transformed =
6131            tone_map_linear_color([4.0, 1.0, 0.5, 1.0], RequestedToneMappingMode::Reinhard);
6132
6133        assert!(transformed[0] < 1.0);
6134        assert!(transformed[0] > transformed[1]);
6135        assert_eq!(transformed[3], 1.0);
6136    }
6137
6138    #[test]
6139    fn clamp_tone_mapping_limits_linear_values_to_sdr_range() {
6140        let transformed =
6141            tone_map_linear_color([2.5, 1.25, 0.5, 1.0], RequestedToneMappingMode::Clamp);
6142
6143        assert_eq!(transformed, [1.0, 1.0, 0.5, 1.0]);
6144    }
6145
6146    #[test]
6147    fn hdr_output_transform_scales_reference_white_to_requested_sdr_content_brightness() {
6148        let transformed = apply_output_transform_for_testing(
6149            [1.0, 1.0, 1.0, 1.0],
6150            OutputStrategy::HdrNativeSurface {
6151                format: wgpu::TextureFormat::Rgba16Float,
6152                primaries: DisplayColorPrimaries::Srgb,
6153                transfer: DisplayTransferFunction::LinearExtended,
6154            },
6155            RequestedToneMappingMode::Automatic,
6156            203.0,
6157            None,
6158        );
6159
6160        let expected = 203.0 / 80.0;
6161        assert!((transformed[0] - expected).abs() < 0.0001);
6162        assert!((transformed[1] - expected).abs() < 0.0001);
6163        assert!((transformed[2] - expected).abs() < 0.0001);
6164        assert_eq!(transformed[3], 1.0);
6165    }
6166
6167    #[test]
6168    fn native_hdr_output_preserves_requested_reference_white_even_with_manual_tone_mapping_modes() {
6169        let strategy = OutputStrategy::HdrNativeSurface {
6170            format: wgpu::TextureFormat::Rgba16Float,
6171            primaries: DisplayColorPrimaries::Srgb,
6172            transfer: DisplayTransferFunction::LinearExtended,
6173        };
6174        let expected = 203.0 / 80.0;
6175
6176        for mode in [
6177            RequestedToneMappingMode::Automatic,
6178            RequestedToneMappingMode::Clamp,
6179            RequestedToneMappingMode::Reinhard,
6180        ] {
6181            let transformed = apply_output_transform_for_testing(
6182                [1.0, 1.0, 1.0, 1.0],
6183                strategy,
6184                mode,
6185                203.0,
6186                None,
6187            );
6188            assert!((transformed[0] - expected).abs() < 0.0001, "mode={mode:?}");
6189            assert!((transformed[1] - expected).abs() < 0.0001, "mode={mode:?}");
6190            assert!((transformed[2] - expected).abs() < 0.0001, "mode={mode:?}");
6191            assert_eq!(transformed[3], 1.0, "mode={mode:?}");
6192        }
6193    }
6194
6195    #[test]
6196    fn native_hdr_output_uses_sc_rgb_reference_white_when_display_sdr_white_is_reported() {
6197        let strategy = OutputStrategy::HdrNativeSurface {
6198            format: wgpu::TextureFormat::Rgba16Float,
6199            primaries: DisplayColorPrimaries::DisplayP3,
6200            transfer: DisplayTransferFunction::LinearExtended,
6201        };
6202        let transformed = apply_output_transform_for_testing(
6203            [1.0, 1.0, 1.0, 1.0],
6204            strategy,
6205            RequestedToneMappingMode::Automatic,
6206            101.5,
6207            Some(203.0),
6208        );
6209
6210        let expected = 101.5 / 80.0;
6211        assert!((transformed[0] - expected).abs() < 0.0001);
6212        assert!((transformed[1] - expected).abs() < 0.0001);
6213        assert!((transformed[2] - expected).abs() < 0.0001);
6214        assert_eq!(transformed[3], 1.0);
6215    }
6216
6217    #[test]
6218    fn output_transform_maps_linear_srgb_to_display_p3_canvas_primaries() {
6219        let transformed = apply_output_transform_for_testing(
6220            [1.0, 0.55, 0.18, 1.0],
6221            OutputStrategy::HdrNativeSurface {
6222                format: wgpu::TextureFormat::Rgba16Float,
6223                primaries: DisplayColorPrimaries::DisplayP3,
6224                transfer: DisplayTransferFunction::Srgb,
6225            },
6226            RequestedToneMappingMode::Automatic,
6227            80.0,
6228            None,
6229        );
6230
6231        assert!((transformed[0] - 0.920_107_84).abs() < 0.0001);
6232        assert!((transformed[1] - 0.564_937_35).abs() < 0.0001);
6233        assert!((transformed[2] - 0.220_794_81).abs() < 0.0001);
6234        assert_eq!(transformed[3], 1.0);
6235    }
6236
6237    #[test]
6238    fn hdr_tone_mapped_output_preserves_sdr_reference_white_by_default() {
6239        let transformed = apply_output_transform_for_testing(
6240            [1.0, 1.0, 1.0, 1.0],
6241            OutputStrategy::HdrIntermediateThenToneMap {
6242                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6243                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6244                primaries: DisplayColorPrimaries::DisplayP3,
6245            },
6246            RequestedToneMappingMode::Automatic,
6247            203.0,
6248            None,
6249        );
6250
6251        assert!((transformed[0] - 1.0).abs() < 0.0001);
6252        assert!((transformed[1] - 1.0).abs() < 0.0001);
6253        assert!((transformed[2] - 1.0).abs() < 0.0001);
6254        assert_eq!(transformed[3], 1.0);
6255    }
6256
6257    #[test]
6258    fn hdr_tone_mapped_output_keeps_reinhard_as_explicit_opt_in() {
6259        let transformed = apply_output_transform_for_testing(
6260            [1.0, 1.0, 1.0, 1.0],
6261            OutputStrategy::HdrIntermediateThenToneMap {
6262                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6263                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6264                primaries: DisplayColorPrimaries::Srgb,
6265            },
6266            RequestedToneMappingMode::Reinhard,
6267            203.0,
6268            None,
6269        );
6270
6271        let expected = 0.5;
6272        assert!((transformed[0] - expected).abs() < 0.0001);
6273        assert!((transformed[1] - expected).abs() < 0.0001);
6274        assert!((transformed[2] - expected).abs() < 0.0001);
6275        assert_eq!(transformed[3], 1.0);
6276    }
6277
6278    #[test]
6279    fn shader_color_preserves_linear_display_p3_channels_before_gamut_conversion() {
6280        let encoded = shader_color(Color::display_p3(0.5, 0.25, 0.75, 1.0));
6281        let linear = shader_color(Color::linear_display_p3(
6282            0.21404114, 0.05087609, 0.52252156, 1.0,
6283        ));
6284
6285        for index in 0..3 {
6286            assert!((encoded[index] - linear[index]).abs() < 0.0001);
6287        }
6288        assert_eq!(linear[3], 1.0);
6289    }
6290
6291    #[test]
6292    fn cached_path_mesh_linearizes_srgb_inputs() {
6293        let mut mesh = CachedGlyphMesh::default();
6294        let a = mesh.push_vertex(Point::new(0.0, 0.0), 1.0);
6295        let b = mesh.push_vertex(Point::new(10.0, 0.0), 1.0);
6296        let c = mesh.push_vertex(Point::new(0.0, 10.0), 1.0);
6297        mesh.add_triangle(a, b, c);
6298
6299        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0);
6300        let mut vertices = Vec::new();
6301        append_cached_path_mesh(&mut vertices, &mesh, color, Size::new(32.0, 32.0));
6302
6303        assert_eq!(vertices.len(), 3);
6304        let expected = shader_color(color);
6305        for vertex in vertices {
6306            assert!((vertex.color[0] - expected[0]).abs() < 0.0001);
6307            assert!((vertex.color[1] - expected[1]).abs() < 0.0001);
6308            assert!((vertex.color[2] - expected[2]).abs() < 0.0001);
6309            assert_eq!(vertex.color[3], 1.0);
6310        }
6311    }
6312
6313    #[test]
6314    fn cached_glyph_atlas_linearizes_srgb_inputs() {
6315        let atlas = CachedGlyphAtlas {
6316            scale: 12.0,
6317            offset: Vector::new(1.0, 2.0),
6318            size: Size::new(8.0, 10.0),
6319            uv_min: [0.25, 0.5],
6320            uv_max: [0.5, 0.75],
6321            color_mode: TextAtlasColorMode::Grayscale,
6322            is_color: false,
6323            page_index: 0,
6324        };
6325        let glyph = ShapedGlyph {
6326            glyph_id: 42,
6327            cluster: 0,
6328            span_id: sui_text::TextSpanId {
6329                paragraph_index: 0,
6330                span_index: 0,
6331            },
6332            run_index: 0,
6333            line_index: 0,
6334            face_index: 0,
6335            origin_x: 12.0,
6336            origin_y: 20.0,
6337            advance: Vector::new(8.0, 0.0),
6338            scale: 12.0,
6339            bounds: Some(Rect::new(13.0, 22.0, 8.0, 10.0)),
6340        };
6341
6342        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 0.75);
6343        let mut vertices = Vec::new();
6344        append_cached_glyph_atlas(
6345            &mut vertices,
6346            &atlas,
6347            &glyph,
6348            color,
6349            Transform::IDENTITY,
6350            Size::new(64.0, 64.0),
6351            1.0,
6352        );
6353
6354        assert_eq!(vertices.len(), 6);
6355        let expected = shader_color(color);
6356        for vertex in vertices {
6357            assert!((vertex.color[0] - expected[0]).abs() < 0.0001);
6358            assert!((vertex.color[1] - expected[1]).abs() < 0.0001);
6359            assert!((vertex.color[2] - expected[2]).abs() < 0.0001);
6360            assert!((vertex.color[3] - expected[3]).abs() < 0.0001);
6361        }
6362    }
6363
6364    #[test]
6365    fn cached_glyph_atlas_places_quad_from_subpixel_phase_integer() {
6366        let atlas = CachedGlyphAtlas {
6367            scale: 12.0,
6368            offset: Vector::ZERO,
6369            size: Size::new(8.0, 10.0),
6370            uv_min: [0.25, 0.5],
6371            uv_max: [0.5, 0.75],
6372            color_mode: TextAtlasColorMode::Grayscale,
6373            is_color: false,
6374            page_index: 0,
6375        };
6376        let glyph = ShapedGlyph {
6377            glyph_id: 42,
6378            cluster: 0,
6379            span_id: sui_text::TextSpanId {
6380                paragraph_index: 0,
6381                span_index: 0,
6382            },
6383            run_index: 0,
6384            line_index: 0,
6385            face_index: 0,
6386            origin_x: 10.75,
6387            origin_y: 20.0,
6388            advance: Vector::new(8.0, 0.0),
6389            scale: 12.0,
6390            bounds: None,
6391        };
6392        let viewport = Size::new(64.0, 64.0);
6393        let mut vertices = Vec::new();
6394        append_cached_glyph_atlas(
6395            &mut vertices,
6396            &atlas,
6397            &glyph,
6398            Color::WHITE,
6399            Transform::IDENTITY,
6400            viewport,
6401            1.0,
6402        );
6403
6404        assert_eq!(vertices.len(), 6);
6405        let left = logical_x_from_ndc(vertices[0].position[0], viewport);
6406        assert!((left - 10.0).abs() < 0.0001);
6407    }
6408
6409    #[test]
6410    fn swash_placement_offsets_are_converted_to_screen_space() {
6411        let offset = glyph_raster_offset(
6412            &swash::zeno::Placement {
6413                left: 6,
6414                top: 10,
6415                width: 12,
6416                height: 14,
6417            },
6418            2.0,
6419        );
6420
6421        assert_eq!(offset, Vector::new(3.0, -5.0));
6422    }
6423
6424    #[test]
6425    fn cached_color_glyph_atlas_uses_opacity_sentinel() {
6426        let atlas = CachedGlyphAtlas {
6427            scale: 12.0,
6428            offset: Vector::new(1.0, 2.0),
6429            size: Size::new(8.0, 10.0),
6430            uv_min: [0.25, 0.5],
6431            uv_max: [0.5, 0.75],
6432            color_mode: TextAtlasColorMode::Grayscale,
6433            is_color: true,
6434            page_index: 0,
6435        };
6436        let glyph = ShapedGlyph {
6437            glyph_id: 42,
6438            cluster: 0,
6439            span_id: sui_text::TextSpanId {
6440                paragraph_index: 0,
6441                span_index: 0,
6442            },
6443            run_index: 0,
6444            line_index: 0,
6445            face_index: 0,
6446            origin_x: 12.0,
6447            origin_y: 20.0,
6448            advance: Vector::new(8.0, 0.0),
6449            scale: 12.0,
6450            bounds: Some(Rect::new(13.0, 22.0, 8.0, 10.0)),
6451        };
6452
6453        let mut vertices = Vec::new();
6454        append_cached_glyph_atlas(
6455            &mut vertices,
6456            &atlas,
6457            &glyph,
6458            Color::srgba(0.2, 0.4, 0.6, 0.75),
6459            Transform::IDENTITY,
6460            Size::new(64.0, 64.0),
6461            1.0,
6462        );
6463
6464        assert_eq!(vertices.len(), 6);
6465        for vertex in vertices {
6466            assert_eq!(vertex.color[0], 1.0);
6467            assert_eq!(vertex.color[1], 1.0);
6468            assert_eq!(vertex.color[2], 1.0);
6469            assert_eq!(vertex.color[3], -0.75);
6470        }
6471    }
6472
6473    #[test]
6474    fn swash_color_glyph_images_store_srgb_for_text_atlas() {
6475        let image = swash::scale::image::Image {
6476            source: SwashSource::ColorBitmap(SwashStrikeWith::BestFit),
6477            content: SwashImageContent::Color,
6478            placement: swash::zeno::Placement {
6479                left: 0,
6480                top: 0,
6481                width: 1,
6482                height: 1,
6483            },
6484            data: vec![66, 42, 213, 128],
6485        };
6486
6487        let rasterized = swash_image_to_rgba(
6488            &image,
6489            14.0,
6490            TextRenderMode::Grayscale,
6491            TextSubpixelOrder::None,
6492            StemDarkening::None,
6493        )
6494        .expect("color glyph should convert into atlas pixels");
6495
6496        assert!(rasterized.is_color);
6497        // The atlas stores sRGB verbatim; the fragment shader linearizes at sample time.
6498        assert_rgba_pixels_near(
6499            &rasterized.pixels,
6500            &[66, 42, 213, 128],
6501            RGBA_CHANNEL_TOLERANCE,
6502        );
6503    }
6504
6505    #[test]
6506    fn text_atlas_shader_outputs_premultiplied_alpha() {
6507        let color = shader_color(Color::srgba(
6508            66.0 / 255.0,
6509            42.0 / 255.0,
6510            213.0 / 255.0,
6511            0.75,
6512        ));
6513        let coverage = 0.5;
6514        let alpha = color[3] * coverage;
6515        let premultiplied = [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha];
6516
6517        assert!((premultiplied[0] - 0.02043).abs() < 0.0001);
6518        assert!((premultiplied[1] - 0.00868).abs() < 0.0001);
6519        assert!((premultiplied[2] - 0.24952).abs() < 0.0001);
6520        assert!((premultiplied[3] - 0.375).abs() < 0.0001);
6521    }
6522
6523    #[test]
6524    fn color_text_atlas_shader_outputs_sampled_premultiplied_alpha() {
6525        // The atlas now holds sRGB; the shader linearizes the sampled color before premultiplying.
6526        fn srgb_to_linear(channel: f32) -> f32 {
6527            if channel <= 0.04045 {
6528                channel / 12.92
6529            } else {
6530                ((channel + 0.055) / 1.055).powf(2.4)
6531            }
6532        }
6533        let sampled_srgb = [66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0];
6534        let linear = [
6535            srgb_to_linear(sampled_srgb[0]),
6536            srgb_to_linear(sampled_srgb[1]),
6537            srgb_to_linear(sampled_srgb[2]),
6538        ];
6539        let sampled_alpha = 0.5;
6540        let opacity = 0.75;
6541        let alpha = sampled_alpha * opacity;
6542        let premultiplied = [
6543            linear[0] * alpha,
6544            linear[1] * alpha,
6545            linear[2] * alpha,
6546            alpha,
6547        ];
6548
6549        assert!((premultiplied[0] - linear[0] * 0.375).abs() < 0.0001);
6550        assert!((premultiplied[1] - linear[1] * 0.375).abs() < 0.0001);
6551        assert!((premultiplied[2] - linear[2] * 0.375).abs() < 0.0001);
6552        assert!((premultiplied[3] - 0.375).abs() < 0.0001);
6553    }
6554
6555    #[test]
6556    fn text_coverage_policy_matches_egui_reference_formulas() {
6557        assert!((TextCoveragePolicy::Linear.apply(0.5) - 0.5).abs() < 0.0001);
6558        assert!((TextCoveragePolicy::Gamma(2.0).apply(0.5) - 0.25).abs() < 0.0001);
6559        assert!((TextCoveragePolicy::CoverageBoost(0.5).apply(0.5) - 0.625).abs() < 0.0001);
6560        assert!((TextCoveragePolicy::TwoCoverageMinusCoverageSq.apply(0.5) - 0.75).abs() < 0.0001);
6561    }
6562
6563    #[test]
6564    fn text_coverage_policy_defaults_to_perceptual_luminance_curve() {
6565        assert_eq!(
6566            TextCoveragePolicy::default(),
6567            TextCoveragePolicy::Perceptual
6568        );
6569
6570        let TextCoveragePolicy::CoverageBoost(black_boost) =
6571            TextCoveragePolicy::default().resolved_for_text_color(Color::BLACK)
6572        else {
6573            panic!("perceptual coverage should resolve to a coverage boost policy");
6574        };
6575        let TextCoveragePolicy::CoverageBoost(white_boost) =
6576            TextCoveragePolicy::default().resolved_for_text_color(Color::WHITE)
6577        else {
6578            panic!("perceptual coverage should resolve to a coverage boost policy");
6579        };
6580
6581        assert!((black_boost - 0.92).abs() < 0.0001);
6582        assert!((white_boost - 0.45).abs() < 0.0001);
6583        assert!(black_boost > white_boost);
6584    }
6585
6586    #[test]
6587    fn text_render_mode_defaults_to_grayscale() {
6588        assert_eq!(TextRenderMode::default(), TextRenderMode::Grayscale);
6589    }
6590
6591    #[test]
6592    fn text_subpixel_order_defaults_to_none() {
6593        assert_eq!(TextSubpixelOrder::default(), TextSubpixelOrder::None);
6594        assert_eq!(
6595            WgpuRenderer::new().text_subpixel_order(),
6596            TextSubpixelOrder::None
6597        );
6598    }
6599
6600    #[test]
6601    fn slight_hinting_enables_below_threshold() {
6602        let config = TextHinting::Slight { max_ppem: 18.0 };
6603        assert!(config.should_hint(14.0));
6604        assert!(!config.should_hint(24.0));
6605    }
6606
6607    #[test]
6608    fn stem_darkening_applies_only_below_threshold() {
6609        let config = StemDarkening::Enabled {
6610            max_ppem: 18.0,
6611            amount: 0.08,
6612        };
6613        assert!(config.effective_amount(14.0) > 0.0);
6614        assert_eq!(config.effective_amount(24.0), 0.0);
6615    }
6616
6617    #[test]
6618    fn stem_darkening_boosts_partial_coverage() {
6619        let darkened = apply_stem_darkening_to_coverage(128, 0.1);
6620        assert!(darkened > 128);
6621    }
6622
6623    #[test]
6624    fn stem_darkening_preserves_transparent_and_opaque_endpoints() {
6625        // A transparent pixel must stay transparent — otherwise every glyph cell's background
6626        // gets lifted to `amount` opacity, painting a gray box behind each glyph. A fully
6627        // opaque pixel must stay opaque. This must hold even at a large darkening amount.
6628        for amount in [0.1, 0.5, 0.6, 1.0] {
6629            assert_eq!(apply_stem_darkening_to_coverage(0, amount), 0);
6630            assert_eq!(apply_stem_darkening_to_coverage(255, amount), 255);
6631        }
6632    }
6633
6634    #[test]
6635    fn lcd_text_render_mode_has_distinct_cache_identity() {
6636        assert_ne!(
6637            TextAtlasColorMode::from(TextRenderMode::Grayscale),
6638            TextAtlasColorMode::from(TextRenderMode::LcdSubpixel),
6639        );
6640    }
6641
6642    #[test]
6643    fn subpixel_mask_preserves_distinct_rgb_channels_in_lcd_mode() {
6644        let converted = convert_subpixel_texel_for_mode(
6645            [255, 128, 32, 255],
6646            TextRenderMode::LcdSubpixel,
6647            TextSubpixelOrder::Rgb,
6648            0.0,
6649        );
6650        assert_rgba_channels_near(&converted, [32, 128, 255, 255], RGBA_CHANNEL_TOLERANCE);
6651    }
6652
6653    #[test]
6654    fn subpixel_mask_can_reverse_physical_order_for_bgr_lcd() {
6655        let converted = convert_subpixel_texel_for_mode(
6656            [255, 128, 32, 255],
6657            TextRenderMode::LcdSubpixel,
6658            TextSubpixelOrder::Bgr,
6659            0.0,
6660        );
6661        assert_rgba_channels_near(&converted, [255, 128, 32, 255], RGBA_CHANNEL_TOLERANCE);
6662    }
6663
6664    #[test]
6665    fn subpixel_mask_uses_grayscale_when_subpixel_order_is_none() {
6666        let converted = convert_subpixel_texel_for_mode(
6667            [255, 128, 32, 255],
6668            TextRenderMode::LcdSubpixel,
6669            TextSubpixelOrder::None,
6670            0.0,
6671        );
6672        assert_rgba_channels_near(&converted, [255, 255, 255, 138], RGBA_CHANNEL_TOLERANCE);
6673    }
6674
6675    #[test]
6676    fn glyph_subpixel_offset_tracks_quarter_pixel_phase() {
6677        let glyph = ShapedGlyph {
6678            glyph_id: 42,
6679            cluster: 0,
6680            span_id: sui_text::TextSpanId {
6681                paragraph_index: 0,
6682                span_index: 0,
6683            },
6684            run_index: 0,
6685            line_index: 0,
6686            face_index: 0,
6687            origin_x: 10.25,
6688            origin_y: 20.0,
6689            advance: Vector::new(8.0, 0.0),
6690            scale: 12.0,
6691            bounds: None,
6692        };
6693
6694        assert_eq!(
6695            glyph_subpixel_offset(Transform::IDENTITY, Vector::ZERO, &glyph, 1.0),
6696            GlyphSubpixelOffsetKey::new(1, 0)
6697        );
6698        assert_eq!(
6699            glyph_subpixel_offset(Transform::IDENTITY, Vector::ZERO, &glyph, 2.0),
6700            GlyphSubpixelOffsetKey::new(2, 0)
6701        );
6702        assert_eq!(
6703            glyph_subpixel_offset(Transform::rotation(0.25), Vector::ZERO, &glyph, 1.0),
6704            GlyphSubpixelOffsetKey::default()
6705        );
6706    }
6707
6708    #[test]
6709    fn glyph_subpixel_offset_includes_layer_pixel_snap_phase() {
6710        let glyph = ShapedGlyph {
6711            glyph_id: 42,
6712            cluster: 0,
6713            span_id: sui_text::TextSpanId {
6714                paragraph_index: 0,
6715                span_index: 0,
6716            },
6717            run_index: 0,
6718            line_index: 0,
6719            face_index: 0,
6720            origin_x: 14.0,
6721            origin_y: 20.0,
6722            advance: Vector::new(8.0, 0.0),
6723            scale: 12.0,
6724            bounds: None,
6725        };
6726
6727        assert_eq!(
6728            glyph_subpixel_offset(
6729                Transform::IDENTITY,
6730                Vector::new(1.0 / 3.0, 0.0),
6731                &glyph,
6732                1.5
6733            ),
6734            GlyphSubpixelOffsetKey::new(2, 0)
6735        );
6736    }
6737
6738    #[test]
6739    fn glyph_cache_key_includes_subpixel_offset() {
6740        let face = GlyphFaceCacheKey {
6741            data_ptr: 0x1000,
6742            data_len: 128,
6743            face_index: 0,
6744        };
6745        let first = GlyphCacheKey::new(
6746            face,
6747            7,
6748            1024,
6749            GlyphSubpixelOffsetKey::new(0, 0),
6750            TextRenderMode::Grayscale,
6751            TextSubpixelOrder::None,
6752            TextHinting::None,
6753            StemDarkening::None,
6754            400,
6755        );
6756        let second = GlyphCacheKey::new(
6757            face,
6758            7,
6759            1024,
6760            GlyphSubpixelOffsetKey::new(1, 0),
6761            TextRenderMode::Grayscale,
6762            TextSubpixelOrder::None,
6763            TextHinting::None,
6764            StemDarkening::None,
6765            400,
6766        );
6767        assert_ne!(first, second);
6768    }
6769
6770    #[test]
6771    fn glyph_cache_key_includes_weight() {
6772        let face = GlyphFaceCacheKey {
6773            data_ptr: 0x1000,
6774            data_len: 128,
6775            face_index: 0,
6776        };
6777        let key = |weight| {
6778            GlyphCacheKey::new(
6779                face,
6780                7,
6781                1024,
6782                GlyphSubpixelOffsetKey::new(0, 0),
6783                TextRenderMode::Grayscale,
6784                TextSubpixelOrder::None,
6785                TextHinting::None,
6786                StemDarkening::None,
6787                weight,
6788            )
6789        };
6790        // Different weights of a variable font rasterize differently -> distinct cache entries.
6791        assert_ne!(key(400), key(700));
6792        assert_eq!(key(700), key(700));
6793    }
6794
6795    #[test]
6796    fn glyph_cache_key_includes_subpixel_order() {
6797        let face = GlyphFaceCacheKey {
6798            data_ptr: 0x1000,
6799            data_len: 128,
6800            face_index: 0,
6801        };
6802        let key = |order| {
6803            GlyphCacheKey::new(
6804                face,
6805                7,
6806                1024,
6807                GlyphSubpixelOffsetKey::new(0, 0),
6808                TextRenderMode::LcdSubpixel,
6809                order,
6810                TextHinting::None,
6811                StemDarkening::None,
6812                400,
6813            )
6814        };
6815        assert_ne!(key(TextSubpixelOrder::Rgb), key(TextSubpixelOrder::Bgr));
6816        assert_eq!(key(TextSubpixelOrder::None), key(TextSubpixelOrder::None));
6817    }
6818
6819    #[test]
6820    fn text_atlas_shaders_use_sampled_coverage_and_dual_source_blending() {
6821        assert!(TEXT_ATLAS_SHADER_SOURCE.contains("fn apply_text_coverage"));
6822        assert!(TEXT_ATLAS_SHADER_SOURCE.contains("apply_text_coverage(sampled.a"));
6823        assert!(!TEXT_ATLAS_SHADER_SOURCE.contains("TEXT_COVERAGE_GAMMA"));
6824        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("@blend_src(0)"));
6825        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("@blend_src(1)"));
6826        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("fn apply_text_coverage"));
6827        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("apply_text_coverage(sampled.a"));
6828        assert!(!TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("TEXT_COVERAGE_GAMMA"));
6829    }
6830
6831    #[test]
6832    fn lcd_text_requires_axis_aligned_pixel_snapped_path() {
6833        assert!(allows_lcd_text(Transform::IDENTITY));
6834        assert!(!allows_lcd_text(Transform::rotation(
6835            std::f32::consts::FRAC_PI_4
6836        )));
6837        assert!(!allows_lcd_text(Transform::scale(-1.0, 1.0)));
6838        assert!(!allows_lcd_text(Transform::rotation(std::f32::consts::PI)));
6839    }
6840
6841    #[test]
6842    fn analytic_path_fill_shader_uses_symmetric_signed_distance() {
6843        assert!(ANALYTIC_PATH_SHADER_SOURCE.contains("let signed_distance"));
6844        assert!(ANALYTIC_PATH_SHADER_SOURCE.contains("0.5 - (signed_distance"));
6845        assert!(!ANALYTIC_PATH_SHADER_SOURCE.contains("1.0 - (min_distance"));
6846    }
6847
6848    #[test]
6849    fn atlas_text_snaps_repeated_stems_to_physical_pixels() {
6850        let handle = FontHandle::new(31);
6851        let mut fonts = FontRegistry::new();
6852        fonts.insert(handle, load_test_font());
6853
6854        let viewport = Size::new(260.0, 52.0);
6855        let frame = SceneFrame {
6856            window_id: WindowId::new(98),
6857            viewport,
6858            surface_size: Size::new(390.0, 78.0),
6859            scale_factor: 1.5,
6860            dirty_regions: Vec::new(),
6861            layer_updates: Vec::new(),
6862            scene: {
6863                let mut scene = Scene::new();
6864                scene.push(SceneCommand::DrawText(TextRun {
6865                    rect: Rect::new(8.0, 10.0, 220.0, 24.0),
6866                    text: "scroll".to_string(),
6867                    style: TextStyle {
6868                        font: Some(handle),
6869                        font_size: 14.0,
6870                        line_height: 18.0,
6871                        color: Color::rgba(0.12, 0.16, 0.22, 1.0),
6872                        ..TextStyle::default()
6873                    },
6874                }));
6875                scene
6876            },
6877            font_registry: Arc::new(fonts),
6878            image_registry: Arc::new(ImageRegistry::new()),
6879            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
6880        };
6881
6882        let mut text_engine = TextEngine::new().unwrap();
6883        let vertices = build_vertices(&frame, &mut text_engine).unwrap();
6884
6885        assert!(
6886            vertices.len() >= 12,
6887            "expected atlas vertices for repeated l glyphs"
6888        );
6889
6890        let first_l_left = logical_x_from_ndc(vertices[24].position[0], viewport);
6891        let second_l_left = logical_x_from_ndc(vertices[30].position[0], viewport);
6892
6893        assert!(
6894            is_physically_pixel_aligned(first_l_left, frame.scale_factor),
6895            "first l did not snap to the physical pixel grid: x={first_l_left}"
6896        );
6897        assert!(
6898            is_physically_pixel_aligned(second_l_left, frame.scale_factor),
6899            "second l did not snap to the physical pixel grid: x={second_l_left}"
6900        );
6901    }
6902
6903    #[test]
6904    fn atlas_text_is_position_invariant_at_matching_fractional_dpi_phase() {
6905        let handle = FontHandle::new(311);
6906        let mut fonts = FontRegistry::new();
6907        fonts.insert(handle, load_test_font());
6908
6909        let viewport = Size::new(260.0, 140.0);
6910        let outer_origin = Point::new(39.0, 2.3333333);
6911        let inner_origin = Point::new(58.333332, 97.666664);
6912        let delta = inner_origin - outer_origin;
6913        let frame = SceneFrame {
6914            window_id: WindowId::new(99),
6915            viewport,
6916            surface_size: Size::new(390.0, 210.0),
6917            scale_factor: 1.5,
6918            dirty_regions: Vec::new(),
6919            layer_updates: Vec::new(),
6920            scene: {
6921                let mut scene = Scene::new();
6922                for origin in [outer_origin, inner_origin] {
6923                    scene.push(SceneCommand::DrawText(TextRun {
6924                        rect: Rect::new(origin.x, origin.y, 180.0, 22.0),
6925                        text: "Light preview live updates".to_string(),
6926                        style: TextStyle {
6927                            font: Some(handle),
6928                            font_size: 14.0,
6929                            line_height: 20.0,
6930                            color: Color::rgba(0.12, 0.16, 0.22, 1.0),
6931                            ..TextStyle::default()
6932                        },
6933                    }));
6934                }
6935                scene
6936            },
6937            font_registry: Arc::new(fonts),
6938            image_registry: Arc::new(ImageRegistry::new()),
6939            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
6940        };
6941
6942        let mut text_engine = TextEngine::new().unwrap();
6943        let vertices = build_vertices(&frame, &mut text_engine).unwrap();
6944
6945        assert_eq!(
6946            vertices.len() % 2,
6947            0,
6948            "expected identical text runs to produce an even vertex count"
6949        );
6950
6951        let split = vertices.len() / 2;
6952        let (outer_vertices, inner_vertices) = vertices.split_at(split);
6953        assert_eq!(outer_vertices.len(), inner_vertices.len());
6954
6955        for (index, (outer, inner)) in outer_vertices.iter().zip(inner_vertices.iter()).enumerate()
6956        {
6957            let outer_x = logical_x_from_ndc(outer.position[0], viewport);
6958            let outer_y = logical_y_from_ndc(outer.position[1], viewport);
6959            let inner_x = logical_x_from_ndc(inner.position[0], viewport);
6960            let inner_y = logical_y_from_ndc(inner.position[1], viewport);
6961            let normalized_inner_x = inner_x - delta.x;
6962            let normalized_inner_y = inner_y - delta.y;
6963
6964            assert!(
6965                (outer_x - normalized_inner_x).abs() < 0.0001,
6966                "vertex {index} changed x after translation normalization: outer={outer_x}, inner={inner_x}, delta_x={} ",
6967                delta.x,
6968            );
6969            assert!(
6970                (outer_y - normalized_inner_y).abs() < 0.0001,
6971                "vertex {index} changed y after translation normalization: outer={outer_y}, inner={inner_y}, delta_y={} ",
6972                delta.y,
6973            );
6974            assert_eq!(
6975                outer.tex_coords, inner.tex_coords,
6976                "vertex {index} UVs differ"
6977            );
6978            assert_eq!(outer.color, inner.color, "vertex {index} colors differ");
6979        }
6980    }
6981
6982    #[test]
6983    fn renderer_text_coverage_policy_shares_glyph_cache_entries_for_explicit_policies() {
6984        let handle = FontHandle::new(33);
6985        let mut fonts = FontRegistry::new();
6986        fonts.insert(handle, load_test_font());
6987
6988        let frame = SceneFrame {
6989            window_id: WindowId::new(201),
6990            viewport: Size::new(320.0, 84.0),
6991            surface_size: Size::new(320.0, 84.0),
6992            scale_factor: 1.25,
6993            dirty_regions: Vec::new(),
6994            layer_updates: Vec::new(),
6995            scene: {
6996                let mut scene = Scene::new();
6997                scene.push(SceneCommand::FillRect {
6998                    rect: Rect::new(0.0, 0.0, 320.0, 84.0),
6999                    brush: Color::BLACK.into(),
7000                });
7001                scene.push(SceneCommand::DrawText(TextRun {
7002                    rect: Rect::new(12.0, 8.0, 296.0, 64.0),
7003                    text: "Reusable".to_string(),
7004                    style: TextStyle {
7005                        font: Some(handle),
7006                        font_size: 55.5,
7007                        line_height: 59.5,
7008                        color: Color::WHITE,
7009                        ..TextStyle::default()
7010                    },
7011                }));
7012                scene
7013            },
7014            font_registry: Arc::new(fonts),
7015            image_registry: Arc::new(ImageRegistry::new()),
7016            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7017        };
7018
7019        let mut text_engine = TextEngine::new().unwrap();
7020        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7021        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7022        let linear_stats = text_engine.glyph_cache_stats();
7023
7024        text_engine.set_text_coverage_policy(TextCoveragePolicy::TwoCoverageMinusCoverageSq);
7025        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7026        let dark_stats = text_engine.glyph_cache_stats();
7027
7028        assert!(
7029            linear_stats.0 > 0,
7030            "linear policy should populate the glyph cache"
7031        );
7032        assert!(
7033            linear_stats.2 > 0,
7034            "first pass should record glyph cache misses"
7035        );
7036        assert!(
7037            dark_stats.1 > linear_stats.1,
7038            "switching policy should reuse existing glyph cache entries"
7039        );
7040        assert_eq!(dark_stats.0, linear_stats.0);
7041        assert_eq!(dark_stats.2, linear_stats.2);
7042    }
7043
7044    #[test]
7045    fn text_render_policy_scope_overrides_and_restores_glyph_cache_policy() {
7046        let handle = FontHandle::new(36);
7047        let mut fonts = FontRegistry::new();
7048        fonts.insert(handle, load_test_font());
7049        let text_style = TextStyle {
7050            font: Some(handle),
7051            font_size: 24.0,
7052            line_height: 28.0,
7053            color: Color::WHITE,
7054            ..TextStyle::default()
7055        };
7056
7057        let frame = SceneFrame {
7058            window_id: WindowId::new(204),
7059            viewport: Size::new(120.0, 120.0),
7060            surface_size: Size::new(120.0, 120.0),
7061            scale_factor: 1.0,
7062            dirty_regions: Vec::new(),
7063            layer_updates: Vec::new(),
7064            scene: {
7065                let mut scene = Scene::new();
7066                scene.push(SceneCommand::DrawText(TextRun {
7067                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7068                    text: "I".to_string(),
7069                    style: text_style.clone(),
7070                }));
7071                scene.push(SceneCommand::PushTextRenderPolicy {
7072                    policy: TextRenderPolicy::new()
7073                        .with_coverage_policy(TextRenderCoveragePolicy::TwoCoverageMinusCoverageSq),
7074                });
7075                scene.push(SceneCommand::DrawText(TextRun {
7076                    rect: Rect::new(8.0, 44.0, 80.0, 28.0),
7077                    text: "I".to_string(),
7078                    style: text_style.clone(),
7079                }));
7080                scene.push(SceneCommand::PopTextRenderPolicy);
7081                scene.push(SceneCommand::DrawText(TextRun {
7082                    rect: Rect::new(8.0, 80.0, 80.0, 28.0),
7083                    text: "I".to_string(),
7084                    style: text_style,
7085                }));
7086                scene
7087            },
7088            font_registry: Arc::new(fonts),
7089            image_registry: Arc::new(ImageRegistry::new()),
7090            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7091        };
7092
7093        let mut text_engine = TextEngine::new().unwrap();
7094        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7095        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7096
7097        assert_eq!(text_engine.glyph_cache_stats(), (1, 2, 1));
7098    }
7099
7100    #[test]
7101    fn text_render_policy_scope_overrides_and_restores_render_mode() {
7102        let handle = FontHandle::new(37);
7103        let mut fonts = FontRegistry::new();
7104        fonts.insert(handle, load_test_font());
7105        let text_style = TextStyle {
7106            font: Some(handle),
7107            font_size: 24.0,
7108            line_height: 28.0,
7109            color: Color::WHITE,
7110            ..TextStyle::default()
7111        };
7112
7113        let frame = SceneFrame {
7114            window_id: WindowId::new(205),
7115            viewport: Size::new(120.0, 120.0),
7116            surface_size: Size::new(120.0, 120.0),
7117            scale_factor: 1.0,
7118            dirty_regions: Vec::new(),
7119            layer_updates: Vec::new(),
7120            scene: {
7121                let mut scene = Scene::new();
7122                scene.push(SceneCommand::DrawText(TextRun {
7123                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7124                    text: "I".to_string(),
7125                    style: text_style.clone(),
7126                }));
7127                scene.push(SceneCommand::PushTextRenderPolicy {
7128                    policy: TextRenderPolicy::new()
7129                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
7130                        .with_subpixel_order(TextSubpixelOrder::Rgb),
7131                });
7132                scene.push(SceneCommand::DrawText(TextRun {
7133                    rect: Rect::new(8.0, 44.0, 80.0, 28.0),
7134                    text: "I".to_string(),
7135                    style: text_style.clone(),
7136                }));
7137                scene.push(SceneCommand::PopTextRenderPolicy);
7138                scene.push(SceneCommand::DrawText(TextRun {
7139                    rect: Rect::new(8.0, 80.0, 80.0, 28.0),
7140                    text: "I".to_string(),
7141                    style: text_style,
7142                }));
7143                scene
7144            },
7145            font_registry: Arc::new(fonts),
7146            image_registry: Arc::new(ImageRegistry::new()),
7147            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7148        };
7149
7150        let mut text_engine = TextEngine::new().unwrap();
7151        text_engine.set_text_render_mode(TextRenderMode::Grayscale);
7152        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7153
7154        assert_eq!(text_engine.glyph_cache_stats(), (2, 1, 2));
7155    }
7156
7157    #[test]
7158    fn unsafe_lcd_text_transform_uses_grayscale_glyph_cache_entry() {
7159        let handle = FontHandle::new(38);
7160        let mut fonts = FontRegistry::new();
7161        fonts.insert(handle, load_test_font());
7162        let text_style = TextStyle {
7163            font: Some(handle),
7164            font_size: 24.0,
7165            line_height: 28.0,
7166            color: Color::WHITE,
7167            ..TextStyle::default()
7168        };
7169
7170        let frame = SceneFrame {
7171            window_id: WindowId::new(206),
7172            viewport: Size::new(160.0, 120.0),
7173            surface_size: Size::new(160.0, 120.0),
7174            scale_factor: 1.0,
7175            dirty_regions: Vec::new(),
7176            layer_updates: Vec::new(),
7177            scene: {
7178                let mut scene = Scene::new();
7179                scene.push(SceneCommand::DrawText(TextRun {
7180                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7181                    text: "I".to_string(),
7182                    style: text_style.clone(),
7183                }));
7184                scene.push(SceneCommand::PushTextRenderPolicy {
7185                    policy: TextRenderPolicy::new()
7186                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
7187                        .with_subpixel_order(TextSubpixelOrder::Rgb),
7188                });
7189                scene.push(SceneCommand::PushTransform {
7190                    transform: Transform::rotation(0.25),
7191                });
7192                scene.push(SceneCommand::DrawText(TextRun {
7193                    rect: Rect::new(20.0, 20.0, 80.0, 28.0),
7194                    text: "I".to_string(),
7195                    style: text_style,
7196                }));
7197                scene.push(SceneCommand::PopTransform);
7198                scene.push(SceneCommand::PopTextRenderPolicy);
7199                scene
7200            },
7201            font_registry: Arc::new(fonts),
7202            image_registry: Arc::new(ImageRegistry::new()),
7203            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7204        };
7205
7206        let mut text_engine = TextEngine::new().unwrap();
7207        text_engine.set_text_render_mode(TextRenderMode::Grayscale);
7208        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7209
7210        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7211    }
7212
7213    #[test]
7214    fn linear_text_coverage_policy_shares_glyph_cache_entries_for_light_and_dark_text() {
7215        let handle = FontHandle::new(34);
7216        let mut fonts = FontRegistry::new();
7217        fonts.insert(handle, load_test_font());
7218
7219        let frame = SceneFrame {
7220            window_id: WindowId::new(202),
7221            viewport: Size::new(240.0, 96.0),
7222            surface_size: Size::new(240.0, 96.0),
7223            scale_factor: 1.0,
7224            dirty_regions: Vec::new(),
7225            layer_updates: Vec::new(),
7226            scene: {
7227                let mut scene = Scene::new();
7228                scene.push(SceneCommand::DrawText(TextRun {
7229                    rect: Rect::new(8.0, 8.0, 100.0, 32.0),
7230                    text: "I".to_string(),
7231                    style: TextStyle {
7232                        font: Some(handle),
7233                        font_size: 24.0,
7234                        line_height: 28.0,
7235                        color: Color::BLACK,
7236                        ..TextStyle::default()
7237                    },
7238                }));
7239                scene.push(SceneCommand::DrawText(TextRun {
7240                    rect: Rect::new(8.0, 48.0, 100.0, 32.0),
7241                    text: "I".to_string(),
7242                    style: TextStyle {
7243                        font: Some(handle),
7244                        font_size: 24.0,
7245                        line_height: 28.0,
7246                        color: Color::WHITE,
7247                        ..TextStyle::default()
7248                    },
7249                }));
7250                scene
7251            },
7252            font_registry: Arc::new(fonts),
7253            image_registry: Arc::new(ImageRegistry::new()),
7254            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7255        };
7256
7257        let mut text_engine = TextEngine::new().unwrap();
7258        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7259        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7260
7261        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7262    }
7263
7264    #[test]
7265    fn default_text_coverage_policy_shares_glyph_cache_entries_across_text_colors() {
7266        let handle = FontHandle::new(35);
7267        let mut fonts = FontRegistry::new();
7268        fonts.insert(handle, load_test_font());
7269
7270        let frame = SceneFrame {
7271            window_id: WindowId::new(203),
7272            viewport: Size::new(240.0, 96.0),
7273            surface_size: Size::new(240.0, 96.0),
7274            scale_factor: 1.0,
7275            dirty_regions: Vec::new(),
7276            layer_updates: Vec::new(),
7277            scene: {
7278                let mut scene = Scene::new();
7279                scene.push(SceneCommand::DrawText(TextRun {
7280                    rect: Rect::new(8.0, 8.0, 100.0, 32.0),
7281                    text: "I".to_string(),
7282                    style: TextStyle {
7283                        font: Some(handle),
7284                        font_size: 24.0,
7285                        line_height: 28.0,
7286                        color: Color::BLACK,
7287                        ..TextStyle::default()
7288                    },
7289                }));
7290                scene.push(SceneCommand::DrawText(TextRun {
7291                    rect: Rect::new(8.0, 48.0, 100.0, 32.0),
7292                    text: "I".to_string(),
7293                    style: TextStyle {
7294                        font: Some(handle),
7295                        font_size: 24.0,
7296                        line_height: 28.0,
7297                        color: Color::WHITE,
7298                        ..TextStyle::default()
7299                    },
7300                }));
7301                scene
7302            },
7303            font_registry: Arc::new(fonts),
7304            image_registry: Arc::new(ImageRegistry::new()),
7305            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7306        };
7307
7308        let mut text_engine = TextEngine::new().unwrap();
7309        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7310
7311        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7312    }
7313
7314    #[test]
7315    fn retained_compositor_carries_active_path_clips() {
7316        let mut clip = Path::builder();
7317        clip.move_to(Point::new(8.0, 8.0))
7318            .line_to(Point::new(32.0, 8.0))
7319            .line_to(Point::new(20.0, 28.0))
7320            .close();
7321
7322        let mut scene = Scene::new();
7323        scene.push(SceneCommand::PushClipPath { path: clip.build() });
7324        scene.push(SceneCommand::FillRect {
7325            rect: Rect::new(0.0, 0.0, 40.0, 40.0),
7326            brush: Color::WHITE.into(),
7327        });
7328
7329        let mut text_engine = TextEngine::new().unwrap();
7330        let mut compositor = RetainedCompositorState::default();
7331        let ops = prepare_with_compositor(
7332            &SceneFrame {
7333                window_id: WindowId::new(6),
7334                viewport: Size::new(64.0, 64.0),
7335                surface_size: Size::new(64.0, 64.0),
7336                scale_factor: 1.0,
7337                dirty_regions: Vec::new(),
7338                layer_updates: Vec::new(),
7339                scene,
7340                font_registry: Arc::new(FontRegistry::new()),
7341                image_registry: Arc::new(ImageRegistry::new()),
7342                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7343            },
7344            &mut text_engine,
7345            &mut compositor,
7346        )
7347        .unwrap();
7348
7349        assert_eq!(ops.draw_ops.len(), 1);
7350        let op = &ops.draw_ops[0];
7351        let clip_state = &ops.clip_states[op.clip_state_index];
7352        assert!(op.clip_state_index > 0);
7353        assert_eq!(clip_state.clip_paths.len(), 1);
7354        assert!(clip_state.clip_paths[0].len > 0);
7355        assert_eq!(op.clip_rect, Some(Rect::new(8.0, 8.0, 24.0, 20.0)));
7356    }
7357
7358    #[test]
7359    fn batch_draw_ops_merges_consecutive_matching_state() {
7360        let passes = batch_draw_ops(
7361            &DrawOpArena {
7362                scene_vertices: vec![
7363                    Vertex::basic(
7364                        [0.0, 0.0],
7365                        [1.0, 1.0, 1.0, 1.0],
7366                        [0.0, 0.0],
7367                        [0.0; 4],
7368                    );
7369                    6
7370                ],
7371                clip_vertices: Vec::new(),
7372                text_instances: Vec::new(),
7373                clip_states: vec![ClipState {
7374                    clip_paths: Vec::new(),
7375                }],
7376                draw_ops: vec![
7377                    DrawOp {
7378                        kind: DrawOpKind::Solid,
7379                        vertices: PreparedVertices { start: 0, len: 3 },
7380                        clip_rect: Some(Rect::new(2.0, 4.0, 20.0, 10.0)),
7381                        clip_state_index: 0,
7382                    },
7383                    DrawOp {
7384                        kind: DrawOpKind::Solid,
7385                        vertices: PreparedVertices { start: 3, len: 3 },
7386                        clip_rect: Some(Rect::new(2.0, 4.0, 20.0, 10.0)),
7387                        clip_state_index: 0,
7388                    },
7389                ],
7390                analytic_paths: std::collections::HashMap::new(),
7391                next_analytic_path_id: 0,
7392            },
7393            Size::new(50.0, 40.0),
7394            (100, 80),
7395        );
7396
7397        assert_eq!(passes.len(), 1);
7398        assert_eq!(passes[0].draws.len(), 1);
7399        assert_eq!(passes[0].draws[0].vertices.len, 6);
7400    }
7401
7402    #[test]
7403    fn prepare_frame_batches_converts_clip_rects_to_scissors() {
7404        let prepared = prepare_frame_batches(
7405            DrawOpArena {
7406                scene_vertices: vec![
7407                    Vertex::basic(
7408                        [0.0, 0.0],
7409                        [1.0, 1.0, 1.0, 1.0],
7410                        [0.0, 0.0],
7411                        [0.0; 4],
7412                    );
7413                    6
7414                ],
7415                clip_vertices: Vec::new(),
7416                text_instances: Vec::new(),
7417                clip_states: vec![ClipState {
7418                    clip_paths: Vec::new(),
7419                }],
7420                draw_ops: vec![DrawOp {
7421                    kind: DrawOpKind::Solid,
7422                    clip_rect: Some(Rect::new(5.0, 8.0, 20.0, 10.0)),
7423                    vertices: PreparedVertices { start: 0, len: 6 },
7424                    clip_state_index: 0,
7425                }],
7426                analytic_paths: std::collections::HashMap::new(),
7427                next_analytic_path_id: 0,
7428            },
7429            Size::new(50.0, 40.0),
7430            (100, 80),
7431        );
7432
7433        assert_eq!(prepared.passes.len(), 1);
7434        assert_eq!(
7435            prepared.passes[0].draws[0].clip_rect,
7436            Some(ScissorRect {
7437                x: 10,
7438                y: 16,
7439                width: 40,
7440                height: 20,
7441            })
7442        );
7443    }
7444
7445    #[test]
7446    fn prepare_cached_passes_snap_translated_adjacent_clip_edges_without_overlap() {
7447        let passes = prepare_cached_passes(
7448            &[
7449                CachedPassBatch {
7450                    clip_paths: Vec::new(),
7451                    draws: vec![CachedDrawBatch {
7452                        kind: PreparedDrawKind::Solid,
7453                        clip_rect: Some(Rect::new(0.0, 0.0, 384.0, 128.0)),
7454                        vertices: PreparedVertices { start: 0, len: 6 },
7455                    }],
7456                },
7457                CachedPassBatch {
7458                    clip_paths: Vec::new(),
7459                    draws: vec![CachedDrawBatch {
7460                        kind: PreparedDrawKind::Solid,
7461                        clip_rect: Some(Rect::new(384.0, 0.0, 128.0, 128.0)),
7462                        vertices: PreparedVertices { start: 6, len: 6 },
7463                    }],
7464                },
7465            ],
7466            Size::new(512.0, 128.0),
7467            (768, 192),
7468            Vector::new(0.25, 0.0),
7469            None,
7470            0,
7471            0,
7472            0,
7473        );
7474
7475        let first = passes[0].draws[0].clip_rect.expect("first scissor");
7476        let second = passes[1].draws[0].clip_rect.expect("second scissor");
7477
7478        assert_eq!(first.x + first.width, second.x);
7479        assert!(first.x + first.width <= second.x);
7480    }
7481
7482    #[test]
7483    fn prepare_cached_passes_uses_external_clip_for_unclipped_draws() {
7484        let passes = prepare_cached_passes(
7485            &[CachedPassBatch {
7486                clip_paths: Vec::new(),
7487                draws: vec![CachedDrawBatch {
7488                    kind: PreparedDrawKind::Image {
7489                        handle: ImageHandle::new(99),
7490                        sampling: ImageSampling::Linear,
7491                    },
7492                    clip_rect: None,
7493                    vertices: PreparedVertices { start: 0, len: 6 },
7494                }],
7495            }],
7496            Size::new(100.0, 100.0),
7497            (100, 100),
7498            Vector::ZERO,
7499            Some(Rect::new(20.0, 30.0, 40.0, 50.0)),
7500            0,
7501            0,
7502            0,
7503        );
7504
7505        assert_eq!(passes.len(), 1);
7506        assert_eq!(passes[0].draws.len(), 1);
7507        assert_eq!(
7508            passes[0].draws[0].clip_rect,
7509            Some(ScissorRect {
7510                x: 20,
7511                y: 30,
7512                width: 40,
7513                height: 50,
7514            })
7515        );
7516    }
7517
7518    #[test]
7519    fn prepare_cached_passes_drops_draws_fully_outside_external_clip() {
7520        let passes = prepare_cached_passes(
7521            &[CachedPassBatch {
7522                clip_paths: Vec::new(),
7523                draws: vec![CachedDrawBatch {
7524                    kind: PreparedDrawKind::Image {
7525                        handle: ImageHandle::new(100),
7526                        sampling: ImageSampling::Linear,
7527                    },
7528                    clip_rect: Some(Rect::new(70.0, 70.0, 20.0, 20.0)),
7529                    vertices: PreparedVertices { start: 0, len: 6 },
7530                }],
7531            }],
7532            Size::new(100.0, 100.0),
7533            (100, 100),
7534            Vector::ZERO,
7535            Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
7536            0,
7537            0,
7538            0,
7539        );
7540
7541        assert_eq!(passes.len(), 1);
7542        assert!(passes[0].draws.is_empty());
7543    }
7544
7545    #[test]
7546    fn renderer_frame_stats_count_passes_draws_and_uploaded_vertices() {
7547        let vertex = Vertex::basic([0.0, 0.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0], [0.0; 4]);
7548        let prepared = PreparedFrameBatches {
7549            scene_vertices: vec![vertex; 9],
7550            clip_vertices: vec![vertex; 6],
7551            text_instances: Vec::new(),
7552            passes: vec![
7553                PreparedPassBatch {
7554                    clip_paths: vec![PreparedClipPath {
7555                        vertices: PreparedVertices { start: 0, len: 6 },
7556                    }],
7557                    draws: vec![
7558                        PreparedDrawBatch {
7559                            kind: PreparedDrawKind::Solid,
7560                            clip_rect: None,
7561                            vertices: PreparedVertices { start: 0, len: 3 },
7562                        },
7563                        PreparedDrawBatch {
7564                            kind: PreparedDrawKind::Solid,
7565                            clip_rect: Some(ScissorRect {
7566                                x: 0,
7567                                y: 0,
7568                                width: 10,
7569                                height: 10,
7570                            }),
7571                            vertices: PreparedVertices { start: 3, len: 6 },
7572                        },
7573                    ],
7574                },
7575                PreparedPassBatch {
7576                    clip_paths: Vec::new(),
7577                    draws: vec![PreparedDrawBatch {
7578                        kind: PreparedDrawKind::Image {
7579                            handle: ImageHandle::new(1),
7580                            sampling: ImageSampling::Linear,
7581                        },
7582                        clip_rect: None,
7583                        vertices: PreparedVertices { start: 0, len: 3 },
7584                    }],
7585                },
7586            ],
7587        };
7588
7589        let stats = RendererFrameStats::from_prepared_frame(&prepared);
7590
7591        assert_eq!(stats.pass_count, 2);
7592        assert_eq!(stats.draw_count, 4);
7593        assert_eq!(stats.uploaded_vertex_bytes, 15 * VERTEX_SIZE);
7594        assert_eq!(stats.visible_layer_count, 0);
7595        assert_eq!(stats.retained_state_update_time_us, 0);
7596    }
7597
7598    #[test]
7599    fn text_engine_shapes_text_with_font_metrics() {
7600        let text = TextRun {
7601            rect: Rect::new(8.0, 10.0, 160.0, 32.0),
7602            text: "office".to_string(),
7603            style: TextStyle::new(Color::WHITE),
7604        };
7605
7606        let text_engine = TextEngine::new().unwrap();
7607        let layout = text_engine
7608            .shape_text_run(&text, &FontRegistry::new())
7609            .unwrap();
7610
7611        assert!(!layout.glyphs().is_empty());
7612        assert!(layout.measurement().width > 0.0);
7613        assert!(layout.measurement().height >= text.style.font_size);
7614    }
7615
7616    #[test]
7617    fn build_vertices_supports_pre_shaped_text() {
7618        let text_system = TextSystem::new();
7619        let layout = text_system
7620            .shape_text_persistent(
7621                None,
7622                "scene",
7623                Size::new(80.0, 24.0),
7624                TextStyle::new(Color::WHITE),
7625                &FontRegistry::new(),
7626            )
7627            .unwrap();
7628
7629        let mut scene = Scene::new();
7630        scene.push(SceneCommand::DrawShapedText(ShapedText::new(
7631            Point::new(4.0, 6.0),
7632            &layout,
7633        )));
7634
7635        let mut text_engine = TextEngine::new().unwrap();
7636        let vertices = build_vertices(
7637            &SceneFrame {
7638                window_id: WindowId::new(11),
7639                viewport: Size::new(100.0, 80.0),
7640                surface_size: Size::new(100.0, 80.0),
7641                scale_factor: 1.0,
7642                dirty_regions: Vec::new(),
7643                layer_updates: Vec::new(),
7644                scene,
7645                font_registry: Arc::new(FontRegistry::new()),
7646                image_registry: Arc::new(ImageRegistry::new()),
7647                text_layout_registry: text_system.text_layout_registry(),
7648            },
7649            &mut text_engine,
7650        )
7651        .unwrap();
7652
7653        assert!(!vertices.is_empty());
7654    }
7655
7656    #[test]
7657    fn shaped_text_color_override_paints_cached_layout_without_changing_style() {
7658        let text_system = TextSystem::new();
7659        let layout_color = Color::rgba(0.92, 0.18, 0.16, 1.0);
7660        let paint_color = Color::rgba(0.12, 0.48, 0.86, 1.0);
7661        let layout = text_system
7662            .shape_text_persistent(
7663                None,
7664                "state",
7665                Size::new(96.0, 24.0),
7666                TextStyle::new(layout_color),
7667                &FontRegistry::new(),
7668            )
7669            .unwrap();
7670
7671        let mut scene = Scene::new();
7672        scene.push(SceneCommand::DrawShapedText(
7673            ShapedText::new(Point::new(4.0, 6.0), &layout).with_color(paint_color),
7674        ));
7675
7676        let mut text_engine = TextEngine::new().unwrap();
7677        let vertices = build_vertices(
7678            &SceneFrame {
7679                window_id: WindowId::new(311),
7680                viewport: Size::new(120.0, 80.0),
7681                surface_size: Size::new(120.0, 80.0),
7682                scale_factor: 1.0,
7683                dirty_regions: Vec::new(),
7684                layer_updates: Vec::new(),
7685                scene,
7686                font_registry: Arc::new(FontRegistry::new()),
7687                image_registry: Arc::new(ImageRegistry::new()),
7688                text_layout_registry: text_system.text_layout_registry(),
7689            },
7690            &mut text_engine,
7691        )
7692        .unwrap();
7693
7694        assert_eq!(layout.style().color, layout_color);
7695        assert!(!vertices.is_empty());
7696        assert_eq!(vertices[0].color, shader_color(paint_color));
7697    }
7698
7699    #[test]
7700    fn shaped_text_from_runtime_draw_text_snaps_to_physical_pixels_at_fractional_dpi() {
7701        let handle = FontHandle::new(312);
7702        let mut fonts = FontRegistry::new();
7703        fonts.insert(handle, load_test_font());
7704        let text_system = TextSystem::new();
7705        let layout = text_system
7706            .shape_text_persistent(
7707                None,
7708                "Widget text",
7709                Size::new(132.0, 24.0),
7710                TextStyle {
7711                    font: Some(handle),
7712                    font_size: 14.0,
7713                    line_height: 19.0,
7714                    color: Color::rgba(0.12, 0.16, 0.22, 1.0),
7715                    ..TextStyle::default()
7716                },
7717                &fonts,
7718            )
7719            .unwrap();
7720        let viewport = Size::new(220.0, 72.0);
7721        let origin = Point::new(18.333_332, 10.666_667);
7722        let mut scene = Scene::new();
7723        scene.push(SceneCommand::DrawShapedText(ShapedText::new(
7724            origin, &layout,
7725        )));
7726
7727        let frame = SceneFrame {
7728            window_id: WindowId::new(312),
7729            viewport,
7730            surface_size: Size::new(330.0, 108.0),
7731            scale_factor: 1.5,
7732            dirty_regions: Vec::new(),
7733            layer_updates: Vec::new(),
7734            scene,
7735            font_registry: Arc::new(fonts),
7736            image_registry: Arc::new(ImageRegistry::new()),
7737            text_layout_registry: text_system.text_layout_registry(),
7738        };
7739
7740        let mut text_engine = TextEngine::new().unwrap();
7741        let mut compositor = RetainedCompositorState::default();
7742        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor)
7743            .expect("shaped text frame should prepare");
7744        let text_op = draw_ops
7745            .draw_ops
7746            .iter()
7747            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
7748            .expect("shaped text should emit atlas instances");
7749        let start = text_op.vertices.start as usize;
7750        let end = start + text_op.vertices.len as usize;
7751        let instances = &draw_ops.text_instances[start..end];
7752        assert!(!instances.is_empty());
7753        for (index, instance) in instances.iter().enumerate() {
7754            let x = logical_x_from_ndc(instance.top_left[0], viewport);
7755            let y = logical_y_from_ndc(instance.top_left[1], viewport);
7756            assert!(
7757                is_physically_pixel_aligned(x, frame.scale_factor),
7758                "shaped text instance {index} x was not physically aligned: {x}"
7759            );
7760            assert!(
7761                is_physically_pixel_aligned(y, frame.scale_factor),
7762                "shaped text instance {index} y was not physically aligned: {y}"
7763            );
7764        }
7765    }
7766
7767    #[test]
7768    fn shaped_text_window_snaps_to_physical_pixels_at_fractional_dpi() {
7769        let handle = FontHandle::new(313);
7770        let mut fonts = FontRegistry::new();
7771        fonts.insert(handle, load_test_font());
7772        let text_system = TextSystem::new();
7773        let layout = text_system
7774            .shape_text_persistent(
7775                None,
7776                "First line wraps into a second visible line",
7777                Size::new(84.0, 72.0),
7778                TextStyle {
7779                    font: Some(handle),
7780                    font_size: 14.0,
7781                    line_height: 19.0,
7782                    color: Color::rgba(0.12, 0.16, 0.22, 1.0),
7783                    ..TextStyle::default()
7784                },
7785                &fonts,
7786            )
7787            .unwrap();
7788        assert!(
7789            layout.lines().len() > 1,
7790            "test layout must produce a non-empty line window"
7791        );
7792        assert!(
7793            layout.line_window(1..2).glyph_instances().len() > 0,
7794            "test layout line window must contain glyphs"
7795        );
7796        let viewport = Size::new(220.0, 96.0);
7797        let origin = Point::new(18.333_332, 10.666_667);
7798        let mut scene = Scene::new();
7799        scene.push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
7800            origin,
7801            &layout,
7802            1..2,
7803        )));
7804
7805        let frame = SceneFrame {
7806            window_id: WindowId::new(313),
7807            viewport,
7808            surface_size: Size::new(330.0, 144.0),
7809            scale_factor: 1.5,
7810            dirty_regions: Vec::new(),
7811            layer_updates: Vec::new(),
7812            scene,
7813            font_registry: Arc::new(fonts),
7814            image_registry: Arc::new(ImageRegistry::new()),
7815            text_layout_registry: text_system.text_layout_registry(),
7816        };
7817
7818        let mut text_engine = TextEngine::new().unwrap();
7819        let mut compositor = RetainedCompositorState::default();
7820        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor)
7821            .expect("windowed shaped text frame should prepare");
7822        let text_op = draw_ops
7823            .draw_ops
7824            .iter()
7825            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
7826            .expect("windowed shaped text should emit atlas instances");
7827        let start = text_op.vertices.start as usize;
7828        let end = start + text_op.vertices.len as usize;
7829        let instances = &draw_ops.text_instances[start..end];
7830        assert!(!instances.is_empty());
7831        for (index, instance) in instances.iter().enumerate() {
7832            let x = logical_x_from_ndc(instance.top_left[0], viewport);
7833            let y = logical_y_from_ndc(instance.top_left[1], viewport);
7834            assert!(
7835                is_physically_pixel_aligned(x, frame.scale_factor),
7836                "windowed shaped text instance {index} x was not physically aligned: {x}"
7837            );
7838            assert!(
7839                is_physically_pixel_aligned(y, frame.scale_factor),
7840                "windowed shaped text instance {index} y was not physically aligned: {y}"
7841            );
7842        }
7843    }
7844
7845    #[test]
7846    fn text_engine_reuses_cached_glyph_atlas_entries_across_repeated_builds() {
7847        let mut scene = Scene::new();
7848        scene.push(SceneCommand::DrawText(TextRun {
7849            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
7850            text: "abc".to_string(),
7851            style: TextStyle::new(Color::WHITE),
7852        }));
7853
7854        let frame = SceneFrame {
7855            window_id: WindowId::new(12),
7856            viewport: Size::new(160.0, 60.0),
7857            surface_size: Size::new(160.0, 60.0),
7858            scale_factor: 1.0,
7859            dirty_regions: Vec::new(),
7860            layer_updates: Vec::new(),
7861            scene,
7862            font_registry: Arc::new(FontRegistry::new()),
7863            image_registry: Arc::new(ImageRegistry::new()),
7864            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7865        };
7866
7867        let mut text_engine = TextEngine::new().unwrap();
7868        let first = build_vertices(&frame, &mut text_engine).unwrap();
7869        assert!(!first.is_empty());
7870        assert_eq!(first.len(), 18);
7871        assert!(first.iter().any(|vertex| vertex.tex_coords != [0.0, 0.0]));
7872        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
7873
7874        let second = build_vertices(&frame, &mut text_engine).unwrap();
7875        assert_eq!(first.len(), second.len());
7876        assert!(first.iter().zip(&second).all(|(left, right)| {
7877            left.position == right.position
7878                && left.color == right.color
7879                && left.tex_coords == right.tex_coords
7880        }));
7881        assert_eq!(text_engine.glyph_cache_stats(), (3, 3, 3));
7882    }
7883
7884    #[test]
7885    fn text_engine_parses_swash_face_once_per_text_run_when_glyphs_miss() {
7886        let mut scene = Scene::new();
7887        scene.push(SceneCommand::DrawText(TextRun {
7888            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
7889            text: "abc".to_string(),
7890            style: TextStyle::new(Color::WHITE),
7891        }));
7892
7893        let frame = SceneFrame {
7894            window_id: WindowId::new(15),
7895            viewport: Size::new(160.0, 60.0),
7896            surface_size: Size::new(160.0, 60.0),
7897            scale_factor: 1.0,
7898            dirty_regions: Vec::new(),
7899            layer_updates: Vec::new(),
7900            scene,
7901            font_registry: Arc::new(FontRegistry::new()),
7902            image_registry: Arc::new(ImageRegistry::new()),
7903            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7904        };
7905
7906        let mut text_engine = TextEngine::new().unwrap();
7907        let first = build_vertices(&frame, &mut text_engine).unwrap();
7908        assert!(!first.is_empty());
7909        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
7910        assert_eq!(text_engine.swash_face_parse_count(), 1);
7911
7912        let second = build_vertices(&frame, &mut text_engine).unwrap();
7913        assert_eq!(first.len(), second.len());
7914        assert_eq!(text_engine.glyph_cache_stats(), (3, 3, 3));
7915        assert_eq!(text_engine.swash_face_parse_count(), 1);
7916    }
7917
7918    #[test]
7919    fn text_engine_buckets_cached_glyph_atlas_entries_by_scale() {
7920        let mut scene = Scene::new();
7921        scene.push(SceneCommand::DrawText(TextRun {
7922            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
7923            text: "abc".to_string(),
7924            style: TextStyle::new(Color::WHITE),
7925        }));
7926
7927        let base_frame = SceneFrame {
7928            window_id: WindowId::new(13),
7929            viewport: Size::new(160.0, 60.0),
7930            surface_size: Size::new(160.0, 60.0),
7931            scale_factor: 1.0,
7932            dirty_regions: Vec::new(),
7933            layer_updates: Vec::new(),
7934            scene,
7935            font_registry: Arc::new(FontRegistry::new()),
7936            image_registry: Arc::new(ImageRegistry::new()),
7937            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7938        };
7939
7940        let mut scaled_scene = Scene::new();
7941        scaled_scene.push(SceneCommand::DrawText(TextRun {
7942            rect: Rect::new(4.0, 6.0, 120.0, 56.0),
7943            text: "abc".to_string(),
7944            style: TextStyle {
7945                font_size: 28.0,
7946                line_height: 32.0,
7947                ..TextStyle::new(Color::WHITE)
7948            },
7949        }));
7950
7951        let scaled_frame = SceneFrame {
7952            window_id: WindowId::new(14),
7953            viewport: Size::new(160.0, 80.0),
7954            surface_size: Size::new(160.0, 80.0),
7955            scale_factor: 1.0,
7956            dirty_regions: Vec::new(),
7957            layer_updates: Vec::new(),
7958            scene: scaled_scene,
7959            font_registry: Arc::new(FontRegistry::new()),
7960            image_registry: Arc::new(ImageRegistry::new()),
7961            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7962        };
7963
7964        let mut text_engine = TextEngine::new().unwrap();
7965        let first = build_vertices(&base_frame, &mut text_engine).unwrap();
7966        assert!(!first.is_empty());
7967        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
7968
7969        let second = build_vertices(&scaled_frame, &mut text_engine).unwrap();
7970        assert!(!second.is_empty());
7971        assert_eq!(text_engine.glyph_cache_stats(), (6, 0, 6));
7972    }
7973
7974    #[test]
7975    fn retained_compositor_reuses_cached_path_meshes_across_retained_packets() {
7976        let layer_id = WidgetId::new(70);
7977        let descriptor = SceneLayerDescriptor::new(
7978            SceneLayerId::from_widget(layer_id),
7979            layer_id,
7980            Rect::new(0.0, 0.0, 512.0, 128.0),
7981        )
7982        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
7983        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
7984        .with_cache_policy(LayerCachePolicy::Cached);
7985
7986        let mut layer_scene = Scene::new();
7987        layer_scene.push(SceneCommand::FillPath {
7988            path: Path::rect(Rect::new(0.0, 0.0, 512.0, 128.0)),
7989            brush: Color::rgba(0.24, 0.48, 0.72, 1.0).into(),
7990        });
7991
7992        let mut scene = Scene::new();
7993        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
7994            descriptor.clone(),
7995            layer_scene,
7996        )));
7997
7998        let frame = SceneFrame {
7999            window_id: WindowId::new(30),
8000            viewport: Size::new(512.0, 128.0),
8001            surface_size: Size::new(512.0, 128.0),
8002            scale_factor: 1.0,
8003            dirty_regions: Vec::new(),
8004            layer_updates: vec![
8005                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
8006                    .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
8007            ],
8008            scene,
8009            font_registry: Arc::new(FontRegistry::new()),
8010            image_registry: Arc::new(ImageRegistry::new()),
8011            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8012        };
8013
8014        let mut text_engine = TextEngine::new().unwrap();
8015        let mut compositor = RetainedCompositorState::default();
8016        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8017
8018        assert!(!draw_ops.draw_ops.is_empty());
8019        assert_eq!(compositor.path_cache.stats(), (0, 0, 0));
8020        assert_eq!(draw_ops.analytic_paths.len(), 1);
8021        assert!(
8022            draw_ops
8023                .draw_ops
8024                .iter()
8025                .any(|draw| matches!(draw.kind, DrawOpKind::AnalyticPath { .. }))
8026        );
8027    }
8028
8029    #[test]
8030    fn retained_compositor_uses_analytic_stroke_paths_across_retained_packets() {
8031        let layer_id = WidgetId::new(71);
8032        let descriptor = SceneLayerDescriptor::new(
8033            SceneLayerId::from_widget(layer_id),
8034            layer_id,
8035            Rect::new(0.0, 0.0, 512.0, 128.0),
8036        )
8037        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8038        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8039        .with_cache_policy(LayerCachePolicy::Cached);
8040
8041        let mut stroke_path = Path::builder();
8042        stroke_path
8043            .move_to(Point::new(8.0, 24.0))
8044            .line_to(Point::new(180.0, 92.0))
8045            .line_to(Point::new(340.0, 20.0))
8046            .line_to(Point::new(500.0, 92.0));
8047
8048        let mut layer_scene = Scene::new();
8049        layer_scene.push(SceneCommand::StrokePath {
8050            path: stroke_path.build(),
8051            brush: Color::rgba(0.92, 0.46, 0.18, 1.0).into(),
8052            stroke: StrokeStyle::new(12.0),
8053        });
8054
8055        let mut scene = Scene::new();
8056        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8057            descriptor.clone(),
8058            layer_scene,
8059        )));
8060
8061        let frame = SceneFrame {
8062            window_id: WindowId::new(31),
8063            viewport: Size::new(512.0, 128.0),
8064            surface_size: Size::new(512.0, 128.0),
8065            scale_factor: 1.0,
8066            dirty_regions: Vec::new(),
8067            layer_updates: vec![
8068                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
8069                    .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
8070            ],
8071            scene,
8072            font_registry: Arc::new(FontRegistry::new()),
8073            image_registry: Arc::new(ImageRegistry::new()),
8074            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8075        };
8076
8077        let mut text_engine = TextEngine::new().unwrap();
8078        let mut compositor = RetainedCompositorState::default();
8079        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8080
8081        assert!(!draw_ops.draw_ops.is_empty());
8082        assert_eq!(compositor.path_cache.stats(), (0, 0, 0));
8083        assert_eq!(draw_ops.analytic_paths.len(), 1);
8084        assert!(
8085            draw_ops
8086                .draw_ops
8087                .iter()
8088                .any(|draw| matches!(draw.kind, DrawOpKind::AnalyticPath { .. }))
8089        );
8090    }
8091
8092    #[test]
8093    fn retained_compositor_reuses_layer_packets_until_content_changes() {
8094        let layer_id = WidgetId::new(41);
8095        let mut child_scene = Scene::new();
8096        child_scene.push(SceneCommand::FillRect {
8097            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8098            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8099        });
8100
8101        let mut scene = Scene::new();
8102        scene.push(SceneCommand::Clear(Color::BLACK));
8103        scene.push(SceneCommand::Layer(SceneLayer::new(
8104            layer_id,
8105            Rect::new(4.0, 6.0, 32.0, 24.0),
8106            child_scene,
8107        )));
8108
8109        let mut frame = SceneFrame {
8110            window_id: WindowId::new(21),
8111            viewport: Size::new(96.0, 64.0),
8112            surface_size: Size::new(96.0, 64.0),
8113            scale_factor: 1.0,
8114            dirty_regions: Vec::new(),
8115            layer_updates: content_updates([layer_id]),
8116            scene,
8117            font_registry: Arc::new(FontRegistry::new()),
8118            image_registry: Arc::new(ImageRegistry::new()),
8119            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8120        };
8121
8122        let mut text_engine = TextEngine::new().unwrap();
8123        let mut compositor = RetainedCompositorState::default();
8124        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8125        assert!(compositor.last_frame_stats.packet_build_count > 0);
8126        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8127        let first_signature = packet_signature(&compositor, layer_container);
8128        let first_content_version =
8129            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8130
8131        frame.layer_updates.clear();
8132        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8133        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8134        assert_eq!(first.scene_vertices, second.scene_vertices);
8135        assert_eq!(
8136            first_signature,
8137            packet_signature(&compositor, layer_container)
8138        );
8139
8140        frame.layer_updates = content_updates([layer_id]);
8141        let mut updated_child_scene = Scene::new();
8142        updated_child_scene.push(SceneCommand::FillRect {
8143            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8144            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8145        });
8146        updated_child_scene.push(SceneCommand::FillRect {
8147            rect: Rect::new(12.0, 10.0, 8.0, 8.0),
8148            brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8149        });
8150        assert!(frame.scene.replace_layer(
8151            layer_id,
8152            SceneLayer::new(
8153                layer_id,
8154                Rect::new(4.0, 6.0, 32.0, 24.0),
8155                updated_child_scene
8156            ),
8157        ));
8158        let third = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8159        assert!(compositor.last_frame_stats.packet_build_count > 0);
8160        let third_signature = packet_signature(&compositor, layer_container);
8161        let third_content_version =
8162            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8163
8164        assert!(third_content_version > first_content_version);
8165        assert_ne!(first_signature, third_signature);
8166        assert_ne!(first.scene_vertices, third.scene_vertices);
8167    }
8168
8169    #[test]
8170    fn retained_compositor_skips_packet_rebuild_for_unchanged_content_updates() {
8171        let layer_id = WidgetId::new(411);
8172        let mut child_scene = Scene::new();
8173        child_scene.push(SceneCommand::FillRect {
8174            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8175            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8176        });
8177
8178        let mut scene = Scene::new();
8179        scene.push(SceneCommand::Layer(SceneLayer::new(
8180            layer_id,
8181            Rect::new(4.0, 6.0, 32.0, 24.0),
8182            child_scene,
8183        )));
8184
8185        let mut frame = SceneFrame {
8186            window_id: WindowId::new(211),
8187            viewport: Size::new(96.0, 64.0),
8188            surface_size: Size::new(96.0, 64.0),
8189            scale_factor: 1.0,
8190            dirty_regions: Vec::new(),
8191            layer_updates: content_updates([layer_id]),
8192            scene,
8193            font_registry: Arc::new(FontRegistry::new()),
8194            image_registry: Arc::new(ImageRegistry::new()),
8195            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8196        };
8197
8198        let mut text_engine = TextEngine::new().unwrap();
8199        let mut compositor = RetainedCompositorState::default();
8200        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8201        assert!(compositor.last_frame_stats.packet_build_count > 0);
8202        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8203        let first_signature = packet_signature(&compositor, layer_container);
8204
8205        frame.layer_updates = content_updates([layer_id]);
8206        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8207
8208        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8209        assert_eq!(
8210            first_signature,
8211            packet_signature(&compositor, layer_container)
8212        );
8213        assert_eq!(first.scene_vertices, second.scene_vertices);
8214    }
8215
8216    #[test]
8217    fn retained_compositor_reuses_parent_packets_when_only_child_content_changes() {
8218        let parent_id = WidgetId::new(51);
8219        let child_id = WidgetId::new(52);
8220
8221        let mut child_scene = Scene::new();
8222        child_scene.push(SceneCommand::FillRect {
8223            rect: Rect::new(8.0, 8.0, 10.0, 10.0),
8224            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8225        });
8226
8227        let mut parent_scene = Scene::new();
8228        parent_scene.push(SceneCommand::FillRect {
8229            rect: Rect::new(4.0, 4.0, 24.0, 24.0),
8230            brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
8231        });
8232        parent_scene.push(SceneCommand::Layer(SceneLayer::new(
8233            child_id,
8234            Rect::new(8.0, 8.0, 10.0, 10.0),
8235            child_scene,
8236        )));
8237
8238        let mut scene = Scene::new();
8239        scene.push(SceneCommand::Layer(SceneLayer::new(
8240            parent_id,
8241            Rect::new(4.0, 4.0, 24.0, 24.0),
8242            parent_scene,
8243        )));
8244
8245        let mut frame = SceneFrame {
8246            window_id: WindowId::new(22),
8247            viewport: Size::new(64.0, 64.0),
8248            surface_size: Size::new(64.0, 64.0),
8249            scale_factor: 1.0,
8250            dirty_regions: Vec::new(),
8251            layer_updates: content_updates([parent_id, child_id]),
8252            scene,
8253            font_registry: Arc::new(FontRegistry::new()),
8254            image_registry: Arc::new(ImageRegistry::new()),
8255            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8256        };
8257
8258        let mut text_engine = TextEngine::new().unwrap();
8259        let mut compositor = RetainedCompositorState::default();
8260        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8261        let parent_container = CompositionContainerId::Layer(SceneLayerId::from_widget(parent_id));
8262        let child_container = CompositionContainerId::Layer(SceneLayerId::from_widget(child_id));
8263        let parent_signature = packet_signature(&compositor, parent_container);
8264        let child_signature = packet_signature(&compositor, child_container);
8265
8266        frame.layer_updates.clear();
8267        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8268        assert_eq!(first.scene_vertices, second.scene_vertices);
8269        assert_eq!(
8270            parent_signature,
8271            packet_signature(&compositor, parent_container)
8272        );
8273        assert_eq!(
8274            child_signature,
8275            packet_signature(&compositor, child_container)
8276        );
8277
8278        let mut updated_child_scene = Scene::new();
8279        updated_child_scene.push(SceneCommand::FillRect {
8280            rect: Rect::new(8.0, 8.0, 10.0, 10.0),
8281            brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8282        });
8283
8284        let mut updated_parent_scene = Scene::new();
8285        updated_parent_scene.push(SceneCommand::FillRect {
8286            rect: Rect::new(4.0, 4.0, 24.0, 24.0),
8287            brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
8288        });
8289        updated_parent_scene.push(SceneCommand::Layer(SceneLayer::new(
8290            child_id,
8291            Rect::new(8.0, 8.0, 10.0, 10.0),
8292            updated_child_scene,
8293        )));
8294        assert!(frame.scene.replace_layer(
8295            parent_id,
8296            SceneLayer::new(
8297                parent_id,
8298                Rect::new(4.0, 4.0, 24.0, 24.0),
8299                updated_parent_scene
8300            ),
8301        ));
8302
8303        frame.layer_updates = content_updates([child_id]);
8304        let third = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8305
8306        assert_eq!(
8307            parent_signature,
8308            packet_signature(&compositor, parent_container)
8309        );
8310        assert_ne!(
8311            child_signature,
8312            packet_signature(&compositor, child_container)
8313        );
8314        assert_ne!(first.scene_vertices, third.scene_vertices);
8315    }
8316
8317    #[test]
8318    fn retained_compositor_reuses_direct_packets_across_layer_translation() {
8319        let layer_id = WidgetId::new(53);
8320
8321        let build_layer = |x: f32| {
8322            let descriptor = SceneLayerDescriptor::new(
8323                SceneLayerId::from_widget(layer_id),
8324                layer_id,
8325                Rect::new(x, 10.0, 80.0, 36.0),
8326            )
8327            .with_content_bounds(Rect::new(x, 10.0, 80.0, 36.0))
8328            .with_paint_bounds(Rect::new(x, 10.0, 80.0, 36.0))
8329            .with_cache_policy(LayerCachePolicy::Direct);
8330
8331            let mut layer_scene = Scene::new();
8332            layer_scene.push(SceneCommand::FillRect {
8333                rect: Rect::new(x, 10.0, 80.0, 36.0),
8334                brush: Color::rgba(0.82, 0.36, 0.18, 1.0).into(),
8335            });
8336
8337            SceneLayer::from_descriptor(descriptor, layer_scene)
8338        };
8339
8340        let mut scene = Scene::new();
8341        scene.push(SceneCommand::Layer(build_layer(8.0)));
8342
8343        let mut frame = SceneFrame {
8344            window_id: WindowId::new(24),
8345            viewport: Size::new(160.0, 80.0),
8346            surface_size: Size::new(160.0, 80.0),
8347            scale_factor: 1.0,
8348            dirty_regions: Vec::new(),
8349            layer_updates: content_updates([layer_id]),
8350            scene,
8351            font_registry: Arc::new(FontRegistry::new()),
8352            image_registry: Arc::new(ImageRegistry::new()),
8353            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8354        };
8355
8356        let mut text_engine = TextEngine::new().unwrap();
8357        let mut compositor = RetainedCompositorState::default();
8358        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8359        assert!(compositor.last_frame_stats.packet_build_count > 0);
8360        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8361        let first_signature = packet_signature(&compositor, layer_container);
8362        let first_content_version =
8363            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8364
8365        frame.scene = {
8366            let mut next = Scene::new();
8367            next.push(SceneCommand::Layer(build_layer(44.0)));
8368            next
8369        };
8370        frame.layer_updates = vec![SceneLayerUpdate::from_descriptor(
8371            SceneLayerUpdateKind::Transform,
8372            SceneLayerDescriptor::new(
8373                SceneLayerId::from_widget(layer_id),
8374                layer_id,
8375                Rect::new(44.0, 10.0, 80.0, 36.0),
8376            )
8377            .with_content_bounds(Rect::new(44.0, 10.0, 80.0, 36.0))
8378            .with_paint_bounds(Rect::new(44.0, 10.0, 80.0, 36.0))
8379            .with_cache_policy(LayerCachePolicy::Direct),
8380        )];
8381
8382        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8383        let second_signature = packet_signature(&compositor, layer_container);
8384        let second_content_version =
8385            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8386
8387        assert_eq!(first_signature, second_signature);
8388        assert_eq!(first_content_version, second_content_version);
8389        assert_eq!(compositor.last_frame_stats.direct_packets, 1);
8390        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8391        assert_ne!(first.scene_vertices, second.scene_vertices);
8392    }
8393
8394    #[test]
8395    fn retained_compositor_reuses_direct_packets_across_clip_only_updates() {
8396        let layer_id = WidgetId::new(54);
8397        let descriptor = SceneLayerDescriptor::new(
8398            SceneLayerId::from_widget(layer_id),
8399            layer_id,
8400            Rect::new(8.0, 8.0, 96.0, 48.0),
8401        )
8402        .with_content_bounds(Rect::new(8.0, 8.0, 96.0, 48.0))
8403        .with_paint_bounds(Rect::new(8.0, 8.0, 96.0, 48.0))
8404        .with_cache_policy(LayerCachePolicy::Direct);
8405
8406        let build_layer = || {
8407            let mut layer_scene = Scene::new();
8408            layer_scene.push(SceneCommand::FillRect {
8409                rect: Rect::new(8.0, 8.0, 96.0, 48.0),
8410                brush: Color::rgba(0.16, 0.52, 0.84, 1.0).into(),
8411            });
8412            SceneLayer::from_descriptor(descriptor.clone(), layer_scene)
8413        };
8414
8415        let build_scene = |clip: Rect| {
8416            let mut scene = Scene::new();
8417            scene.push(SceneCommand::PushClip { rect: clip });
8418            scene.push(SceneCommand::Layer(build_layer()));
8419            scene.push(SceneCommand::PopClip);
8420            scene
8421        };
8422
8423        let mut frame = SceneFrame {
8424            window_id: WindowId::new(25),
8425            viewport: Size::new(160.0, 96.0),
8426            surface_size: Size::new(160.0, 96.0),
8427            scale_factor: 1.0,
8428            dirty_regions: Vec::new(),
8429            layer_updates: content_updates([layer_id]),
8430            scene: build_scene(Rect::new(0.0, 0.0, 160.0, 96.0)),
8431            font_registry: Arc::new(FontRegistry::new()),
8432            image_registry: Arc::new(ImageRegistry::new()),
8433            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8434        };
8435
8436        let mut text_engine = TextEngine::new().unwrap();
8437        let mut compositor = RetainedCompositorState::default();
8438        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8439        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8440        let first_signature = packet_signature(&compositor, layer_container);
8441        let first_content_version =
8442            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8443        let first_clip_rects = first
8444            .draw_ops
8445            .iter()
8446            .map(|draw_op| draw_op.clip_rect)
8447            .collect::<Vec<_>>();
8448
8449        frame.scene = build_scene(Rect::new(24.0, 8.0, 64.0, 48.0));
8450        frame.layer_updates = vec![SceneLayerUpdate::from_descriptor(
8451            SceneLayerUpdateKind::Clip,
8452            descriptor.clone(),
8453        )];
8454
8455        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8456        let second_signature = packet_signature(&compositor, layer_container);
8457        let second_content_version =
8458            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8459        let second_clip_rects = second
8460            .draw_ops
8461            .iter()
8462            .map(|draw_op| draw_op.clip_rect)
8463            .collect::<Vec<_>>();
8464
8465        assert_eq!(first_signature, second_signature);
8466        assert_eq!(first_content_version, second_content_version);
8467        assert_eq!(compositor.last_frame_stats.direct_packets, 1);
8468        assert_eq!(first.scene_vertices, second.scene_vertices);
8469        assert_ne!(first_clip_rects, second_clip_rects);
8470    }
8471
8472    #[test]
8473    fn retained_compositor_rebuilds_retained_packets_across_ancestor_clip_updates() {
8474        let shell_id = WidgetId::new(55);
8475        let scroll_id = WidgetId::new(56);
8476        let content_id = WidgetId::new(57);
8477
8478        let shell_descriptor = SceneLayerDescriptor::new(
8479            SceneLayerId::from_widget(shell_id),
8480            shell_id,
8481            Rect::new(0.0, 0.0, 220.0, 180.0),
8482        )
8483        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 180.0))
8484        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 180.0))
8485        .with_cache_policy(LayerCachePolicy::Direct);
8486
8487        let scroll_descriptor = SceneLayerDescriptor::new(
8488            SceneLayerId::from_widget(scroll_id),
8489            scroll_id,
8490            Rect::new(0.0, 0.0, 220.0, 360.0),
8491        )
8492        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8493        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8494        .with_cache_policy(LayerCachePolicy::Cached)
8495        .with_composition_mode(LayerCompositionMode::Scroll);
8496
8497        let content_descriptor = SceneLayerDescriptor::new(
8498            SceneLayerId::from_widget(content_id),
8499            content_id,
8500            Rect::new(0.0, 0.0, 220.0, 360.0),
8501        )
8502        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8503        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8504        .with_cache_policy(LayerCachePolicy::Direct);
8505
8506        let build_scene = |clip: Rect| {
8507            let mut content_scene = Scene::new();
8508            content_scene.push(SceneCommand::FillRect {
8509                rect: Rect::new(0.0, 0.0, 220.0, 360.0),
8510                brush: Color::WHITE.into(),
8511            });
8512            content_scene.push(SceneCommand::FillRect {
8513                rect: Rect::new(16.0, 16.0, 188.0, 120.0),
8514                brush: Color::rgba(0.28, 0.20, 0.86, 1.0).into(),
8515            });
8516            content_scene.push(SceneCommand::FillRect {
8517                rect: Rect::new(16.0, 220.0, 188.0, 120.0),
8518                brush: Color::rgba(0.14, 0.55, 0.82, 1.0).into(),
8519            });
8520
8521            let mut scroll_scene = Scene::new();
8522            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8523                content_descriptor.clone(),
8524                content_scene,
8525            )));
8526
8527            let mut shell_scene = Scene::new();
8528            shell_scene.push(SceneCommand::PushClip { rect: clip });
8529            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8530                scroll_descriptor.clone(),
8531                scroll_scene,
8532            )));
8533            shell_scene.push(SceneCommand::PopClip);
8534
8535            let mut scene = Scene::new();
8536            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8537                shell_descriptor.clone(),
8538                shell_scene,
8539            )));
8540            scene
8541        };
8542
8543        let mut frame = SceneFrame {
8544            window_id: WindowId::new(26),
8545            viewport: Size::new(220.0, 180.0),
8546            surface_size: Size::new(220.0, 180.0),
8547            scale_factor: 1.0,
8548            dirty_regions: Vec::new(),
8549            layer_updates: vec![
8550                SceneLayerUpdate::from_descriptor(
8551                    SceneLayerUpdateKind::Content,
8552                    scroll_descriptor.clone(),
8553                )
8554                .with_damage(scroll_descriptor.paint_bounds),
8555            ],
8556            scene: build_scene(Rect::new(0.0, 0.0, 220.0, 180.0)),
8557            font_registry: Arc::new(FontRegistry::new()),
8558            image_registry: Arc::new(ImageRegistry::new()),
8559            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8560        };
8561
8562        let mut text_engine = TextEngine::new().unwrap();
8563        let mut compositor = RetainedCompositorState::default();
8564        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8565        let first_clip_rects = first
8566            .draw_ops
8567            .iter()
8568            .map(|draw_op| draw_op.clip_rect)
8569            .collect::<Vec<_>>();
8570
8571        frame.scene = build_scene(Rect::new(0.0, 0.0, 220.0, 96.0));
8572        frame.layer_updates = vec![
8573            SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Clip, shell_descriptor.clone())
8574                .with_damage(shell_descriptor.paint_bounds),
8575        ];
8576
8577        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8578        let second_clip_rects = second
8579            .draw_ops
8580            .iter()
8581            .map(|draw_op| draw_op.clip_rect)
8582            .collect::<Vec<_>>();
8583
8584        assert_ne!(first_clip_rects, second_clip_rects);
8585    }
8586
8587    #[test]
8588    fn retained_compositor_prunes_removed_layers_and_packets() {
8589        let removed_id = WidgetId::new(61);
8590        let replacement_id = WidgetId::new(62);
8591
8592        let mut first_scene = Scene::new();
8593        first_scene.push(SceneCommand::Layer(SceneLayer::new(
8594            removed_id,
8595            Rect::new(0.0, 0.0, 24.0, 24.0),
8596            {
8597                let mut scene = Scene::new();
8598                scene.push(SceneCommand::FillRect {
8599                    rect: Rect::new(0.0, 0.0, 24.0, 24.0),
8600                    brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8601                });
8602                scene
8603            },
8604        )));
8605
8606        let mut frame = SceneFrame {
8607            window_id: WindowId::new(23),
8608            viewport: Size::new(64.0, 64.0),
8609            surface_size: Size::new(64.0, 64.0),
8610            scale_factor: 1.0,
8611            dirty_regions: Vec::new(),
8612            layer_updates: content_updates([removed_id]),
8613            scene: first_scene,
8614            font_registry: Arc::new(FontRegistry::new()),
8615            image_registry: Arc::new(ImageRegistry::new()),
8616            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8617        };
8618
8619        let mut text_engine = TextEngine::new().unwrap();
8620        let mut compositor = RetainedCompositorState::default();
8621        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8622        let removed_layer_id = SceneLayerId::from_widget(removed_id);
8623        let replacement_layer_id = SceneLayerId::from_widget(replacement_id);
8624        let removed_packet_id = RetainedPacketId {
8625            container: CompositionContainerId::Layer(removed_layer_id),
8626            segment_index: 0,
8627        };
8628        assert!(compositor.layers.contains_key(&removed_layer_id));
8629        assert!(compositor.packets.contains_key(&removed_packet_id));
8630
8631        let mut second_scene = Scene::new();
8632        second_scene.push(SceneCommand::Layer(SceneLayer::new(
8633            replacement_id,
8634            Rect::new(8.0, 8.0, 24.0, 24.0),
8635            {
8636                let mut scene = Scene::new();
8637                scene.push(SceneCommand::FillRect {
8638                    rect: Rect::new(8.0, 8.0, 24.0, 24.0),
8639                    brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8640                });
8641                scene
8642            },
8643        )));
8644        frame.scene = second_scene;
8645        frame.layer_updates = content_updates([replacement_id]);
8646
8647        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8648
8649        assert!(!compositor.layers.contains_key(&removed_layer_id));
8650        assert!(!compositor.packets.contains_key(&removed_packet_id));
8651        assert!(compositor.layers.contains_key(&replacement_layer_id));
8652        assert!(compositor.packets.contains_key(&RetainedPacketId {
8653            container: CompositionContainerId::Layer(replacement_layer_id),
8654            segment_index: 0,
8655        }));
8656    }
8657
8658    #[test]
8659    fn overlay_layers_paint_above_later_normal_siblings() {
8660        let normal_id = WidgetId::new(205);
8661        let overlay_id = WidgetId::new(206);
8662
8663        let build_frame = || {
8664            let normal_descriptor = SceneLayerDescriptor::new(
8665                SceneLayerId::from_widget(normal_id),
8666                normal_id,
8667                Rect::new(32.0, 12.0, 72.0, 48.0),
8668            )
8669            .with_content_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8670            .with_paint_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8671            .with_cache_policy(LayerCachePolicy::Direct);
8672            let overlay_descriptor = SceneLayerDescriptor::new(
8673                SceneLayerId::from_widget(overlay_id),
8674                overlay_id,
8675                Rect::new(12.0, 12.0, 72.0, 48.0),
8676            )
8677            .with_content_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8678            .with_paint_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8679            .with_cache_policy(LayerCachePolicy::Direct)
8680            .with_composition_mode(LayerCompositionMode::Overlay);
8681
8682            let mut overlay_scene = Scene::new();
8683            overlay_scene.push(SceneCommand::FillRect {
8684                rect: overlay_descriptor.bounds,
8685                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
8686            });
8687
8688            let mut normal_scene = Scene::new();
8689            normal_scene.push(SceneCommand::FillRect {
8690                rect: normal_descriptor.bounds,
8691                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
8692            });
8693
8694            let mut scene = Scene::new();
8695            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8696                overlay_descriptor.clone(),
8697                overlay_scene,
8698            )));
8699            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8700                normal_descriptor.clone(),
8701                normal_scene,
8702            )));
8703
8704            SceneFrame {
8705                window_id: WindowId::new(143),
8706                viewport: Size::new(128.0, 80.0),
8707                surface_size: Size::new(128.0, 80.0),
8708                scale_factor: 1.0,
8709                dirty_regions: Vec::new(),
8710                layer_updates: vec![
8711                    SceneLayerUpdate::from_descriptor(
8712                        SceneLayerUpdateKind::Content,
8713                        overlay_descriptor,
8714                    )
8715                    .with_damage(Rect::new(12.0, 12.0, 72.0, 48.0)),
8716                    SceneLayerUpdate::from_descriptor(
8717                        SceneLayerUpdateKind::Content,
8718                        normal_descriptor,
8719                    )
8720                    .with_damage(Rect::new(32.0, 12.0, 72.0, 48.0)),
8721                ],
8722                scene,
8723                font_registry: Arc::new(FontRegistry::new()),
8724                image_registry: Arc::new(ImageRegistry::new()),
8725                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8726            }
8727        };
8728
8729        let mut renderer = WgpuRenderer::default();
8730        let frame = build_frame();
8731        renderer.render(&frame).unwrap();
8732        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
8733        let overlap = rgba_pixel(&pixels, 48, 24);
8734
8735        assert!(
8736            overlap[0] > overlap[1],
8737            "expected overlay pixel to dominate overlap, got rgba={overlap:?}"
8738        );
8739    }
8740
8741    #[test]
8742    fn nested_overlay_layers_paint_above_later_root_normal_siblings() {
8743        let shell_id = WidgetId::new(207);
8744        let nested_overlay_id = WidgetId::new(208);
8745        let blocker_id = WidgetId::new(209);
8746
8747        let build_frame = || {
8748            let shell_descriptor = SceneLayerDescriptor::new(
8749                SceneLayerId::from_widget(shell_id),
8750                shell_id,
8751                Rect::new(0.0, 0.0, 128.0, 80.0),
8752            )
8753            .with_content_bounds(Rect::new(0.0, 0.0, 128.0, 80.0))
8754            .with_paint_bounds(Rect::new(0.0, 0.0, 128.0, 80.0))
8755            .with_cache_policy(LayerCachePolicy::Direct);
8756            let nested_overlay_descriptor = SceneLayerDescriptor::new(
8757                SceneLayerId::from_widget(nested_overlay_id),
8758                nested_overlay_id,
8759                Rect::new(12.0, 12.0, 72.0, 48.0),
8760            )
8761            .with_content_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8762            .with_paint_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8763            .with_cache_policy(LayerCachePolicy::Direct)
8764            .with_composition_mode(LayerCompositionMode::Overlay);
8765            let blocker_descriptor = SceneLayerDescriptor::new(
8766                SceneLayerId::from_widget(blocker_id),
8767                blocker_id,
8768                Rect::new(32.0, 12.0, 72.0, 48.0),
8769            )
8770            .with_content_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8771            .with_paint_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8772            .with_cache_policy(LayerCachePolicy::Direct);
8773
8774            let mut nested_overlay_scene = Scene::new();
8775            nested_overlay_scene.push(SceneCommand::FillRect {
8776                rect: nested_overlay_descriptor.bounds,
8777                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
8778            });
8779
8780            let mut shell_scene = Scene::new();
8781            shell_scene.push(SceneCommand::FillRect {
8782                rect: shell_descriptor.bounds,
8783                brush: Color::rgba(0.97, 0.98, 1.0, 1.0).into(),
8784            });
8785            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8786                nested_overlay_descriptor.clone(),
8787                nested_overlay_scene,
8788            )));
8789
8790            let mut blocker_scene = Scene::new();
8791            blocker_scene.push(SceneCommand::FillRect {
8792                rect: blocker_descriptor.bounds,
8793                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
8794            });
8795
8796            let mut scene = Scene::new();
8797            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8798                shell_descriptor.clone(),
8799                shell_scene,
8800            )));
8801            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8802                blocker_descriptor.clone(),
8803                blocker_scene,
8804            )));
8805
8806            SceneFrame {
8807                window_id: WindowId::new(144),
8808                viewport: Size::new(128.0, 80.0),
8809                surface_size: Size::new(128.0, 80.0),
8810                scale_factor: 1.0,
8811                dirty_regions: Vec::new(),
8812                layer_updates: vec![
8813                    SceneLayerUpdate::from_descriptor(
8814                        SceneLayerUpdateKind::Content,
8815                        shell_descriptor,
8816                    )
8817                    .with_damage(Rect::new(0.0, 0.0, 128.0, 80.0)),
8818                    SceneLayerUpdate::from_descriptor(
8819                        SceneLayerUpdateKind::Content,
8820                        nested_overlay_descriptor,
8821                    )
8822                    .with_damage(Rect::new(12.0, 12.0, 72.0, 48.0)),
8823                    SceneLayerUpdate::from_descriptor(
8824                        SceneLayerUpdateKind::Content,
8825                        blocker_descriptor,
8826                    )
8827                    .with_damage(Rect::new(32.0, 12.0, 72.0, 48.0)),
8828                ],
8829                scene,
8830                font_registry: Arc::new(FontRegistry::new()),
8831                image_registry: Arc::new(ImageRegistry::new()),
8832                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8833            }
8834        };
8835
8836        let mut renderer = WgpuRenderer::default();
8837        let frame = build_frame();
8838        renderer.render(&frame).unwrap();
8839        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
8840        let overlap = rgba_pixel(&pixels, 48, 24);
8841
8842        assert!(
8843            overlap[0] > overlap[1],
8844            "expected nested overlay pixel to dominate overlap, got rgba={overlap:?}"
8845        );
8846    }
8847
8848    #[test]
8849    fn cached_ancestor_overlay_layers_paint_above_later_root_normal_siblings() {
8850        let shell_id = WidgetId::new(210);
8851        let nested_overlay_id = WidgetId::new(211);
8852        let blocker_id = WidgetId::new(212);
8853
8854        let build_frame = || {
8855            let shell_descriptor = SceneLayerDescriptor::new(
8856                SceneLayerId::from_widget(shell_id),
8857                shell_id,
8858                Rect::new(0.0, 0.0, 512.0, 120.0),
8859            )
8860            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 120.0))
8861            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 120.0))
8862            .with_cache_policy(LayerCachePolicy::Cached);
8863            let nested_overlay_descriptor = SceneLayerDescriptor::new(
8864                SceneLayerId::from_widget(nested_overlay_id),
8865                nested_overlay_id,
8866                Rect::new(12.0, 12.0, 180.0, 80.0),
8867            )
8868            .with_content_bounds(Rect::new(12.0, 12.0, 180.0, 80.0))
8869            .with_paint_bounds(Rect::new(12.0, 12.0, 180.0, 80.0))
8870            .with_cache_policy(LayerCachePolicy::Direct)
8871            .with_composition_mode(LayerCompositionMode::Overlay);
8872            let blocker_descriptor = SceneLayerDescriptor::new(
8873                SceneLayerId::from_widget(blocker_id),
8874                blocker_id,
8875                Rect::new(96.0, 40.0, 220.0, 44.0),
8876            )
8877            .with_content_bounds(Rect::new(96.0, 40.0, 220.0, 44.0))
8878            .with_paint_bounds(Rect::new(96.0, 40.0, 220.0, 44.0))
8879            .with_cache_policy(LayerCachePolicy::Direct);
8880
8881            let mut nested_overlay_scene = Scene::new();
8882            nested_overlay_scene.push(SceneCommand::FillRect {
8883                rect: nested_overlay_descriptor.bounds,
8884                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
8885            });
8886
8887            let mut shell_scene = Scene::new();
8888            shell_scene.push(SceneCommand::FillRect {
8889                rect: shell_descriptor.bounds,
8890                brush: Color::rgba(0.97, 0.98, 1.0, 1.0).into(),
8891            });
8892            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8893                nested_overlay_descriptor.clone(),
8894                nested_overlay_scene,
8895            )));
8896
8897            let mut blocker_scene = Scene::new();
8898            blocker_scene.push(SceneCommand::FillRect {
8899                rect: blocker_descriptor.bounds,
8900                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
8901            });
8902
8903            let mut scene = Scene::new();
8904            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8905                shell_descriptor.clone(),
8906                shell_scene,
8907            )));
8908            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8909                blocker_descriptor.clone(),
8910                blocker_scene,
8911            )));
8912
8913            SceneFrame {
8914                window_id: WindowId::new(145),
8915                viewport: Size::new(512.0, 120.0),
8916                surface_size: Size::new(512.0, 120.0),
8917                scale_factor: 1.0,
8918                dirty_regions: Vec::new(),
8919                layer_updates: vec![
8920                    SceneLayerUpdate::from_descriptor(
8921                        SceneLayerUpdateKind::Content,
8922                        shell_descriptor,
8923                    )
8924                    .with_damage(Rect::new(0.0, 0.0, 512.0, 120.0)),
8925                    SceneLayerUpdate::from_descriptor(
8926                        SceneLayerUpdateKind::Content,
8927                        nested_overlay_descriptor,
8928                    )
8929                    .with_damage(Rect::new(12.0, 12.0, 180.0, 80.0)),
8930                    SceneLayerUpdate::from_descriptor(
8931                        SceneLayerUpdateKind::Content,
8932                        blocker_descriptor,
8933                    )
8934                    .with_damage(Rect::new(96.0, 40.0, 220.0, 44.0)),
8935                ],
8936                scene,
8937                font_registry: Arc::new(FontRegistry::new()),
8938                image_registry: Arc::new(ImageRegistry::new()),
8939                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8940            }
8941        };
8942
8943        let mut renderer = WgpuRenderer::default();
8944        let frame = build_frame();
8945        renderer.render(&frame).unwrap();
8946        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
8947        let overlap = rgba_pixel(&pixels, 120, 52);
8948
8949        assert!(
8950            overlap[0] > overlap[1],
8951            "expected cached-ancestor overlay pixel to dominate overlap, got rgba={overlap:?}"
8952        );
8953    }
8954
8955    #[test]
8956    fn retained_compositor_routes_descendant_damage_into_cached_parent_packets() {
8957        let parent_id = WidgetId::new(81);
8958        let child_id = WidgetId::new(82);
8959
8960        let parent_descriptor = SceneLayerDescriptor::new(
8961            SceneLayerId::from_widget(parent_id),
8962            parent_id,
8963            Rect::new(0.0, 0.0, 512.0, 128.0),
8964        )
8965        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8966        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8967        .with_cache_policy(LayerCachePolicy::Cached);
8968        let child_descriptor = SceneLayerDescriptor::new(
8969            SceneLayerId::from_widget(child_id),
8970            child_id,
8971            Rect::new(300.0, 24.0, 48.0, 48.0),
8972        );
8973
8974        let build_parent_scene = |child_brush: Color| {
8975            let mut child_scene = Scene::new();
8976            child_scene.push(SceneCommand::FillRect {
8977                rect: Rect::new(300.0, 24.0, 48.0, 48.0),
8978                brush: child_brush.into(),
8979            });
8980
8981            let mut parent_scene = Scene::new();
8982            parent_scene.push(SceneCommand::FillRect {
8983                rect: Rect::new(0.0, 0.0, 512.0, 128.0),
8984                brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
8985            });
8986            parent_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8987                child_descriptor.clone(),
8988                child_scene,
8989            )));
8990            parent_scene
8991        };
8992
8993        let mut scene = Scene::new();
8994        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8995            parent_descriptor.clone(),
8996            build_parent_scene(Color::rgba(1.0, 0.0, 0.0, 1.0)),
8997        )));
8998
8999        let mut frame = SceneFrame {
9000            window_id: WindowId::new(32),
9001            viewport: Size::new(512.0, 128.0),
9002            surface_size: Size::new(512.0, 128.0),
9003            scale_factor: 1.0,
9004            dirty_regions: Vec::new(),
9005            layer_updates: vec![
9006                SceneLayerUpdate::from_descriptor(
9007                    SceneLayerUpdateKind::Content,
9008                    parent_descriptor.clone(),
9009                )
9010                .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
9011                SceneLayerUpdate::from_descriptor(
9012                    SceneLayerUpdateKind::Content,
9013                    child_descriptor.clone(),
9014                )
9015                .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9016            ],
9017            scene,
9018            font_registry: Arc::new(FontRegistry::new()),
9019            image_registry: Arc::new(ImageRegistry::new()),
9020            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9021        };
9022
9023        let mut text_engine = TextEngine::new().unwrap();
9024        let mut compositor = RetainedCompositorState::default();
9025        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9026
9027        assert!(frame.scene.replace_layer(
9028            parent_id,
9029            SceneLayer::from_descriptor(
9030                parent_descriptor.clone(),
9031                build_parent_scene(Color::rgba(0.0, 1.0, 0.0, 1.0)),
9032            ),
9033        ));
9034        frame.layer_updates = vec![
9035            SceneLayerUpdate::from_descriptor(
9036                SceneLayerUpdateKind::Content,
9037                child_descriptor.clone(),
9038            )
9039            .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9040        ];
9041
9042        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9043    }
9044
9045    #[test]
9046    fn retained_compositor_routes_descendant_transform_into_cached_parent_packets() {
9047        let parent_id = WidgetId::new(181);
9048        let child_id = WidgetId::new(182);
9049
9050        let parent_descriptor = SceneLayerDescriptor::new(
9051            SceneLayerId::from_widget(parent_id),
9052            parent_id,
9053            Rect::new(0.0, 0.0, 512.0, 128.0),
9054        )
9055        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9056        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9057        .with_cache_policy(LayerCachePolicy::Cached);
9058
9059        let child_descriptor = |x: f32| {
9060            SceneLayerDescriptor::new(
9061                SceneLayerId::from_widget(child_id),
9062                child_id,
9063                Rect::new(x, 24.0, 48.0, 48.0),
9064            )
9065            .with_content_bounds(Rect::new(x, 24.0, 48.0, 48.0))
9066            .with_paint_bounds(Rect::new(x, 24.0, 48.0, 48.0))
9067            .with_cache_policy(LayerCachePolicy::Direct)
9068        };
9069
9070        let build_parent_scene = |child_x: f32| {
9071            let mut child_scene = Scene::new();
9072            child_scene.push(SceneCommand::FillRect {
9073                rect: Rect::new(child_x, 24.0, 48.0, 48.0),
9074                brush: Color::rgba(0.84, 0.32, 0.18, 1.0).into(),
9075            });
9076
9077            let mut parent_scene = Scene::new();
9078            parent_scene.push(SceneCommand::FillRect {
9079                rect: Rect::new(0.0, 0.0, 512.0, 128.0),
9080                brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
9081            });
9082            parent_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9083                child_descriptor(child_x),
9084                child_scene,
9085            )));
9086            parent_scene
9087        };
9088
9089        let mut scene = Scene::new();
9090        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9091            parent_descriptor.clone(),
9092            build_parent_scene(300.0),
9093        )));
9094
9095        let mut frame = SceneFrame {
9096            window_id: WindowId::new(132),
9097            viewport: Size::new(512.0, 128.0),
9098            surface_size: Size::new(512.0, 128.0),
9099            scale_factor: 1.0,
9100            dirty_regions: Vec::new(),
9101            layer_updates: vec![
9102                SceneLayerUpdate::from_descriptor(
9103                    SceneLayerUpdateKind::Content,
9104                    parent_descriptor.clone(),
9105                )
9106                .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
9107                SceneLayerUpdate::from_descriptor(
9108                    SceneLayerUpdateKind::Content,
9109                    child_descriptor(300.0),
9110                )
9111                .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9112            ],
9113            scene,
9114            font_registry: Arc::new(FontRegistry::new()),
9115            image_registry: Arc::new(ImageRegistry::new()),
9116            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9117        };
9118
9119        let mut text_engine = TextEngine::new().unwrap();
9120        let mut compositor = RetainedCompositorState::default();
9121        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9122
9123        assert!(frame.scene.replace_layer(
9124            parent_id,
9125            SceneLayer::from_descriptor(parent_descriptor.clone(), build_parent_scene(340.0)),
9126        ));
9127        frame.layer_updates = vec![
9128            SceneLayerUpdate::from_descriptor(
9129                SceneLayerUpdateKind::Transform,
9130                child_descriptor(340.0),
9131            )
9132            .with_damage(Rect::new(300.0, 24.0, 88.0, 48.0)),
9133        ];
9134
9135        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9136    }
9137
9138    #[test]
9139    fn retained_compositor_updates_nested_retained_scroll_layer_after_child_transform() {
9140        let shell_id = WidgetId::new(191);
9141        let scroll_id = WidgetId::new(192);
9142        let content_id = WidgetId::new(193);
9143        let first_id = WidgetId::new(194);
9144        let second_id = WidgetId::new(195);
9145        let third_id = WidgetId::new(196);
9146
9147        let shell_descriptor = SceneLayerDescriptor::new(
9148            SceneLayerId::from_widget(shell_id),
9149            shell_id,
9150            Rect::new(0.0, 0.0, 360.0, 220.0),
9151        )
9152        .with_content_bounds(Rect::new(0.0, 0.0, 360.0, 220.0))
9153        .with_paint_bounds(Rect::new(0.0, 0.0, 360.0, 220.0))
9154        .with_cache_policy(LayerCachePolicy::Direct);
9155
9156        let scroll_descriptor = SceneLayerDescriptor::new(
9157            SceneLayerId::from_widget(scroll_id),
9158            scroll_id,
9159            Rect::new(0.0, 0.0, 240.0, 220.0),
9160        )
9161        .with_content_bounds(Rect::new(0.0, 0.0, 240.0, 220.0))
9162        .with_paint_bounds(Rect::new(0.0, 0.0, 240.0, 220.0))
9163        .with_cache_policy(LayerCachePolicy::Cached)
9164        .with_composition_mode(LayerCompositionMode::Scroll);
9165
9166        let content_descriptor = |y: f32| {
9167            SceneLayerDescriptor::new(
9168                SceneLayerId::from_widget(content_id),
9169                content_id,
9170                Rect::new(0.0, y, 360.0, 360.0),
9171            )
9172            .with_content_bounds(Rect::new(0.0, y, 220.0, 360.0))
9173            .with_paint_bounds(Rect::new(0.0, y, 220.0, 360.0))
9174            .with_cache_policy(LayerCachePolicy::Direct)
9175        };
9176
9177        let child_layer = |id: WidgetId, y: f32, brush: Color| {
9178            let mut scene = Scene::new();
9179            scene.push(SceneCommand::FillRect {
9180                rect: Rect::new(0.0, y, 220.0, 120.0),
9181                brush: brush.into(),
9182            });
9183            SceneLayer::from_descriptor(
9184                SceneLayerDescriptor::new(
9185                    SceneLayerId::from_widget(id),
9186                    id,
9187                    Rect::new(0.0, y, 220.0, 120.0),
9188                )
9189                .with_content_bounds(Rect::new(0.0, y, 220.0, 120.0))
9190                .with_paint_bounds(Rect::new(0.0, y, 220.0, 120.0))
9191                .with_cache_policy(LayerCachePolicy::Direct),
9192                scene,
9193            )
9194        };
9195
9196        let build_content_scene = |y: f32| {
9197            let mut scene = Scene::new();
9198            scene.push(SceneCommand::Layer(child_layer(
9199                first_id,
9200                y,
9201                Color::rgba(0.82, 0.36, 0.18, 1.0),
9202            )));
9203            scene.push(SceneCommand::Layer(child_layer(
9204                second_id,
9205                y + 120.0,
9206                Color::rgba(0.18, 0.54, 0.82, 1.0),
9207            )));
9208            scene.push(SceneCommand::Layer(child_layer(
9209                third_id,
9210                y + 240.0,
9211                Color::rgba(0.24, 0.72, 0.36, 1.0),
9212            )));
9213            scene
9214        };
9215
9216        let build_shell_scene = |content_y: f32| {
9217            let mut scroll_scene = Scene::new();
9218            scroll_scene.push(SceneCommand::PushClip {
9219                rect: Rect::new(0.0, 0.0, 230.0, 220.0),
9220            });
9221            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9222                content_descriptor(content_y),
9223                build_content_scene(content_y),
9224            )));
9225            scroll_scene.push(SceneCommand::PopClip);
9226
9227            let mut shell_scene = Scene::new();
9228            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9229                scroll_descriptor.clone(),
9230                scroll_scene,
9231            )));
9232            shell_scene.push(SceneCommand::FillRect {
9233                rect: Rect::new(240.0, 0.0, 120.0, 220.0),
9234                brush: Color::rgba(0.94, 0.95, 0.97, 1.0).into(),
9235            });
9236            shell_scene
9237        };
9238
9239        let mut scene = Scene::new();
9240        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9241            shell_descriptor.clone(),
9242            build_shell_scene(0.0),
9243        )));
9244
9245        let mut frame = SceneFrame {
9246            window_id: WindowId::new(142),
9247            viewport: Size::new(360.0, 220.0),
9248            surface_size: Size::new(360.0, 220.0),
9249            scale_factor: 1.0,
9250            dirty_regions: Vec::new(),
9251            layer_updates: vec![
9252                SceneLayerUpdate::from_descriptor(
9253                    SceneLayerUpdateKind::Content,
9254                    scroll_descriptor.clone(),
9255                )
9256                .with_damage(scroll_descriptor.paint_bounds),
9257                SceneLayerUpdate::from_descriptor(
9258                    SceneLayerUpdateKind::Content,
9259                    content_descriptor(0.0),
9260                )
9261                .with_damage(Rect::new(0.0, 0.0, 220.0, 360.0)),
9262            ],
9263            scene,
9264            font_registry: Arc::new(FontRegistry::new()),
9265            image_registry: Arc::new(ImageRegistry::new()),
9266            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9267        };
9268
9269        let mut text_engine = TextEngine::new().unwrap();
9270        let mut compositor = RetainedCompositorState::default();
9271        let first_frame = frame.clone();
9272        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9273
9274        assert!(
9275            frame
9276                .scene
9277                .translate_layer(content_id, Vector::new(0.0, -72.0))
9278        );
9279        frame.layer_updates = vec![
9280            SceneLayerUpdate::from_descriptor(
9281                SceneLayerUpdateKind::Transform,
9282                content_descriptor(-72.0),
9283            )
9284            .with_damage(Rect::new(0.0, -72.0, 220.0, 432.0)),
9285            SceneLayerUpdate::from_descriptor(
9286                SceneLayerUpdateKind::Transform,
9287                scroll_descriptor.clone(),
9288            )
9289            .with_damage(Rect::new(0.0, 0.0, 220.0, 360.0)),
9290        ];
9291
9292        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9293
9294        assert_ne!(first.scene_vertices, second.scene_vertices);
9295        let mut renderer = WgpuRenderer::default();
9296        renderer.render(&first_frame).unwrap();
9297        let before = renderer
9298            .capture_last_frame_rgba(first_frame.window_id)
9299            .unwrap();
9300        renderer.render(&frame).unwrap();
9301        let after = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
9302
9303        assert!(
9304            rgba_image_diff_count(&before, &after) > 0,
9305            "translated retained layer did not change the captured image beyond {RGBA_CHANNEL_TOLERANCE} channel value"
9306        );
9307    }
9308
9309    #[test]
9310    fn retained_compositor_routes_nested_cached_descendant_damage_into_packet_owner() {
9311        let outer_id = WidgetId::new(83);
9312        let inner_id = WidgetId::new(84);
9313        let leaf_id = WidgetId::new(85);
9314
9315        let outer_descriptor = SceneLayerDescriptor::new(
9316            SceneLayerId::from_widget(outer_id),
9317            outer_id,
9318            Rect::new(0.0, 0.0, 512.0, 128.0),
9319        )
9320        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9321        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9322        .with_cache_policy(LayerCachePolicy::Cached);
9323        let inner_descriptor = SceneLayerDescriptor::new(
9324            SceneLayerId::from_widget(inner_id),
9325            inner_id,
9326            Rect::new(256.0, 0.0, 256.0, 128.0),
9327        )
9328        .with_content_bounds(Rect::new(256.0, 0.0, 256.0, 128.0))
9329        .with_paint_bounds(Rect::new(256.0, 0.0, 256.0, 128.0))
9330        .with_cache_policy(LayerCachePolicy::Cached);
9331        let leaf_descriptor = SceneLayerDescriptor::new(
9332            SceneLayerId::from_widget(leaf_id),
9333            leaf_id,
9334            Rect::new(300.0, 24.0, 48.0, 48.0),
9335        )
9336        .with_content_bounds(Rect::new(300.0, 24.0, 48.0, 48.0))
9337        .with_paint_bounds(Rect::new(300.0, 24.0, 48.0, 48.0));
9338
9339        let build_scene = |leaf_brush: Color| {
9340            let mut leaf_scene = Scene::new();
9341            leaf_scene.push(SceneCommand::FillRect {
9342                rect: leaf_descriptor.bounds,
9343                brush: leaf_brush.into(),
9344            });
9345
9346            let mut inner_scene = Scene::new();
9347            inner_scene.push(SceneCommand::FillRect {
9348                rect: inner_descriptor.bounds,
9349                brush: Color::rgba(0.12, 0.12, 0.16, 1.0).into(),
9350            });
9351            inner_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9352                leaf_descriptor.clone(),
9353                leaf_scene,
9354            )));
9355
9356            let mut outer_scene = Scene::new();
9357            outer_scene.push(SceneCommand::FillRect {
9358                rect: outer_descriptor.bounds,
9359                brush: Color::rgba(0.08, 0.08, 0.10, 1.0).into(),
9360            });
9361            outer_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9362                inner_descriptor.clone(),
9363                inner_scene,
9364            )));
9365
9366            let mut scene = Scene::new();
9367            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9368                outer_descriptor.clone(),
9369                outer_scene,
9370            )));
9371            scene
9372        };
9373
9374        let mut frame = SceneFrame {
9375            window_id: WindowId::new(36),
9376            viewport: Size::new(512.0, 128.0),
9377            surface_size: Size::new(512.0, 128.0),
9378            scale_factor: 1.0,
9379            dirty_regions: Vec::new(),
9380            layer_updates: vec![
9381                SceneLayerUpdate::from_descriptor(
9382                    SceneLayerUpdateKind::Content,
9383                    outer_descriptor.clone(),
9384                )
9385                .with_damage(outer_descriptor.paint_bounds),
9386                SceneLayerUpdate::from_descriptor(
9387                    SceneLayerUpdateKind::Content,
9388                    inner_descriptor.clone(),
9389                )
9390                .with_damage(inner_descriptor.paint_bounds),
9391                SceneLayerUpdate::from_descriptor(
9392                    SceneLayerUpdateKind::Content,
9393                    leaf_descriptor.clone(),
9394                )
9395                .with_damage(leaf_descriptor.paint_bounds),
9396            ],
9397            scene: build_scene(Color::rgba(1.0, 0.0, 0.0, 1.0)),
9398            font_registry: Arc::new(FontRegistry::new()),
9399            image_registry: Arc::new(ImageRegistry::new()),
9400            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9401        };
9402
9403        let mut text_engine = TextEngine::new().unwrap();
9404        let mut compositor = RetainedCompositorState::default();
9405        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9406
9407        frame.scene = build_scene(Color::rgba(0.0, 1.0, 0.0, 1.0));
9408        frame.layer_updates = vec![
9409            SceneLayerUpdate::from_descriptor(
9410                SceneLayerUpdateKind::Content,
9411                leaf_descriptor.clone(),
9412            )
9413            .with_damage(leaf_descriptor.paint_bounds),
9414        ];
9415
9416        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9417
9418        assert_ne!(first.scene_vertices, second.scene_vertices);
9419    }
9420
9421    #[test]
9422    fn retained_packets_match_direct_text_across_packet_boundaries() {
9423        let handle = FontHandle::new(27);
9424        let mut fonts = FontRegistry::new();
9425        fonts.insert(handle, load_test_font());
9426
9427        let layer_id = WidgetId::new(92);
9428        let build_frame = |cache_policy| {
9429            let descriptor = SceneLayerDescriptor::new(
9430                SceneLayerId::from_widget(layer_id),
9431                layer_id,
9432                Rect::new(0.0, 0.0, 512.0, 72.0),
9433            )
9434            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 72.0))
9435            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 72.0))
9436            .with_cache_policy(cache_policy);
9437
9438            let mut layer_scene = Scene::new();
9439            layer_scene.push(SceneCommand::FillRect {
9440                rect: Rect::new(0.0, 0.0, 512.0, 72.0),
9441                brush: Color::rgba(0.08, 0.09, 0.11, 1.0).into(),
9442            });
9443            layer_scene.push(SceneCommand::DrawText(TextRun {
9444                rect: Rect::new(332.0, 18.0, 156.0, 28.0),
9445                text: "boundary glyph sample".to_string(),
9446                style: TextStyle {
9447                    font: Some(handle),
9448                    ..TextStyle::new(Color::WHITE)
9449                },
9450            }));
9451
9452            let mut scene = Scene::new();
9453            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9454                descriptor.clone(),
9455                layer_scene,
9456            )));
9457
9458            SceneFrame {
9459                window_id: WindowId::new(92),
9460                viewport: Size::new(512.0, 72.0),
9461                surface_size: Size::new(512.0, 72.0),
9462                scale_factor: 1.0,
9463                dirty_regions: Vec::new(),
9464                layer_updates: vec![
9465                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9466                        .with_damage(Rect::new(0.0, 0.0, 512.0, 72.0)),
9467                ],
9468                scene,
9469                font_registry: Arc::new(fonts.clone()),
9470                image_registry: Arc::new(ImageRegistry::new()),
9471                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9472            }
9473        };
9474
9475        let mut renderer = WgpuRenderer::default();
9476        let direct = build_frame(LayerCachePolicy::Direct);
9477        renderer.render(&direct).unwrap();
9478        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9479
9480        let cached = build_frame(LayerCachePolicy::Cached);
9481        renderer.render(&cached).unwrap();
9482        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9483
9484        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9485    }
9486
9487    #[test]
9488    fn retained_layer_local_text_snaps_after_fractional_origin_composition() {
9489        let handle = FontHandle::new(127);
9490        let mut fonts = FontRegistry::new();
9491        fonts.insert(handle, load_test_font());
9492        let viewport = Size::new(240.0, 92.0);
9493        let layer_id = WidgetId::new(127);
9494        let layer_bounds = Rect::new(58.333_332, 18.333_334, 158.0, 54.0);
9495        let text_rect = Rect::new(
9496            layer_bounds.x() + 14.0,
9497            layer_bounds.y() + 14.0,
9498            132.0,
9499            24.0,
9500        );
9501        let text_style = TextStyle {
9502            font: Some(handle),
9503            font_size: 14.0,
9504            line_height: 19.0,
9505            color: Color::rgba(0.92, 0.94, 0.98, 1.0),
9506            ..TextStyle::default()
9507        };
9508        let text = "Popup text snaps".to_string();
9509
9510        let descriptor =
9511            SceneLayerDescriptor::new(SceneLayerId::from_widget(layer_id), layer_id, layer_bounds)
9512                .with_content_bounds(layer_bounds)
9513                .with_paint_bounds(layer_bounds);
9514        let mut layer_scene = Scene::new();
9515        layer_scene.push(SceneCommand::FillRect {
9516            rect: layer_bounds,
9517            brush: Color::rgba(0.12, 0.15, 0.20, 1.0).into(),
9518        });
9519        layer_scene.push(SceneCommand::DrawText(TextRun {
9520            rect: text_rect,
9521            text,
9522            style: text_style,
9523        }));
9524        let mut retained_scene = Scene::new();
9525        retained_scene.push(SceneCommand::FillRect {
9526            rect: Rect::new(0.0, 0.0, viewport.width, viewport.height),
9527            brush: Color::rgba(0.06, 0.07, 0.09, 1.0).into(),
9528        });
9529        retained_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9530            descriptor.clone(),
9531            layer_scene,
9532        )));
9533
9534        let retained = SceneFrame {
9535            window_id: WindowId::new(128),
9536            viewport,
9537            surface_size: Size::new(360.0, 138.0),
9538            scale_factor: 1.5,
9539            dirty_regions: Vec::new(),
9540            layer_updates: vec![
9541                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9542                    .with_damage(layer_bounds),
9543            ],
9544            scene: retained_scene,
9545            font_registry: Arc::new(fonts),
9546            image_registry: Arc::new(ImageRegistry::new()),
9547            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9548        };
9549
9550        let mut text_engine = TextEngine::new().unwrap();
9551        let mut compositor = RetainedCompositorState::default();
9552        let draw_ops = prepare_with_compositor(&retained, &mut text_engine, &mut compositor)
9553            .expect("retained frame should prepare");
9554        let text_op = draw_ops
9555            .draw_ops
9556            .iter()
9557            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
9558            .expect("retained layer should emit atlas text");
9559        let start = text_op.vertices.start as usize;
9560        let end = start + text_op.vertices.len as usize;
9561        let instances = &draw_ops.text_instances[start..end];
9562        assert!(!instances.is_empty());
9563        for (index, instance) in instances.iter().enumerate() {
9564            let x = logical_x_from_ndc(instance.top_left[0], viewport);
9565            let y = logical_y_from_ndc(instance.top_left[1], viewport);
9566            assert!(
9567                is_physically_pixel_aligned(x, retained.scale_factor),
9568                "text instance {index} x was not aligned after layer composition: {x}"
9569            );
9570            assert!(
9571                is_physically_pixel_aligned(y, retained.scale_factor),
9572                "text instance {index} y was not aligned after layer composition: {y}"
9573            );
9574        }
9575    }
9576
9577    #[test]
9578    fn retained_ancestors_match_direct_for_child_layer_text_across_packet_boundaries() {
9579        let handle = FontHandle::new(28);
9580        let mut fonts = FontRegistry::new();
9581        fonts.insert(handle, load_test_font());
9582
9583        let shell_id = WidgetId::new(93);
9584        let child_id = WidgetId::new(94);
9585        let build_frame = |shell_cache_policy| {
9586            let shell_descriptor = SceneLayerDescriptor::new(
9587                SceneLayerId::from_widget(shell_id),
9588                shell_id,
9589                Rect::new(0.0, 0.0, 512.0, 84.0),
9590            )
9591            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9592            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9593            .with_cache_policy(shell_cache_policy);
9594
9595            let child_descriptor = SceneLayerDescriptor::new(
9596                SceneLayerId::from_widget(child_id),
9597                child_id,
9598                Rect::new(0.0, 0.0, 512.0, 84.0),
9599            )
9600            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9601            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9602            .with_cache_policy(LayerCachePolicy::Direct);
9603
9604            let mut child_scene = Scene::new();
9605            child_scene.push(SceneCommand::FillRect {
9606                rect: Rect::new(0.0, 0.0, 512.0, 84.0),
9607                brush: Color::rgba(0.08, 0.09, 0.11, 1.0).into(),
9608            });
9609            child_scene.push(SceneCommand::DrawText(TextRun {
9610                rect: Rect::new(326.0, 22.0, 164.0, 28.0),
9611                text: "tab boundary sample".to_string(),
9612                style: TextStyle {
9613                    font: Some(handle),
9614                    ..TextStyle::new(Color::WHITE)
9615                },
9616            }));
9617
9618            let mut shell_scene = Scene::new();
9619            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9620                child_descriptor.clone(),
9621                child_scene,
9622            )));
9623
9624            let mut scene = Scene::new();
9625            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9626                shell_descriptor.clone(),
9627                shell_scene,
9628            )));
9629
9630            SceneFrame {
9631                window_id: WindowId::new(93),
9632                viewport: Size::new(512.0, 84.0),
9633                surface_size: Size::new(512.0, 84.0),
9634                scale_factor: 1.0,
9635                dirty_regions: Vec::new(),
9636                layer_updates: vec![
9637                    SceneLayerUpdate::from_descriptor(
9638                        SceneLayerUpdateKind::Content,
9639                        shell_descriptor,
9640                    )
9641                    .with_damage(Rect::new(0.0, 0.0, 512.0, 84.0)),
9642                    SceneLayerUpdate::from_descriptor(
9643                        SceneLayerUpdateKind::Content,
9644                        child_descriptor,
9645                    )
9646                    .with_damage(Rect::new(0.0, 0.0, 512.0, 84.0)),
9647                ],
9648                scene,
9649                font_registry: Arc::new(fonts.clone()),
9650                image_registry: Arc::new(ImageRegistry::new()),
9651                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9652            }
9653        };
9654
9655        let mut renderer = WgpuRenderer::default();
9656        let direct = build_frame(LayerCachePolicy::Direct);
9657        renderer.render(&direct).unwrap();
9658        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9659
9660        let cached = build_frame(LayerCachePolicy::Cached);
9661        renderer.render(&cached).unwrap();
9662        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9663
9664        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9665    }
9666
9667    #[test]
9668    fn retained_packets_match_direct_for_theme_preview_style_cards() {
9669        let handle = FontHandle::new(151);
9670        let mut fonts = FontRegistry::new();
9671        fonts.insert(handle, load_test_font());
9672
9673        let widget_id = WidgetId::new(152);
9674        let build_frame = |window_id, cache_policy| {
9675            let descriptor = SceneLayerDescriptor::new(
9676                SceneLayerId::from_widget(widget_id),
9677                widget_id,
9678                Rect::new(0.0, 0.0, 640.0, 220.0),
9679            )
9680            .with_content_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
9681            .with_paint_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
9682            .with_cache_policy(cache_policy)
9683            .with_composition_mode(LayerCompositionMode::Scroll);
9684
9685            let mut layer_scene = Scene::new();
9686            layer_scene.push(SceneCommand::FillRect {
9687                rect: Rect::new(0.0, 0.0, 640.0, 220.0),
9688                brush: Color::rgba(0.94, 0.95, 0.98, 1.0).into(),
9689            });
9690
9691            let card_specs = [
9692                (
9693                    56.0,
9694                    Color::rgba(0.99, 0.99, 1.0, 1.0),
9695                    Color::rgba(0.19, 0.46, 0.91, 1.0),
9696                    Color::rgba(0.15, 0.73, 0.70, 1.0),
9697                    Color::rgba(0.10, 0.13, 0.19, 1.0),
9698                    Color::rgba(0.39, 0.45, 0.54, 1.0),
9699                    Color::rgba(0.82, 0.85, 0.91, 1.0),
9700                    "Light theme",
9701                ),
9702                (
9703                    344.0,
9704                    Color::rgba(0.14, 0.16, 0.21, 1.0),
9705                    Color::rgba(0.45, 0.60, 0.98, 1.0),
9706                    Color::rgba(0.96, 0.54, 0.31, 1.0),
9707                    Color::rgba(0.94, 0.95, 0.98, 1.0),
9708                    Color::rgba(0.68, 0.72, 0.80, 1.0),
9709                    Color::rgba(0.28, 0.31, 0.38, 1.0),
9710                    "Dark theme",
9711                ),
9712            ];
9713
9714            for (card_x, surface, accent, secondary, text_color, subtle_text, border, title) in
9715                card_specs
9716            {
9717                let card_rect = Rect::new(card_x, 24.0, 240.0, 172.0);
9718                layer_scene.push(SceneCommand::FillPath {
9719                    path: Path::rounded_rect(card_rect, 18.0),
9720                    brush: surface.into(),
9721                });
9722                layer_scene.push(SceneCommand::StrokePath {
9723                    path: Path::rounded_rect(card_rect, 18.0),
9724                    brush: border.into(),
9725                    stroke: StrokeStyle::new(1.0),
9726                });
9727                layer_scene.push(SceneCommand::DrawText(TextRun {
9728                    rect: Rect::new(card_x + 20.0, 44.0, 172.0, 24.0),
9729                    text: title.to_string(),
9730                    style: TextStyle {
9731                        font: Some(handle),
9732                        font_size: 18.0,
9733                        line_height: 22.0,
9734                        color: text_color,
9735                        ..Default::default()
9736                    },
9737                }));
9738                layer_scene.push(SceneCommand::DrawText(TextRun {
9739                    rect: Rect::new(card_x + 20.0, 76.0, 188.0, 20.0),
9740                    text: "Retained packets must match direct".to_string(),
9741                    style: TextStyle {
9742                        font: Some(handle),
9743                        font_size: 13.0,
9744                        line_height: 18.0,
9745                        color: subtle_text,
9746                        ..Default::default()
9747                    },
9748                }));
9749
9750                let swatch_colors = [Color::rgba(0.84, 0.87, 0.92, 1.0), accent, secondary];
9751                for (index, swatch_color) in swatch_colors.into_iter().enumerate() {
9752                    let swatch_rect =
9753                        Rect::new(card_x + 24.0 + (index as f32 * 72.0), 124.0, 60.0, 32.0);
9754                    layer_scene.push(SceneCommand::FillPath {
9755                        path: Path::rounded_rect(swatch_rect, 10.0),
9756                        brush: swatch_color.into(),
9757                    });
9758                    layer_scene.push(SceneCommand::StrokePath {
9759                        path: Path::rounded_rect(swatch_rect, 10.0),
9760                        brush: border.into(),
9761                        stroke: StrokeStyle::new(1.0),
9762                    });
9763                }
9764            }
9765
9766            let mut scene = Scene::new();
9767            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9768                descriptor.clone(),
9769                layer_scene,
9770            )));
9771
9772            SceneFrame {
9773                window_id,
9774                viewport: Size::new(640.0, 220.0),
9775                surface_size: Size::new(640.0, 220.0),
9776                scale_factor: 1.0,
9777                dirty_regions: Vec::new(),
9778                layer_updates: vec![
9779                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9780                        .with_damage(Rect::new(0.0, 0.0, 640.0, 220.0)),
9781                ],
9782                scene,
9783                font_registry: Arc::new(fonts.clone()),
9784                image_registry: Arc::new(ImageRegistry::new()),
9785                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9786            }
9787        };
9788
9789        let mut renderer = WgpuRenderer::default();
9790        let direct = build_frame(WindowId::new(152), LayerCachePolicy::Direct);
9791        renderer.render(&direct).unwrap();
9792        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9793
9794        let cached = build_frame(WindowId::new(153), LayerCachePolicy::Cached);
9795        renderer.render(&cached).unwrap();
9796        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9797
9798        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9799    }
9800
9801    #[test]
9802    fn retained_scroll_layer_matches_direct_at_fractional_packet_boundaries() {
9803        let widget_id = WidgetId::new(95);
9804        let build_frame = |window_id, cache_policy| {
9805            let descriptor = SceneLayerDescriptor::new(
9806                SceneLayerId::from_widget(widget_id),
9807                widget_id,
9808                Rect::new(0.0, -150.5, 420.0, 700.0),
9809            )
9810            .with_content_bounds(Rect::new(0.0, -150.5, 420.0, 700.0))
9811            .with_paint_bounds(Rect::new(0.0, -150.5, 420.0, 700.0))
9812            .with_cache_policy(cache_policy)
9813            .with_composition_mode(LayerCompositionMode::Scroll);
9814
9815            let mut layer_scene = Scene::new();
9816            layer_scene.push(SceneCommand::FillRect {
9817                rect: Rect::new(0.0, -150.5, 420.0, 700.0),
9818                brush: Color::WHITE.into(),
9819            });
9820            layer_scene.push(SceneCommand::FillRect {
9821                rect: Rect::new(32.0, 372.0, 340.0, 18.0),
9822                brush: Color::rgba(0.18, 0.24, 0.34, 1.0).into(),
9823            });
9824            layer_scene.push(SceneCommand::FillRect {
9825                rect: Rect::new(350.0, 356.0, 44.0, 58.0),
9826                brush: Color::rgba(0.12, 0.35, 0.78, 1.0).into(),
9827            });
9828            layer_scene.push(SceneCommand::FillRect {
9829                rect: Rect::new(334.0, 392.0, 64.0, 16.0),
9830                brush: Color::rgba(0.88, 0.52, 0.18, 1.0).into(),
9831            });
9832
9833            let mut scene = Scene::new();
9834            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9835                descriptor.clone(),
9836                layer_scene,
9837            )));
9838
9839            SceneFrame {
9840                window_id,
9841                viewport: Size::new(420.0, 240.0),
9842                surface_size: Size::new(420.0, 240.0),
9843                scale_factor: 1.0,
9844                dirty_regions: Vec::new(),
9845                layer_updates: vec![
9846                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9847                        .with_damage(Rect::new(0.0, -150.5, 420.0, 700.0)),
9848                ],
9849                scene,
9850                font_registry: Arc::new(FontRegistry::new()),
9851                image_registry: Arc::new(ImageRegistry::new()),
9852                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9853            }
9854        };
9855
9856        let mut renderer = WgpuRenderer::default();
9857        let direct = build_frame(WindowId::new(94), LayerCachePolicy::Direct);
9858        renderer.render(&direct).unwrap();
9859        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9860
9861        let cached = build_frame(WindowId::new(95), LayerCachePolicy::Cached);
9862        renderer.render(&cached).unwrap();
9863        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9864
9865        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9866    }
9867
9868    #[test]
9869    fn retained_scroll_layer_matches_direct_for_clipped_rows_across_packet_boundary() {
9870        let widget_id = WidgetId::new(96);
9871        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
9872        let build_frame = |window_id, cache_policy| {
9873            let descriptor = SceneLayerDescriptor::new(
9874                SceneLayerId::from_widget(widget_id),
9875                widget_id,
9876                Rect::new(24.0, -478.0, 1232.0, 2046.0),
9877            )
9878            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
9879            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
9880            .with_cache_policy(cache_policy)
9881            .with_composition_mode(LayerCompositionMode::Scroll);
9882
9883            let mut layer_scene = Scene::new();
9884            layer_scene.push(SceneCommand::FillRect {
9885                rect: Rect::new(24.0, -478.0, 1232.0, 2046.0),
9886                brush: Color::WHITE.into(),
9887            });
9888            layer_scene.push(SceneCommand::PushClip { rect: clip_rect });
9889            for (index, y) in [636.0, 668.0, 700.0, 732.0].into_iter().enumerate() {
9890                let brush = if index == 1 {
9891                    Color::rgba(0.79, 0.86, 0.98, 1.0)
9892                } else {
9893                    Color::rgba(0.90, 0.93, 0.97, 1.0)
9894                };
9895                layer_scene.push(SceneCommand::FillRect {
9896                    rect: Rect::new(42.0, y, 360.0, 28.0),
9897                    brush: brush.into(),
9898                });
9899                layer_scene.push(SceneCommand::FillRect {
9900                    rect: Rect::new(58.0, y + 8.0, 172.0, 12.0),
9901                    brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
9902                });
9903                layer_scene.push(SceneCommand::FillRect {
9904                    rect: Rect::new(248.0, y + 8.0, 96.0, 12.0),
9905                    brush: Color::rgba(0.41, 0.48, 0.58, 1.0).into(),
9906                });
9907            }
9908            layer_scene.push(SceneCommand::PopClip);
9909
9910            let mut scene = Scene::new();
9911            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9912                descriptor.clone(),
9913                layer_scene,
9914            )));
9915
9916            SceneFrame {
9917                window_id,
9918                viewport: Size::new(430.0, 900.0),
9919                surface_size: Size::new(430.0, 900.0),
9920                scale_factor: 1.0,
9921                dirty_regions: Vec::new(),
9922                layer_updates: vec![
9923                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9924                        .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
9925                ],
9926                scene,
9927                font_registry: Arc::new(FontRegistry::new()),
9928                image_registry: Arc::new(ImageRegistry::new()),
9929                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9930            }
9931        };
9932
9933        let mut renderer = WgpuRenderer::default();
9934        let direct = build_frame(WindowId::new(96), LayerCachePolicy::Direct);
9935        renderer.render(&direct).unwrap();
9936        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9937
9938        let cached = build_frame(WindowId::new(97), LayerCachePolicy::Cached);
9939        renderer.render(&cached).unwrap();
9940        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9941
9942        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9943    }
9944
9945    #[test]
9946    fn retained_scroll_layer_clips_direct_packet_after_child_layer_boundary() {
9947        let scroll_id = WidgetId::new(209);
9948        let child_id = WidgetId::new(210);
9949        let scroll_bounds = Rect::new(0.0, 0.0, 200.0, 160.0);
9950        let internal_clip = Rect::new(20.0, 24.0, 120.0, 80.0);
9951        let scroll_descriptor = SceneLayerDescriptor::new(
9952            SceneLayerId::from_widget(scroll_id),
9953            scroll_id,
9954            scroll_bounds,
9955        )
9956        .with_content_bounds(scroll_bounds)
9957        .with_paint_bounds(scroll_bounds)
9958        .with_composition_mode(LayerCompositionMode::Scroll);
9959        let child_descriptor = SceneLayerDescriptor::new(
9960            SceneLayerId::from_widget(child_id),
9961            child_id,
9962            Rect::new(32.0, 36.0, 48.0, 36.0),
9963        )
9964        .with_content_bounds(Rect::new(32.0, 36.0, 48.0, 36.0))
9965        .with_paint_bounds(Rect::new(32.0, 36.0, 48.0, 36.0));
9966
9967        let mut child_scene = Scene::new();
9968        child_scene.push(SceneCommand::FillRect {
9969            rect: Rect::new(32.0, 36.0, 48.0, 36.0),
9970            brush: Color::rgba(0.0, 0.0, 1.0, 1.0).into(),
9971        });
9972
9973        let mut scroll_scene = Scene::new();
9974        scroll_scene.push(SceneCommand::FillRect {
9975            rect: scroll_bounds,
9976            brush: Color::WHITE.into(),
9977        });
9978        scroll_scene.push(SceneCommand::PushClip {
9979            rect: internal_clip,
9980        });
9981        scroll_scene.push(SceneCommand::FillRect {
9982            rect: Rect::new(28.0, 36.0, 52.0, 20.0),
9983            brush: Color::rgba(0.90, 0.94, 0.98, 1.0).into(),
9984        });
9985        scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9986            child_descriptor.clone(),
9987            child_scene,
9988        )));
9989        scroll_scene.push(SceneCommand::FillRect {
9990            rect: Rect::new(28.0, 12.0, 96.0, 40.0),
9991            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
9992        });
9993        scroll_scene.push(SceneCommand::PopClip);
9994
9995        let mut scene = Scene::new();
9996        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9997            scroll_descriptor.clone(),
9998            scroll_scene,
9999        )));
10000
10001        let frame = SceneFrame {
10002            window_id: WindowId::new(209),
10003            viewport: Size::new(200.0, 160.0),
10004            surface_size: Size::new(200.0, 160.0),
10005            scale_factor: 1.0,
10006            dirty_regions: Vec::new(),
10007            layer_updates: vec![
10008                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, scroll_descriptor)
10009                    .with_damage(scroll_bounds),
10010                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, child_descriptor),
10011            ],
10012            scene,
10013            font_registry: Arc::new(FontRegistry::new()),
10014            image_registry: Arc::new(ImageRegistry::new()),
10015            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10016        };
10017
10018        let mut renderer = WgpuRenderer::default();
10019        renderer.render(&frame).unwrap();
10020        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
10021
10022        assert_rgba_pixel_near(&pixels, 32, 18, [255, 255, 255, 255], 2);
10023        assert_rgba_pixel_near(&pixels, 32, 30, [255, 0, 0, 255], 2);
10024    }
10025
10026    #[test]
10027    fn cached_scroll_ancestor_matches_direct_for_clipped_child_layer_rows() {
10028        let shell_id = WidgetId::new(97);
10029        let child_id = WidgetId::new(98);
10030        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
10031        let build_frame = |window_id, shell_cache_policy| {
10032            let shell_descriptor = SceneLayerDescriptor::new(
10033                SceneLayerId::from_widget(shell_id),
10034                shell_id,
10035                Rect::new(24.0, -478.0, 1232.0, 2046.0),
10036            )
10037            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10038            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10039            .with_cache_policy(shell_cache_policy)
10040            .with_composition_mode(LayerCompositionMode::Scroll);
10041
10042            let child_descriptor = SceneLayerDescriptor::new(
10043                SceneLayerId::from_widget(child_id),
10044                child_id,
10045                Rect::new(41.5, 627.5, 361.0, 221.0),
10046            )
10047            .with_content_bounds(Rect::new(41.5, 627.5, 361.0, 221.0))
10048            .with_paint_bounds(Rect::new(41.5, 627.5, 361.0, 221.0))
10049            .with_cache_policy(LayerCachePolicy::Direct);
10050
10051            let mut child_scene = Scene::new();
10052            child_scene.push(SceneCommand::FillRect {
10053                rect: Rect::new(41.5, 627.5, 361.0, 221.0),
10054                brush: Color::WHITE.into(),
10055            });
10056            child_scene.push(SceneCommand::PushClip { rect: clip_rect });
10057            for (index, y) in [636.0, 668.0, 700.0, 732.0].into_iter().enumerate() {
10058                let brush = if index == 1 {
10059                    Color::rgba(0.79, 0.86, 0.98, 1.0)
10060                } else {
10061                    Color::rgba(0.90, 0.93, 0.97, 1.0)
10062                };
10063                child_scene.push(SceneCommand::FillRect {
10064                    rect: Rect::new(42.0, y, 360.0, 28.0),
10065                    brush: brush.into(),
10066                });
10067                child_scene.push(SceneCommand::FillRect {
10068                    rect: Rect::new(58.0, y + 8.0, 172.0, 12.0),
10069                    brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
10070                });
10071                child_scene.push(SceneCommand::FillRect {
10072                    rect: Rect::new(248.0, y + 8.0, 96.0, 12.0),
10073                    brush: Color::rgba(0.41, 0.48, 0.58, 1.0).into(),
10074                });
10075            }
10076            child_scene.push(SceneCommand::PopClip);
10077
10078            let mut shell_scene = Scene::new();
10079            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10080                child_descriptor.clone(),
10081                child_scene,
10082            )));
10083
10084            let mut scene = Scene::new();
10085            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10086                shell_descriptor.clone(),
10087                shell_scene,
10088            )));
10089
10090            SceneFrame {
10091                window_id,
10092                viewport: Size::new(430.0, 900.0),
10093                surface_size: Size::new(430.0, 900.0),
10094                scale_factor: 1.0,
10095                dirty_regions: Vec::new(),
10096                layer_updates: vec![
10097                    SceneLayerUpdate::from_descriptor(
10098                        SceneLayerUpdateKind::Content,
10099                        shell_descriptor,
10100                    )
10101                    .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
10102                    SceneLayerUpdate::from_descriptor(
10103                        SceneLayerUpdateKind::Content,
10104                        child_descriptor,
10105                    )
10106                    .with_damage(Rect::new(41.5, 627.5, 361.0, 221.0)),
10107                ],
10108                scene,
10109                font_registry: Arc::new(FontRegistry::new()),
10110                image_registry: Arc::new(ImageRegistry::new()),
10111                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10112            }
10113        };
10114
10115        let mut renderer = WgpuRenderer::default();
10116        let direct = build_frame(WindowId::new(98), LayerCachePolicy::Direct);
10117        renderer.render(&direct).unwrap();
10118        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10119
10120        let cached = build_frame(WindowId::new(99), LayerCachePolicy::Cached);
10121        renderer.render(&cached).unwrap();
10122        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10123
10124        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10125    }
10126
10127    #[test]
10128    fn cached_scroll_ancestor_clips_fully_outside_child_layer() {
10129        let shell_id = WidgetId::new(100);
10130        let child_id = WidgetId::new(101);
10131        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
10132        let build_frame = |window_id, shell_cache_policy| {
10133            let shell_descriptor = SceneLayerDescriptor::new(
10134                SceneLayerId::from_widget(shell_id),
10135                shell_id,
10136                Rect::new(24.0, -478.0, 1232.0, 2046.0),
10137            )
10138            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10139            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10140            .with_cache_policy(shell_cache_policy)
10141            .with_composition_mode(LayerCompositionMode::Scroll);
10142
10143            let child_descriptor = SceneLayerDescriptor::new(
10144                SceneLayerId::from_widget(child_id),
10145                child_id,
10146                Rect::new(96.0, 904.0, 180.0, 96.0),
10147            )
10148            .with_content_bounds(Rect::new(96.0, 904.0, 180.0, 96.0))
10149            .with_paint_bounds(Rect::new(96.0, 904.0, 180.0, 96.0))
10150            .with_cache_policy(LayerCachePolicy::Direct);
10151
10152            let mut child_scene = Scene::new();
10153            child_scene.push(SceneCommand::FillRect {
10154                rect: Rect::new(96.0, 904.0, 180.0, 96.0),
10155                brush: Color::rgba(0.82, 0.16, 0.18, 1.0).into(),
10156            });
10157
10158            let mut shell_scene = Scene::new();
10159            shell_scene.push(SceneCommand::FillRect {
10160                rect: Rect::new(24.0, -478.0, 1232.0, 2046.0),
10161                brush: Color::WHITE.into(),
10162            });
10163            shell_scene.push(SceneCommand::PushClip { rect: clip_rect });
10164            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10165                child_descriptor.clone(),
10166                child_scene,
10167            )));
10168            shell_scene.push(SceneCommand::PopClip);
10169
10170            let mut scene = Scene::new();
10171            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10172                shell_descriptor.clone(),
10173                shell_scene,
10174            )));
10175
10176            SceneFrame {
10177                window_id,
10178                viewport: Size::new(430.0, 900.0),
10179                surface_size: Size::new(430.0, 900.0),
10180                scale_factor: 1.0,
10181                dirty_regions: Vec::new(),
10182                layer_updates: vec![
10183                    SceneLayerUpdate::from_descriptor(
10184                        SceneLayerUpdateKind::Content,
10185                        shell_descriptor,
10186                    )
10187                    .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
10188                    SceneLayerUpdate::from_descriptor(
10189                        SceneLayerUpdateKind::Content,
10190                        child_descriptor,
10191                    )
10192                    .with_damage(Rect::new(96.0, 904.0, 180.0, 96.0)),
10193                ],
10194                scene,
10195                font_registry: Arc::new(FontRegistry::new()),
10196                image_registry: Arc::new(ImageRegistry::new()),
10197                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10198            }
10199        };
10200
10201        let mut renderer = WgpuRenderer::default();
10202        let direct = build_frame(WindowId::new(100), LayerCachePolicy::Direct);
10203        renderer.render(&direct).unwrap();
10204        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10205
10206        let cached = build_frame(WindowId::new(101), LayerCachePolicy::Cached);
10207        renderer.render(&cached).unwrap();
10208        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10209
10210        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10211    }
10212
10213    #[test]
10214    fn cached_scroll_ancestor_matches_direct_after_child_translation() {
10215        let shell_id = WidgetId::new(102);
10216        let scroll_id = WidgetId::new(103);
10217        let content_id = WidgetId::new(104);
10218        let first_id = WidgetId::new(105);
10219        let second_id = WidgetId::new(106);
10220        let third_id = WidgetId::new(107);
10221        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10222
10223        let content_descriptor = |y: f32| {
10224            SceneLayerDescriptor::new(
10225                SceneLayerId::from_widget(content_id),
10226                content_id,
10227                Rect::new(42.0, y, 360.0, 360.0),
10228            )
10229            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10230            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10231            .with_cache_policy(LayerCachePolicy::Direct)
10232        };
10233
10234        let child_layer = |id: WidgetId, y: f32, brush: Color| {
10235            let mut scene = Scene::new();
10236            scene.push(SceneCommand::FillRect {
10237                rect: Rect::new(42.0, y, 360.0, 96.0),
10238                brush: brush.into(),
10239            });
10240            SceneLayer::from_descriptor(
10241                SceneLayerDescriptor::new(
10242                    SceneLayerId::from_widget(id),
10243                    id,
10244                    Rect::new(42.0, y, 360.0, 96.0),
10245                )
10246                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10247                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10248                .with_cache_policy(LayerCachePolicy::Direct),
10249                scene,
10250            )
10251        };
10252
10253        let build_content_scene = |y: f32| {
10254            let mut scene = Scene::new();
10255            scene.push(SceneCommand::Layer(child_layer(
10256                first_id,
10257                y,
10258                Color::rgba(0.82, 0.36, 0.18, 1.0),
10259            )));
10260            scene.push(SceneCommand::Layer(child_layer(
10261                second_id,
10262                y + 120.0,
10263                Color::rgba(0.18, 0.54, 0.82, 1.0),
10264            )));
10265            scene.push(SceneCommand::Layer(child_layer(
10266                third_id,
10267                y + 240.0,
10268                Color::rgba(0.24, 0.72, 0.36, 1.0),
10269            )));
10270            scene
10271        };
10272
10273        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10274            let shell_descriptor = SceneLayerDescriptor::new(
10275                SceneLayerId::from_widget(shell_id),
10276                shell_id,
10277                Rect::new(0.0, 0.0, 430.0, 360.0),
10278            )
10279            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10280            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10281            .with_cache_policy(LayerCachePolicy::Direct);
10282
10283            let scroll_descriptor = SceneLayerDescriptor::new(
10284                SceneLayerId::from_widget(scroll_id),
10285                scroll_id,
10286                Rect::new(24.0, 24.0, 382.0, 292.0),
10287            )
10288            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10289            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10290            .with_cache_policy(scroll_cache_policy)
10291            .with_composition_mode(LayerCompositionMode::Scroll);
10292
10293            let mut scroll_scene = Scene::new();
10294            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10295                content_descriptor(content_y),
10296                build_content_scene(content_y),
10297            )));
10298
10299            let mut shell_scene = Scene::new();
10300            shell_scene.push(SceneCommand::FillRect {
10301                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10302                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10303            });
10304            shell_scene.push(SceneCommand::PushClip { rect: clip_rect });
10305            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10306                scroll_descriptor.clone(),
10307                scroll_scene,
10308            )));
10309            shell_scene.push(SceneCommand::PopClip);
10310
10311            let mut scene = Scene::new();
10312            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10313                shell_descriptor.clone(),
10314                shell_scene,
10315            )));
10316
10317            let update = if update_kind == SceneLayerUpdateKind::Content {
10318                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10319                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
10320            } else {
10321                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10322                    .with_damage(Rect::new(42.0, 0.0, 360.0, 432.0))
10323            };
10324
10325            SceneFrame {
10326                window_id,
10327                viewport: Size::new(430.0, 360.0),
10328                surface_size: Size::new(430.0, 360.0),
10329                scale_factor: 1.0,
10330                dirty_regions: Vec::new(),
10331                layer_updates: vec![update],
10332                scene,
10333                font_registry: Arc::new(FontRegistry::new()),
10334                image_registry: Arc::new(ImageRegistry::new()),
10335                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10336            }
10337        };
10338
10339        let mut renderer = WgpuRenderer::default();
10340
10341        let direct_initial = build_frame(
10342            WindowId::new(110),
10343            LayerCachePolicy::Direct,
10344            0.0,
10345            SceneLayerUpdateKind::Content,
10346        );
10347        renderer.render(&direct_initial).unwrap();
10348        let direct_updated = build_frame(
10349            WindowId::new(110),
10350            LayerCachePolicy::Direct,
10351            72.0,
10352            SceneLayerUpdateKind::Transform,
10353        );
10354        renderer.render(&direct_updated).unwrap();
10355        let direct_pixels = renderer
10356            .capture_last_frame_rgba(direct_updated.window_id)
10357            .unwrap();
10358
10359        let cached_initial = build_frame(
10360            WindowId::new(111),
10361            LayerCachePolicy::Cached,
10362            0.0,
10363            SceneLayerUpdateKind::Content,
10364        );
10365        renderer.render(&cached_initial).unwrap();
10366        let cached_updated = build_frame(
10367            WindowId::new(111),
10368            LayerCachePolicy::Cached,
10369            72.0,
10370            SceneLayerUpdateKind::Transform,
10371        );
10372        renderer.render(&cached_updated).unwrap();
10373        let cached_pixels = renderer
10374            .capture_last_frame_rgba(cached_updated.window_id)
10375            .unwrap();
10376
10377        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10378    }
10379
10380    #[test]
10381    fn cached_scroll_internal_clip_matches_direct_after_child_translation() {
10382        let shell_id = WidgetId::new(108);
10383        let scroll_id = WidgetId::new(109);
10384        let content_id = WidgetId::new(110);
10385        let first_id = WidgetId::new(111);
10386        let second_id = WidgetId::new(112);
10387        let third_id = WidgetId::new(113);
10388        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10389
10390        let content_descriptor = |y: f32| {
10391            SceneLayerDescriptor::new(
10392                SceneLayerId::from_widget(content_id),
10393                content_id,
10394                Rect::new(42.0, y, 360.0, 360.0),
10395            )
10396            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10397            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10398            .with_cache_policy(LayerCachePolicy::Direct)
10399        };
10400
10401        let child_layer = |id: WidgetId, y: f32, brush: Color| {
10402            let mut scene = Scene::new();
10403            scene.push(SceneCommand::FillRect {
10404                rect: Rect::new(42.0, y, 360.0, 96.0),
10405                brush: brush.into(),
10406            });
10407            SceneLayer::from_descriptor(
10408                SceneLayerDescriptor::new(
10409                    SceneLayerId::from_widget(id),
10410                    id,
10411                    Rect::new(42.0, y, 360.0, 96.0),
10412                )
10413                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10414                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10415                .with_cache_policy(LayerCachePolicy::Direct),
10416                scene,
10417            )
10418        };
10419
10420        let build_content_scene = |y: f32| {
10421            let mut scene = Scene::new();
10422            scene.push(SceneCommand::Layer(child_layer(
10423                first_id,
10424                y,
10425                Color::rgba(0.82, 0.36, 0.18, 1.0),
10426            )));
10427            scene.push(SceneCommand::Layer(child_layer(
10428                second_id,
10429                y + 120.0,
10430                Color::rgba(0.18, 0.54, 0.82, 1.0),
10431            )));
10432            scene.push(SceneCommand::Layer(child_layer(
10433                third_id,
10434                y + 240.0,
10435                Color::rgba(0.24, 0.72, 0.36, 1.0),
10436            )));
10437            scene
10438        };
10439
10440        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10441            let shell_descriptor = SceneLayerDescriptor::new(
10442                SceneLayerId::from_widget(shell_id),
10443                shell_id,
10444                Rect::new(0.0, 0.0, 430.0, 360.0),
10445            )
10446            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10447            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10448            .with_cache_policy(LayerCachePolicy::Direct);
10449
10450            let scroll_descriptor = SceneLayerDescriptor::new(
10451                SceneLayerId::from_widget(scroll_id),
10452                scroll_id,
10453                Rect::new(24.0, 24.0, 382.0, 292.0),
10454            )
10455            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10456            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10457            .with_cache_policy(scroll_cache_policy)
10458            .with_composition_mode(LayerCompositionMode::Scroll);
10459
10460            let mut scroll_scene = Scene::new();
10461            scroll_scene.push(SceneCommand::PushClip { rect: clip_rect });
10462            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10463                content_descriptor(content_y),
10464                build_content_scene(content_y),
10465            )));
10466            scroll_scene.push(SceneCommand::PopClip);
10467
10468            let mut shell_scene = Scene::new();
10469            shell_scene.push(SceneCommand::FillRect {
10470                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10471                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10472            });
10473            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10474                scroll_descriptor.clone(),
10475                scroll_scene,
10476            )));
10477
10478            let mut scene = Scene::new();
10479            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10480                shell_descriptor.clone(),
10481                shell_scene,
10482            )));
10483
10484            let update = if update_kind == SceneLayerUpdateKind::Content {
10485                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10486                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
10487            } else {
10488                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10489                    .with_damage(Rect::new(42.0, 0.0, 360.0, 432.0))
10490            };
10491
10492            SceneFrame {
10493                window_id,
10494                viewport: Size::new(430.0, 360.0),
10495                surface_size: Size::new(430.0, 360.0),
10496                scale_factor: 1.0,
10497                dirty_regions: Vec::new(),
10498                layer_updates: vec![update],
10499                scene,
10500                font_registry: Arc::new(FontRegistry::new()),
10501                image_registry: Arc::new(ImageRegistry::new()),
10502                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10503            }
10504        };
10505
10506        let mut renderer = WgpuRenderer::default();
10507
10508        let direct_initial = build_frame(
10509            WindowId::new(112),
10510            LayerCachePolicy::Direct,
10511            0.0,
10512            SceneLayerUpdateKind::Content,
10513        );
10514        renderer.render(&direct_initial).unwrap();
10515        let direct_updated = build_frame(
10516            WindowId::new(112),
10517            LayerCachePolicy::Direct,
10518            72.0,
10519            SceneLayerUpdateKind::Transform,
10520        );
10521        renderer.render(&direct_updated).unwrap();
10522        let direct_pixels = renderer
10523            .capture_last_frame_rgba(direct_updated.window_id)
10524            .unwrap();
10525
10526        let cached_initial = build_frame(
10527            WindowId::new(113),
10528            LayerCachePolicy::Cached,
10529            0.0,
10530            SceneLayerUpdateKind::Content,
10531        );
10532        renderer.render(&cached_initial).unwrap();
10533        let cached_updated = build_frame(
10534            WindowId::new(113),
10535            LayerCachePolicy::Cached,
10536            72.0,
10537            SceneLayerUpdateKind::Transform,
10538        );
10539        renderer.render(&cached_updated).unwrap();
10540        let cached_pixels = renderer
10541            .capture_last_frame_rgba(cached_updated.window_id)
10542            .unwrap();
10543
10544        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10545    }
10546
10547    #[test]
10548    fn cached_scroll_translucent_auto_child_matches_direct_after_translation() {
10549        let mut renderer = WgpuRenderer::default();
10550
10551        let direct_initial = build_translucent_scroll_child_frame(
10552            WindowId::new(214),
10553            LayerCachePolicy::Direct,
10554            LayerCachePolicy::Direct,
10555            60.0,
10556            SceneLayerUpdateKind::Content,
10557        );
10558        renderer.render(&direct_initial).unwrap();
10559        let direct_updated = build_translucent_scroll_child_frame(
10560            WindowId::new(214),
10561            LayerCachePolicy::Direct,
10562            LayerCachePolicy::Direct,
10563            132.0,
10564            SceneLayerUpdateKind::Transform,
10565        );
10566        renderer.render(&direct_updated).unwrap();
10567        let direct_pixels = renderer
10568            .capture_last_frame_rgba(direct_updated.window_id)
10569            .unwrap();
10570
10571        let cached_initial = build_translucent_scroll_child_frame(
10572            WindowId::new(215),
10573            LayerCachePolicy::Cached,
10574            LayerCachePolicy::Auto,
10575            60.0,
10576            SceneLayerUpdateKind::Content,
10577        );
10578        renderer.render(&cached_initial).unwrap();
10579        let cached_updated = build_translucent_scroll_child_frame(
10580            WindowId::new(215),
10581            LayerCachePolicy::Cached,
10582            LayerCachePolicy::Auto,
10583            132.0,
10584            SceneLayerUpdateKind::Transform,
10585        );
10586        renderer.render(&cached_updated).unwrap();
10587        let cached_pixels = renderer
10588            .capture_last_frame_rgba(cached_updated.window_id)
10589            .unwrap();
10590
10591        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10592    }
10593
10594    #[test]
10595    fn cached_scroll_translucent_direct_child_matches_direct_after_translation() {
10596        let mut renderer = WgpuRenderer::default();
10597
10598        let direct_initial = build_translucent_scroll_child_frame(
10599            WindowId::new(216),
10600            LayerCachePolicy::Direct,
10601            LayerCachePolicy::Direct,
10602            60.0,
10603            SceneLayerUpdateKind::Content,
10604        );
10605        renderer.render(&direct_initial).unwrap();
10606        let direct_updated = build_translucent_scroll_child_frame(
10607            WindowId::new(216),
10608            LayerCachePolicy::Direct,
10609            LayerCachePolicy::Direct,
10610            132.0,
10611            SceneLayerUpdateKind::Transform,
10612        );
10613        renderer.render(&direct_updated).unwrap();
10614        let direct_pixels = renderer
10615            .capture_last_frame_rgba(direct_updated.window_id)
10616            .unwrap();
10617
10618        let cached_initial = build_translucent_scroll_child_frame(
10619            WindowId::new(217),
10620            LayerCachePolicy::Cached,
10621            LayerCachePolicy::Direct,
10622            60.0,
10623            SceneLayerUpdateKind::Content,
10624        );
10625        renderer.render(&cached_initial).unwrap();
10626        let cached_updated = build_translucent_scroll_child_frame(
10627            WindowId::new(217),
10628            LayerCachePolicy::Cached,
10629            LayerCachePolicy::Direct,
10630            132.0,
10631            SceneLayerUpdateKind::Transform,
10632        );
10633        renderer.render(&cached_updated).unwrap();
10634        let cached_pixels = renderer
10635            .capture_last_frame_rgba(cached_updated.window_id)
10636            .unwrap();
10637
10638        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10639    }
10640
10641    #[test]
10642    fn cached_scroll_internal_clip_image_matches_direct_after_child_translation() {
10643        let shell_id = WidgetId::new(114);
10644        let scroll_id = WidgetId::new(115);
10645        let content_id = WidgetId::new(116);
10646        let image_layer_id = WidgetId::new(117);
10647        let filler_id = WidgetId::new(118);
10648        let image_handle = ImageHandle::new(41);
10649        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10650
10651        let mut images = ImageRegistry::new();
10652        images.insert(
10653            image_handle,
10654            RegisteredImage::from_rgba8(
10655                2,
10656                2,
10657                vec![
10658                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
10659                ],
10660            )
10661            .unwrap(),
10662        );
10663        let images = Arc::new(images);
10664
10665        let content_descriptor = |y: f32| {
10666            SceneLayerDescriptor::new(
10667                SceneLayerId::from_widget(content_id),
10668                content_id,
10669                Rect::new(42.0, y, 360.0, 360.0),
10670            )
10671            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10672            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10673            .with_cache_policy(LayerCachePolicy::Direct)
10674        };
10675
10676        let image_layer = |y: f32| {
10677            let mut scene = Scene::new();
10678            scene.push(SceneCommand::DrawImage {
10679                rect: Rect::new(42.0, y, 220.0, 220.0),
10680                source: ImageSource::new(image_handle),
10681            });
10682            SceneLayer::from_descriptor(
10683                SceneLayerDescriptor::new(
10684                    SceneLayerId::from_widget(image_layer_id),
10685                    image_layer_id,
10686                    Rect::new(42.0, y, 220.0, 220.0),
10687                )
10688                .with_content_bounds(Rect::new(42.0, y, 220.0, 220.0))
10689                .with_paint_bounds(Rect::new(42.0, y, 220.0, 220.0))
10690                .with_cache_policy(LayerCachePolicy::Direct),
10691                scene,
10692            )
10693        };
10694
10695        let filler_layer = |y: f32| {
10696            let mut scene = Scene::new();
10697            scene.push(SceneCommand::FillRect {
10698                rect: Rect::new(42.0, y, 360.0, 96.0),
10699                brush: Color::rgba(0.24, 0.72, 0.36, 1.0).into(),
10700            });
10701            SceneLayer::from_descriptor(
10702                SceneLayerDescriptor::new(
10703                    SceneLayerId::from_widget(filler_id),
10704                    filler_id,
10705                    Rect::new(42.0, y, 360.0, 96.0),
10706                )
10707                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10708                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10709                .with_cache_policy(LayerCachePolicy::Direct),
10710                scene,
10711            )
10712        };
10713
10714        let build_content_scene = |y: f32| {
10715            let mut scene = Scene::new();
10716            scene.push(SceneCommand::Layer(image_layer(y)));
10717            scene.push(SceneCommand::Layer(filler_layer(y + 240.0)));
10718            scene
10719        };
10720
10721        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10722            let shell_descriptor = SceneLayerDescriptor::new(
10723                SceneLayerId::from_widget(shell_id),
10724                shell_id,
10725                Rect::new(0.0, 0.0, 430.0, 360.0),
10726            )
10727            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10728            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10729            .with_cache_policy(LayerCachePolicy::Direct);
10730
10731            let scroll_descriptor = SceneLayerDescriptor::new(
10732                SceneLayerId::from_widget(scroll_id),
10733                scroll_id,
10734                Rect::new(24.0, 24.0, 382.0, 292.0),
10735            )
10736            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10737            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10738            .with_cache_policy(scroll_cache_policy)
10739            .with_composition_mode(LayerCompositionMode::Scroll);
10740
10741            let mut scroll_scene = Scene::new();
10742            scroll_scene.push(SceneCommand::PushClip { rect: clip_rect });
10743            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10744                content_descriptor(content_y),
10745                build_content_scene(content_y),
10746            )));
10747            scroll_scene.push(SceneCommand::PopClip);
10748
10749            let mut shell_scene = Scene::new();
10750            shell_scene.push(SceneCommand::FillRect {
10751                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10752                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10753            });
10754            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10755                scroll_descriptor.clone(),
10756                scroll_scene,
10757            )));
10758
10759            let mut scene = Scene::new();
10760            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10761                shell_descriptor.clone(),
10762                shell_scene,
10763            )));
10764
10765            let update = if update_kind == SceneLayerUpdateKind::Content {
10766                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10767                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
10768            } else {
10769                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10770                    .with_damage(Rect::new(42.0, 0.0, 360.0, 460.0))
10771            };
10772
10773            SceneFrame {
10774                window_id,
10775                viewport: Size::new(430.0, 360.0),
10776                surface_size: Size::new(430.0, 360.0),
10777                scale_factor: 1.0,
10778                dirty_regions: Vec::new(),
10779                layer_updates: vec![update],
10780                scene,
10781                font_registry: Arc::new(FontRegistry::new()),
10782                image_registry: Arc::clone(&images),
10783                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10784            }
10785        };
10786
10787        let mut renderer = WgpuRenderer::default();
10788
10789        let direct_initial = build_frame(
10790            WindowId::new(114),
10791            LayerCachePolicy::Direct,
10792            0.0,
10793            SceneLayerUpdateKind::Content,
10794        );
10795        renderer.render(&direct_initial).unwrap();
10796        let direct_updated = build_frame(
10797            WindowId::new(114),
10798            LayerCachePolicy::Direct,
10799            72.0,
10800            SceneLayerUpdateKind::Transform,
10801        );
10802        renderer.render(&direct_updated).unwrap();
10803        let direct_pixels = renderer
10804            .capture_last_frame_rgba(direct_updated.window_id)
10805            .unwrap();
10806
10807        let cached_initial = build_frame(
10808            WindowId::new(115),
10809            LayerCachePolicy::Cached,
10810            0.0,
10811            SceneLayerUpdateKind::Content,
10812        );
10813        renderer.render(&cached_initial).unwrap();
10814        let cached_updated = build_frame(
10815            WindowId::new(115),
10816            LayerCachePolicy::Cached,
10817            72.0,
10818            SceneLayerUpdateKind::Transform,
10819        );
10820        renderer.render(&cached_updated).unwrap();
10821        let cached_pixels = renderer
10822            .capture_last_frame_rgba(cached_updated.window_id)
10823            .unwrap();
10824
10825        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10826    }
10827
10828    #[test]
10829    fn nested_cached_scroll_image_outside_parent_bounds_matches_direct_render() {
10830        let shell_id = WidgetId::new(119);
10831        let outer_scroll_id = WidgetId::new(120);
10832        let inner_scroll_id = WidgetId::new(121);
10833        let image_layer_id = WidgetId::new(122);
10834        let image_handle = ImageHandle::new(42);
10835
10836        let mut images = ImageRegistry::new();
10837        images.insert(
10838            image_handle,
10839            RegisteredImage::from_rgba8(
10840                2,
10841                2,
10842                vec![
10843                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
10844                ],
10845            )
10846            .unwrap(),
10847        );
10848        let images = Arc::new(images);
10849
10850        let build_frame = |window_id, inner_cache_policy| {
10851            let shell_descriptor = SceneLayerDescriptor::new(
10852                SceneLayerId::from_widget(shell_id),
10853                shell_id,
10854                Rect::new(0.0, 0.0, 1280.0, 720.0),
10855            )
10856            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
10857            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
10858            .with_cache_policy(LayerCachePolicy::Direct);
10859
10860            let outer_scroll_descriptor = SceneLayerDescriptor::new(
10861                SceneLayerId::from_widget(outer_scroll_id),
10862                outer_scroll_id,
10863                Rect::new(320.0, 28.0, 428.0, 336.0),
10864            )
10865            .with_content_bounds(Rect::new(320.0, 28.0, 428.0, 336.0))
10866            .with_paint_bounds(Rect::new(320.0, 28.0, 428.0, 336.0))
10867            .with_cache_policy(LayerCachePolicy::Direct)
10868            .with_composition_mode(LayerCompositionMode::Scroll);
10869
10870            let inner_scroll_descriptor = SceneLayerDescriptor::new(
10871                SceneLayerId::from_widget(inner_scroll_id),
10872                inner_scroll_id,
10873                Rect::new(321.0, 60.0, 426.0, 303.0),
10874            )
10875            .with_content_bounds(Rect::new(321.0, 60.0, 426.0, 303.0))
10876            .with_paint_bounds(Rect::new(321.0, 60.0, 426.0, 303.0))
10877            .with_cache_policy(inner_cache_policy)
10878            .with_composition_mode(LayerCompositionMode::Scroll)
10879            .with_is_stack_surface(true);
10880
10881            let mut image_scene = Scene::new();
10882            image_scene.push(SceneCommand::DrawImage {
10883                rect: Rect::new(363.0, 376.0, 220.0, 220.0),
10884                source: ImageSource::new(image_handle),
10885            });
10886            let image_layer = SceneLayer::from_descriptor(
10887                SceneLayerDescriptor::new(
10888                    SceneLayerId::from_widget(image_layer_id),
10889                    image_layer_id,
10890                    Rect::new(363.0, 376.0, 220.0, 220.0),
10891                )
10892                .with_content_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
10893                .with_paint_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
10894                .with_cache_policy(LayerCachePolicy::Direct),
10895                image_scene,
10896            );
10897
10898            let mut inner_scroll_scene = Scene::new();
10899            inner_scroll_scene.push(SceneCommand::FillRect {
10900                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
10901                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
10902            });
10903            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
10904
10905            let mut outer_scroll_scene = Scene::new();
10906            outer_scroll_scene.push(SceneCommand::FillRect {
10907                rect: Rect::new(320.0, 28.0, 428.0, 336.0),
10908                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
10909            });
10910            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10911                inner_scroll_descriptor,
10912                inner_scroll_scene,
10913            )));
10914
10915            let mut scene = Scene::new();
10916            scene.push(SceneCommand::FillRect {
10917                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
10918                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
10919            });
10920            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10921                shell_descriptor,
10922                {
10923                    let mut shell_scene = Scene::new();
10924                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10925                        outer_scroll_descriptor,
10926                        outer_scroll_scene,
10927                    )));
10928                    shell_scene
10929                },
10930            )));
10931
10932            SceneFrame {
10933                window_id,
10934                viewport: Size::new(1280.0, 720.0),
10935                surface_size: Size::new(1280.0, 720.0),
10936                scale_factor: 1.0,
10937                dirty_regions: Vec::new(),
10938                layer_updates: vec![SceneLayerUpdate::from_descriptor(
10939                    SceneLayerUpdateKind::Content,
10940                    SceneLayerDescriptor::new(
10941                        SceneLayerId::from_widget(image_layer_id),
10942                        image_layer_id,
10943                        Rect::new(363.0, 376.0, 220.0, 220.0),
10944                    )
10945                    .with_content_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
10946                    .with_paint_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
10947                    .with_cache_policy(LayerCachePolicy::Direct),
10948                )],
10949                scene,
10950                font_registry: Arc::new(FontRegistry::new()),
10951                image_registry: Arc::clone(&images),
10952                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10953            }
10954        };
10955
10956        let mut renderer = WgpuRenderer::default();
10957
10958        let direct_frame = build_frame(WindowId::new(116), LayerCachePolicy::Direct);
10959        renderer.render(&direct_frame).unwrap();
10960        let direct_pixels = renderer
10961            .capture_last_frame_rgba(direct_frame.window_id)
10962            .unwrap();
10963
10964        let cached_frame = build_frame(WindowId::new(117), LayerCachePolicy::Cached);
10965        renderer.render(&cached_frame).unwrap();
10966        let cached_pixels = renderer
10967            .capture_last_frame_rgba(cached_frame.window_id)
10968            .unwrap();
10969
10970        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10971    }
10972
10973    #[test]
10974    fn nested_cached_scroll_large_paint_bounds_image_matches_direct_render() {
10975        let shell_id = WidgetId::new(123);
10976        let outer_scroll_id = WidgetId::new(124);
10977        let inner_scroll_id = WidgetId::new(125);
10978        let image_layer_id = WidgetId::new(126);
10979        let image_handle = ImageHandle::new(43);
10980
10981        let mut images = ImageRegistry::new();
10982        images.insert(
10983            image_handle,
10984            RegisteredImage::from_rgba8(
10985                2,
10986                2,
10987                vec![
10988                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
10989                ],
10990            )
10991            .unwrap(),
10992        );
10993        let images = Arc::new(images);
10994
10995        let build_frame = |window_id, inner_cache_policy| {
10996            let shell_descriptor = SceneLayerDescriptor::new(
10997                SceneLayerId::from_widget(shell_id),
10998                shell_id,
10999                Rect::new(0.0, 0.0, 1280.0, 720.0),
11000            )
11001            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11002            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11003            .with_cache_policy(LayerCachePolicy::Direct);
11004
11005            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11006                SceneLayerId::from_widget(outer_scroll_id),
11007                outer_scroll_id,
11008                Rect::new(320.0, 28.0, 428.0, 336.0),
11009            )
11010            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11011            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11012            .with_cache_policy(LayerCachePolicy::Direct)
11013            .with_composition_mode(LayerCompositionMode::Scroll);
11014
11015            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11016                SceneLayerId::from_widget(inner_scroll_id),
11017                inner_scroll_id,
11018                Rect::new(321.0, 60.0, 426.0, 303.0),
11019            )
11020            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11021            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11022            .with_cache_policy(inner_cache_policy)
11023            .with_composition_mode(LayerCompositionMode::Scroll)
11024            .with_is_stack_surface(true);
11025
11026            let mut image_scene = Scene::new();
11027            image_scene.push(SceneCommand::DrawImage {
11028                rect: Rect::new(363.0, 376.0, 220.0, 220.0),
11029                source: ImageSource::new(image_handle),
11030            });
11031            let image_layer = SceneLayer::from_descriptor(
11032                SceneLayerDescriptor::new(
11033                    SceneLayerId::from_widget(image_layer_id),
11034                    image_layer_id,
11035                    Rect::new(363.0, 376.0, 220.0, 220.0),
11036                )
11037                .with_content_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11038                .with_paint_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11039                .with_cache_policy(LayerCachePolicy::Direct),
11040                image_scene,
11041            );
11042
11043            let mut inner_scroll_scene = Scene::new();
11044            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
11045
11046            let mut outer_scroll_scene = Scene::new();
11047            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11048                inner_scroll_descriptor,
11049                inner_scroll_scene,
11050            )));
11051
11052            let mut scene = Scene::new();
11053            scene.push(SceneCommand::FillRect {
11054                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11055                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11056            });
11057            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11058                shell_descriptor,
11059                {
11060                    let mut shell_scene = Scene::new();
11061                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11062                        outer_scroll_descriptor,
11063                        outer_scroll_scene,
11064                    )));
11065                    shell_scene
11066                },
11067            )));
11068
11069            SceneFrame {
11070                window_id,
11071                viewport: Size::new(1280.0, 720.0),
11072                surface_size: Size::new(1280.0, 720.0),
11073                scale_factor: 1.0,
11074                dirty_regions: Vec::new(),
11075                layer_updates: vec![SceneLayerUpdate::from_descriptor(
11076                    SceneLayerUpdateKind::Content,
11077                    SceneLayerDescriptor::new(
11078                        SceneLayerId::from_widget(image_layer_id),
11079                        image_layer_id,
11080                        Rect::new(363.0, 376.0, 220.0, 220.0),
11081                    )
11082                    .with_content_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11083                    .with_paint_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11084                    .with_cache_policy(LayerCachePolicy::Direct),
11085                )],
11086                scene,
11087                font_registry: Arc::new(FontRegistry::new()),
11088                image_registry: Arc::clone(&images),
11089                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11090            }
11091        };
11092
11093        let mut renderer = WgpuRenderer::default();
11094
11095        let direct_frame = build_frame(WindowId::new(118), LayerCachePolicy::Direct);
11096        renderer.render(&direct_frame).unwrap();
11097        let direct_pixels = renderer
11098            .capture_last_frame_rgba(direct_frame.window_id)
11099            .unwrap();
11100
11101        let cached_frame = build_frame(WindowId::new(119), LayerCachePolicy::Cached);
11102        renderer.render(&cached_frame).unwrap();
11103        let cached_pixels = renderer
11104            .capture_last_frame_rgba(cached_frame.window_id)
11105            .unwrap();
11106
11107        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11108    }
11109
11110    #[test]
11111    fn nested_cached_scroll_internal_clip_matches_direct_after_image_scroll() {
11112        let shell_id = WidgetId::new(127);
11113        let outer_scroll_id = WidgetId::new(128);
11114        let inner_scroll_id = WidgetId::new(129);
11115        let image_layer_id = WidgetId::new(130);
11116        let image_handle = ImageHandle::new(44);
11117
11118        let mut images = ImageRegistry::new();
11119        images.insert(
11120            image_handle,
11121            RegisteredImage::from_rgba8(
11122                2,
11123                2,
11124                vec![
11125                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11126                ],
11127            )
11128            .unwrap(),
11129        );
11130        let images = Arc::new(images);
11131
11132        let build_frame = |window_id, inner_cache_policy, image_y, update_kind| {
11133            let shell_descriptor = SceneLayerDescriptor::new(
11134                SceneLayerId::from_widget(shell_id),
11135                shell_id,
11136                Rect::new(0.0, 0.0, 1280.0, 720.0),
11137            )
11138            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11139            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11140            .with_cache_policy(LayerCachePolicy::Direct);
11141
11142            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11143                SceneLayerId::from_widget(outer_scroll_id),
11144                outer_scroll_id,
11145                Rect::new(320.0, 28.0, 428.0, 336.0),
11146            )
11147            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11148            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11149            .with_cache_policy(LayerCachePolicy::Direct)
11150            .with_composition_mode(LayerCompositionMode::Scroll);
11151
11152            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11153                SceneLayerId::from_widget(inner_scroll_id),
11154                inner_scroll_id,
11155                Rect::new(321.0, 60.0, 426.0, 303.0),
11156            )
11157            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11158            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11159            .with_cache_policy(inner_cache_policy)
11160            .with_composition_mode(LayerCompositionMode::Scroll)
11161            .with_is_stack_surface(true);
11162
11163            let image_descriptor = SceneLayerDescriptor::new(
11164                SceneLayerId::from_widget(image_layer_id),
11165                image_layer_id,
11166                Rect::new(363.0, image_y, 220.0, 220.0),
11167            )
11168            .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11169            .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11170            .with_cache_policy(LayerCachePolicy::Direct);
11171
11172            let mut image_scene = Scene::new();
11173            image_scene.push(SceneCommand::FillPath {
11174                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11175                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11176            });
11177            image_scene.push(SceneCommand::PushClip {
11178                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11179            });
11180            image_scene.push(SceneCommand::DrawImage {
11181                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11182                source: ImageSource::new(image_handle),
11183            });
11184            image_scene.push(SceneCommand::PopClip);
11185            image_scene.push(SceneCommand::StrokePath {
11186                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11187                brush: Color::rgba(0.8335978, 0.8335974, 0.835042, 1.0).into(),
11188                stroke: StrokeStyle { width: 1.0 },
11189            });
11190            let image_layer = SceneLayer::from_descriptor(image_descriptor.clone(), image_scene);
11191
11192            let mut inner_scroll_scene = Scene::new();
11193            inner_scroll_scene.push(SceneCommand::PushClip {
11194                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11195            });
11196            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
11197            inner_scroll_scene.push(SceneCommand::PopClip);
11198
11199            let mut outer_scroll_scene = Scene::new();
11200            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11201                inner_scroll_descriptor,
11202                inner_scroll_scene,
11203            )));
11204
11205            let mut scene = Scene::new();
11206            scene.push(SceneCommand::FillRect {
11207                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11208                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11209            });
11210            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11211                shell_descriptor,
11212                {
11213                    let mut shell_scene = Scene::new();
11214                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11215                        outer_scroll_descriptor,
11216                        outer_scroll_scene,
11217                    )));
11218                    shell_scene
11219                },
11220            )));
11221
11222            let update = SceneLayerUpdate::from_descriptor(update_kind, image_descriptor.clone())
11223                .with_damage(Rect::new(362.5, 139.5, 221.0, 457.0));
11224
11225            SceneFrame {
11226                window_id,
11227                viewport: Size::new(1280.0, 720.0),
11228                surface_size: Size::new(1280.0, 720.0),
11229                scale_factor: 1.0,
11230                dirty_regions: Vec::new(),
11231                layer_updates: vec![update],
11232                scene,
11233                font_registry: Arc::new(FontRegistry::new()),
11234                image_registry: Arc::clone(&images),
11235                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11236            }
11237        };
11238
11239        let mut renderer = WgpuRenderer::default();
11240
11241        let direct_initial = build_frame(
11242            WindowId::new(120),
11243            LayerCachePolicy::Direct,
11244            140.0,
11245            SceneLayerUpdateKind::Content,
11246        );
11247        renderer.render(&direct_initial).unwrap();
11248        let direct_updated = build_frame(
11249            WindowId::new(120),
11250            LayerCachePolicy::Direct,
11251            376.0,
11252            SceneLayerUpdateKind::Transform,
11253        );
11254        renderer.render(&direct_updated).unwrap();
11255        let direct_pixels = renderer
11256            .capture_last_frame_rgba(direct_updated.window_id)
11257            .unwrap();
11258
11259        let cached_initial = build_frame(
11260            WindowId::new(121),
11261            LayerCachePolicy::Cached,
11262            140.0,
11263            SceneLayerUpdateKind::Content,
11264        );
11265        renderer.render(&cached_initial).unwrap();
11266        let cached_updated = build_frame(
11267            WindowId::new(121),
11268            LayerCachePolicy::Cached,
11269            376.0,
11270            SceneLayerUpdateKind::Transform,
11271        );
11272        renderer.render(&cached_updated).unwrap();
11273        let cached_pixels = renderer
11274            .capture_last_frame_rgba(cached_updated.window_id)
11275            .unwrap();
11276
11277        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11278    }
11279
11280    #[test]
11281    fn nested_cached_scroll_sibling_transforms_match_direct_after_image_scroll() {
11282        let shell_id = WidgetId::new(131);
11283        let outer_scroll_id = WidgetId::new(132);
11284        let inner_scroll_id = WidgetId::new(133);
11285        let top_section_id = WidgetId::new(134);
11286        let bottom_section_id = WidgetId::new(135);
11287        let image_layer_id = WidgetId::new(136);
11288        let image_handle = ImageHandle::new(45);
11289
11290        let mut images = ImageRegistry::new();
11291        images.insert(
11292            image_handle,
11293            RegisteredImage::from_rgba8(
11294                2,
11295                2,
11296                vec![
11297                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11298                ],
11299            )
11300            .unwrap(),
11301        );
11302        let images = Arc::new(images);
11303
11304        let build_frame = |window_id, inner_cache_policy, top_y, bottom_y, update_kind| {
11305            let shell_descriptor = SceneLayerDescriptor::new(
11306                SceneLayerId::from_widget(shell_id),
11307                shell_id,
11308                Rect::new(0.0, 0.0, 1280.0, 720.0),
11309            )
11310            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11311            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11312            .with_cache_policy(LayerCachePolicy::Direct);
11313
11314            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11315                SceneLayerId::from_widget(outer_scroll_id),
11316                outer_scroll_id,
11317                Rect::new(320.0, 28.0, 428.0, 336.0),
11318            )
11319            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11320            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11321            .with_cache_policy(LayerCachePolicy::Direct)
11322            .with_composition_mode(LayerCompositionMode::Scroll);
11323
11324            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11325                SceneLayerId::from_widget(inner_scroll_id),
11326                inner_scroll_id,
11327                Rect::new(321.0, 60.0, 426.0, 303.0),
11328            )
11329            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11330            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11331            .with_cache_policy(inner_cache_policy)
11332            .with_composition_mode(LayerCompositionMode::Scroll)
11333            .with_is_stack_surface(true);
11334
11335            let mut top_scene = Scene::new();
11336            top_scene.push(SceneCommand::FillRect {
11337                rect: Rect::new(345.0, top_y, 378.0, 379.0),
11338                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11339            });
11340            top_scene.push(SceneCommand::FillRect {
11341                rect: Rect::new(363.0, top_y + 81.0, 440.2, 240.0),
11342                brush: Color::rgba(0.97, 0.981, 0.992, 1.0).into(),
11343            });
11344            let top_layer = SceneLayer::from_descriptor(
11345                SceneLayerDescriptor::new(
11346                    SceneLayerId::from_widget(top_section_id),
11347                    top_section_id,
11348                    Rect::new(345.0, top_y, 378.0, 379.0),
11349                )
11350                .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11351                .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11352                .with_cache_policy(LayerCachePolicy::Direct),
11353                top_scene,
11354            );
11355
11356            let image_y = bottom_y + 133.0;
11357            let mut image_scene = Scene::new();
11358            image_scene.push(SceneCommand::FillPath {
11359                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11360                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11361            });
11362            image_scene.push(SceneCommand::PushClip {
11363                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11364            });
11365            image_scene.push(SceneCommand::DrawImage {
11366                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11367                source: ImageSource::new(image_handle),
11368            });
11369            image_scene.push(SceneCommand::PopClip);
11370            let image_layer = SceneLayer::from_descriptor(
11371                SceneLayerDescriptor::new(
11372                    SceneLayerId::from_widget(image_layer_id),
11373                    image_layer_id,
11374                    Rect::new(363.0, image_y, 220.0, 220.0),
11375                )
11376                .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11377                .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11378                .with_cache_policy(LayerCachePolicy::Direct),
11379                image_scene,
11380            );
11381
11382            let mut bottom_scene = Scene::new();
11383            bottom_scene.push(SceneCommand::FillRect {
11384                rect: Rect::new(345.0, bottom_y, 378.0, 371.0),
11385                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11386            });
11387            bottom_scene.push(SceneCommand::Layer(image_layer));
11388            let bottom_layer = SceneLayer::from_descriptor(
11389                SceneLayerDescriptor::new(
11390                    SceneLayerId::from_widget(bottom_section_id),
11391                    bottom_section_id,
11392                    Rect::new(345.0, bottom_y, 378.0, 371.0),
11393                )
11394                .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11395                .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11396                .with_cache_policy(LayerCachePolicy::Direct),
11397                bottom_scene,
11398            );
11399
11400            let mut inner_scroll_scene = Scene::new();
11401            inner_scroll_scene.push(SceneCommand::PushClip {
11402                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11403            });
11404            inner_scroll_scene.push(SceneCommand::Layer(top_layer));
11405            inner_scroll_scene.push(SceneCommand::Layer(bottom_layer));
11406            inner_scroll_scene.push(SceneCommand::PopClip);
11407
11408            let mut outer_scroll_scene = Scene::new();
11409            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11410                inner_scroll_descriptor,
11411                inner_scroll_scene,
11412            )));
11413
11414            let mut scene = Scene::new();
11415            scene.push(SceneCommand::FillRect {
11416                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11417                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11418            });
11419            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11420                shell_descriptor,
11421                {
11422                    let mut shell_scene = Scene::new();
11423                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11424                        outer_scroll_descriptor,
11425                        outer_scroll_scene,
11426                    )));
11427                    shell_scene
11428                },
11429            )));
11430
11431            SceneFrame {
11432                window_id,
11433                viewport: Size::new(1280.0, 720.0),
11434                surface_size: Size::new(1280.0, 720.0),
11435                scale_factor: 1.0,
11436                dirty_regions: Vec::new(),
11437                layer_updates: vec![
11438                    SceneLayerUpdate::from_descriptor(
11439                        update_kind,
11440                        SceneLayerDescriptor::new(
11441                            SceneLayerId::from_widget(top_section_id),
11442                            top_section_id,
11443                            Rect::new(345.0, top_y, 378.0, 379.0),
11444                        )
11445                        .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11446                        .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11447                        .with_cache_policy(LayerCachePolicy::Direct),
11448                    )
11449                    .with_damage(Rect::new(345.0, -178.0, 1172.2, 403.0)),
11450                    SceneLayerUpdate::from_descriptor(
11451                        update_kind,
11452                        SceneLayerDescriptor::new(
11453                            SceneLayerId::from_widget(bottom_section_id),
11454                            bottom_section_id,
11455                            Rect::new(345.0, bottom_y, 378.0, 371.0),
11456                        )
11457                        .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11458                        .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11459                        .with_cache_policy(LayerCachePolicy::Direct),
11460                    )
11461                    .with_damage(Rect::new(345.0, 219.0, 378.0, 395.0)),
11462                ],
11463                scene,
11464                font_registry: Arc::new(FontRegistry::new()),
11465                image_registry: Arc::clone(&images),
11466                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11467            }
11468        };
11469
11470        let mut renderer = WgpuRenderer::default();
11471
11472        let direct_initial = build_frame(
11473            WindowId::new(122),
11474            LayerCachePolicy::Direct,
11475            -178.0,
11476            219.0,
11477            SceneLayerUpdateKind::Content,
11478        );
11479        renderer.render(&direct_initial).unwrap();
11480        let direct_updated = build_frame(
11481            WindowId::new(122),
11482            LayerCachePolicy::Direct,
11483            -154.0,
11484            243.0,
11485            SceneLayerUpdateKind::Transform,
11486        );
11487        renderer.render(&direct_updated).unwrap();
11488        let direct_pixels = renderer
11489            .capture_last_frame_rgba(direct_updated.window_id)
11490            .unwrap();
11491
11492        let cached_initial = build_frame(
11493            WindowId::new(123),
11494            LayerCachePolicy::Cached,
11495            -178.0,
11496            219.0,
11497            SceneLayerUpdateKind::Content,
11498        );
11499        renderer.render(&cached_initial).unwrap();
11500        let cached_updated = build_frame(
11501            WindowId::new(123),
11502            LayerCachePolicy::Cached,
11503            -154.0,
11504            243.0,
11505            SceneLayerUpdateKind::Transform,
11506        );
11507        renderer.render(&cached_updated).unwrap();
11508        let cached_pixels = renderer
11509            .capture_last_frame_rgba(cached_updated.window_id)
11510            .unwrap();
11511
11512        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11513    }
11514
11515    #[test]
11516    fn nested_cached_scroll_auto_sibling_transforms_match_direct_after_image_scroll() {
11517        let shell_id = WidgetId::new(137);
11518        let outer_scroll_id = WidgetId::new(138);
11519        let inner_scroll_id = WidgetId::new(139);
11520        let top_section_id = WidgetId::new(140);
11521        let bottom_section_id = WidgetId::new(141);
11522        let image_layer_id = WidgetId::new(142);
11523        let image_handle = ImageHandle::new(46);
11524
11525        let mut images = ImageRegistry::new();
11526        images.insert(
11527            image_handle,
11528            RegisteredImage::from_rgba8(
11529                2,
11530                2,
11531                vec![
11532                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11533                ],
11534            )
11535            .unwrap(),
11536        );
11537        let images = Arc::new(images);
11538
11539        let build_frame = |window_id, inner_cache_policy, top_y, bottom_y, update_kind| {
11540            let shell_descriptor = SceneLayerDescriptor::new(
11541                SceneLayerId::from_widget(shell_id),
11542                shell_id,
11543                Rect::new(0.0, 0.0, 1280.0, 720.0),
11544            )
11545            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11546            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11547            .with_cache_policy(LayerCachePolicy::Direct);
11548
11549            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11550                SceneLayerId::from_widget(outer_scroll_id),
11551                outer_scroll_id,
11552                Rect::new(320.0, 28.0, 428.0, 336.0),
11553            )
11554            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11555            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11556            .with_cache_policy(LayerCachePolicy::Direct)
11557            .with_composition_mode(LayerCompositionMode::Scroll);
11558
11559            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11560                SceneLayerId::from_widget(inner_scroll_id),
11561                inner_scroll_id,
11562                Rect::new(321.0, 60.0, 426.0, 303.0),
11563            )
11564            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11565            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11566            .with_cache_policy(inner_cache_policy)
11567            .with_composition_mode(LayerCompositionMode::Scroll)
11568            .with_is_stack_surface(true);
11569
11570            let mut top_scene = Scene::new();
11571            top_scene.push(SceneCommand::FillRect {
11572                rect: Rect::new(345.0, top_y, 378.0, 379.0),
11573                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11574            });
11575            top_scene.push(SceneCommand::FillRect {
11576                rect: Rect::new(363.0, top_y + 81.0, 440.2, 240.0),
11577                brush: Color::rgba(0.97, 0.981, 0.992, 1.0).into(),
11578            });
11579            let top_layer = SceneLayer::from_descriptor(
11580                SceneLayerDescriptor::new(
11581                    SceneLayerId::from_widget(top_section_id),
11582                    top_section_id,
11583                    Rect::new(345.0, top_y, 378.0, 379.0),
11584                )
11585                .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11586                .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0)),
11587                top_scene,
11588            );
11589
11590            let image_y = bottom_y + 133.0;
11591            let mut image_scene = Scene::new();
11592            image_scene.push(SceneCommand::FillPath {
11593                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11594                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11595            });
11596            image_scene.push(SceneCommand::PushClip {
11597                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11598            });
11599            image_scene.push(SceneCommand::DrawImage {
11600                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11601                source: ImageSource::new(image_handle),
11602            });
11603            image_scene.push(SceneCommand::PopClip);
11604            let image_layer = SceneLayer::from_descriptor(
11605                SceneLayerDescriptor::new(
11606                    SceneLayerId::from_widget(image_layer_id),
11607                    image_layer_id,
11608                    Rect::new(363.0, image_y, 220.0, 220.0),
11609                )
11610                .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11611                .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0)),
11612                image_scene,
11613            );
11614
11615            let mut bottom_scene = Scene::new();
11616            bottom_scene.push(SceneCommand::FillRect {
11617                rect: Rect::new(345.0, bottom_y, 378.0, 371.0),
11618                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11619            });
11620            bottom_scene.push(SceneCommand::Layer(image_layer));
11621            let bottom_layer = SceneLayer::from_descriptor(
11622                SceneLayerDescriptor::new(
11623                    SceneLayerId::from_widget(bottom_section_id),
11624                    bottom_section_id,
11625                    Rect::new(345.0, bottom_y, 378.0, 371.0),
11626                )
11627                .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11628                .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0)),
11629                bottom_scene,
11630            );
11631
11632            let mut inner_scroll_scene = Scene::new();
11633            inner_scroll_scene.push(SceneCommand::PushClip {
11634                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11635            });
11636            inner_scroll_scene.push(SceneCommand::Layer(top_layer));
11637            inner_scroll_scene.push(SceneCommand::Layer(bottom_layer));
11638            inner_scroll_scene.push(SceneCommand::PopClip);
11639
11640            let mut outer_scroll_scene = Scene::new();
11641            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11642                inner_scroll_descriptor,
11643                inner_scroll_scene,
11644            )));
11645
11646            let mut scene = Scene::new();
11647            scene.push(SceneCommand::FillRect {
11648                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11649                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11650            });
11651            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11652                shell_descriptor,
11653                {
11654                    let mut shell_scene = Scene::new();
11655                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11656                        outer_scroll_descriptor,
11657                        outer_scroll_scene,
11658                    )));
11659                    shell_scene
11660                },
11661            )));
11662
11663            SceneFrame {
11664                window_id,
11665                viewport: Size::new(1280.0, 720.0),
11666                surface_size: Size::new(1280.0, 720.0),
11667                scale_factor: 1.0,
11668                dirty_regions: Vec::new(),
11669                layer_updates: vec![
11670                    SceneLayerUpdate::from_descriptor(
11671                        update_kind,
11672                        SceneLayerDescriptor::new(
11673                            SceneLayerId::from_widget(top_section_id),
11674                            top_section_id,
11675                            Rect::new(345.0, top_y, 378.0, 379.0),
11676                        )
11677                        .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11678                        .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0)),
11679                    )
11680                    .with_damage(Rect::new(345.0, -178.0, 1172.2, 403.0)),
11681                    SceneLayerUpdate::from_descriptor(
11682                        update_kind,
11683                        SceneLayerDescriptor::new(
11684                            SceneLayerId::from_widget(bottom_section_id),
11685                            bottom_section_id,
11686                            Rect::new(345.0, bottom_y, 378.0, 371.0),
11687                        )
11688                        .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11689                        .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0)),
11690                    )
11691                    .with_damage(Rect::new(345.0, 219.0, 378.0, 395.0)),
11692                ],
11693                scene,
11694                font_registry: Arc::new(FontRegistry::new()),
11695                image_registry: Arc::clone(&images),
11696                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11697            }
11698        };
11699
11700        let mut renderer = WgpuRenderer::default();
11701
11702        let direct_initial = build_frame(
11703            WindowId::new(124),
11704            LayerCachePolicy::Direct,
11705            -178.0,
11706            219.0,
11707            SceneLayerUpdateKind::Content,
11708        );
11709        renderer.render(&direct_initial).unwrap();
11710        let direct_updated = build_frame(
11711            WindowId::new(124),
11712            LayerCachePolicy::Direct,
11713            -154.0,
11714            243.0,
11715            SceneLayerUpdateKind::Transform,
11716        );
11717        renderer.render(&direct_updated).unwrap();
11718        let direct_pixels = renderer
11719            .capture_last_frame_rgba(direct_updated.window_id)
11720            .unwrap();
11721
11722        let cached_initial = build_frame(
11723            WindowId::new(125),
11724            LayerCachePolicy::Cached,
11725            -178.0,
11726            219.0,
11727            SceneLayerUpdateKind::Content,
11728        );
11729        renderer.render(&cached_initial).unwrap();
11730        let cached_updated = build_frame(
11731            WindowId::new(125),
11732            LayerCachePolicy::Cached,
11733            -154.0,
11734            243.0,
11735            SceneLayerUpdateKind::Transform,
11736        );
11737        renderer.render(&cached_updated).unwrap();
11738        let cached_pixels = renderer
11739            .capture_last_frame_rgba(cached_updated.window_id)
11740            .unwrap();
11741
11742        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11743    }
11744
11745    #[test]
11746    fn glyph_raster_bounds_expand_fractional_edges() {
11747        let mut builder = super::TinySkiaPathBuilder::new();
11748        builder.move_to(0.6, -0.2);
11749        builder.line_to(10.2, -0.2);
11750        builder.line_to(10.2, 4.4);
11751        builder.line_to(0.6, 4.4);
11752        builder.close();
11753        let path = builder.finish().expect("fractional rectangle path");
11754
11755        let bounds = super::glyph_raster_bounds(&path).expect("bounds for fractional rectangle");
11756
11757        assert!((bounds.logical_min_x - 0.6).abs() < 0.0001);
11758        assert!((bounds.logical_min_y + 0.2).abs() < 0.0001);
11759        assert!((bounds.logical_width - 9.6).abs() < 0.0001);
11760        assert!((bounds.logical_height - 4.6).abs() < 0.0001);
11761        assert_eq!(bounds.raster_min_x, 0.0);
11762        assert_eq!(bounds.raster_min_y, -1.0);
11763        assert_eq!(bounds.raster_width, 11);
11764        assert_eq!(bounds.raster_height, 6);
11765    }
11766
11767    #[test]
11768    fn atlas_text_keeps_terminal_glyphs_at_fractional_scale() {
11769        let handle = FontHandle::new(30);
11770        let mut fonts = FontRegistry::new();
11771        fonts.insert(handle, load_test_font());
11772
11773        let build_frame = |text: &str| SceneFrame {
11774            window_id: WindowId::new(96),
11775            viewport: Size::new(260.0, 52.0),
11776            surface_size: Size::new(390.0, 78.0),
11777            scale_factor: 1.5,
11778            dirty_regions: Vec::new(),
11779            layer_updates: Vec::new(),
11780            scene: {
11781                let mut scene = Scene::new();
11782                scene.push(SceneCommand::FillRect {
11783                    rect: Rect::new(0.0, 0.0, 260.0, 52.0),
11784                    brush: Color::WHITE.into(),
11785                });
11786                scene.push(SceneCommand::DrawText(TextRun {
11787                    rect: Rect::new(8.0, 10.0, 220.0, 24.0),
11788                    text: text.to_string(),
11789                    style: TextStyle {
11790                        font: Some(handle),
11791                        font_size: 14.0,
11792                        line_height: 18.0,
11793                        color: Color::rgba(0.12, 0.16, 0.22, 1.0),
11794                        ..TextStyle::default()
11795                    },
11796                }));
11797                scene
11798            },
11799            font_registry: Arc::new(fonts.clone()),
11800            image_registry: Arc::new(ImageRegistry::new()),
11801            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11802        };
11803
11804        let mut renderer = WgpuRenderer::default();
11805        let without_terminal = build_frame("inspecto");
11806        renderer.render(&without_terminal).unwrap();
11807        let without_terminal_pixels = renderer
11808            .capture_last_frame_rgba(without_terminal.window_id)
11809            .unwrap();
11810
11811        let with_terminal = build_frame("inspector");
11812        renderer.render(&with_terminal).unwrap();
11813        let with_terminal_pixels = renderer
11814            .capture_last_frame_rgba(with_terminal.window_id)
11815            .unwrap();
11816
11817        let diff_count = rgba_image_diff_count(&without_terminal_pixels, &with_terminal_pixels);
11818
11819        assert!(
11820            diff_count > 0,
11821            "terminal glyph vanished at fractional scale (diff_count={diff_count})"
11822        );
11823    }
11824
11825    #[test]
11826    fn analytic_stroke_rect_renders_at_fractional_scale() {
11827        let frame = SceneFrame {
11828            window_id: WindowId::new(97),
11829            viewport: Size::new(220.0, 64.0),
11830            surface_size: Size::new(330.0, 96.0),
11831            scale_factor: 1.5,
11832            dirty_regions: Vec::new(),
11833            layer_updates: Vec::new(),
11834            scene: {
11835                let mut scene = Scene::new();
11836                scene.push(SceneCommand::FillRect {
11837                    rect: Rect::new(0.0, 0.0, 220.0, 64.0),
11838                    brush: Color::WHITE.into(),
11839                });
11840                scene.push(SceneCommand::StrokeRect {
11841                    rect: Rect::new(12.0, 12.0, 180.0, 32.0),
11842                    brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
11843                    stroke: StrokeStyle::new(1.0),
11844                });
11845                scene
11846            },
11847            font_registry: Arc::new(FontRegistry::new()),
11848            image_registry: Arc::new(ImageRegistry::new()),
11849            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11850        };
11851
11852        let mut renderer = WgpuRenderer::default();
11853        renderer.render(&frame).unwrap();
11854        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
11855
11856        let changed_pixels = pixels
11857            .pixels()
11858            .chunks_exact(4)
11859            .filter(|pixel| {
11860                !rgba_channels_match_with_tolerance(
11861                    pixel,
11862                    &[255, 255, 255, 255],
11863                    RGBA_CHANNEL_TOLERANCE,
11864                )
11865            })
11866            .count();
11867
11868        assert!(
11869            changed_pixels > 500,
11870            "analytic stroke rect disappeared at fractional scale (changed_pixels={changed_pixels})"
11871        );
11872    }
11873
11874    #[test]
11875    fn analytic_stroke_path_keeps_nominal_line_thickness() {
11876        let mut builder = PathBuilder::new();
11877        builder
11878            .move_to(Point::new(24.0, 32.0))
11879            .line_to(Point::new(196.0, 32.0));
11880
11881        let frame = SceneFrame {
11882            window_id: WindowId::new(98),
11883            viewport: Size::new(220.0, 64.0),
11884            surface_size: Size::new(220.0, 64.0),
11885            scale_factor: 1.0,
11886            dirty_regions: Vec::new(),
11887            layer_updates: Vec::new(),
11888            scene: {
11889                let mut scene = Scene::new();
11890                scene.push(SceneCommand::FillRect {
11891                    rect: Rect::new(0.0, 0.0, 220.0, 64.0),
11892                    brush: Color::WHITE.into(),
11893                });
11894                scene.push(SceneCommand::StrokePath {
11895                    path: builder.build(),
11896                    brush: Color::BLACK.into(),
11897                    stroke: StrokeStyle::new(1.0),
11898                });
11899                scene
11900            },
11901            font_registry: Arc::new(FontRegistry::new()),
11902            image_registry: Arc::new(ImageRegistry::new()),
11903            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11904        };
11905
11906        let mut renderer = WgpuRenderer::default();
11907        renderer.render(&frame).unwrap();
11908        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
11909        let visible_rows = non_white_row_count(&pixels, Rect::new(20.0, 26.0, 180.0, 12.0));
11910
11911        assert!(
11912            visible_rows <= 3,
11913            "analytic one-pixel stroke expanded across too many rows (visible_rows={visible_rows})"
11914        );
11915    }
11916
11917    #[test]
11918    fn soft_rounded_border_retains_most_ink_when_feathering_is_enabled() {
11919        let build_frame = || {
11920            let mut scene = Scene::new();
11921            scene.push(SceneCommand::FillRect {
11922                rect: Rect::new(0.0, 0.0, 240.0, 72.0),
11923                brush: Color::WHITE.into(),
11924            });
11925            scene.push(SceneCommand::FillPath {
11926                path: Path::rounded_rect(Rect::new(12.0, 16.0, 196.0, 36.0), 8.0),
11927                brush: Color::rgba(1.0, 1.0, 1.0, 1.0).into(),
11928            });
11929            scene.push(SceneCommand::StrokePath {
11930                path: Path::rounded_rect(Rect::new(12.0, 16.0, 196.0, 36.0), 8.0),
11931                brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
11932                stroke: StrokeStyle::new(1.0 / 1.5),
11933            });
11934
11935            SceneFrame {
11936                window_id: WindowId::new(99),
11937                viewport: Size::new(240.0, 72.0),
11938                surface_size: Size::new(360.0, 108.0),
11939                scale_factor: 1.5,
11940                dirty_regions: Vec::new(),
11941                layer_updates: Vec::new(),
11942                scene,
11943                font_registry: Arc::new(FontRegistry::new()),
11944                image_registry: Arc::new(ImageRegistry::new()),
11945                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11946            }
11947        };
11948
11949        let frame = build_frame();
11950
11951        let mut feathered = WgpuRenderer::default()
11952            .with_feathering_enabled(true)
11953            .with_feather_width(1.0);
11954        feathered.render(&frame).unwrap();
11955        let feathered_pixels = feathered.capture_last_frame_rgba(frame.window_id).unwrap();
11956
11957        let mut hard = WgpuRenderer::default().with_feathering_enabled(false);
11958        hard.render(&frame).unwrap();
11959        let hard_pixels = hard.capture_last_frame_rgba(frame.window_id).unwrap();
11960
11961        let crop = Rect::new(10.0, 14.0, 200.0, 40.0);
11962        let feathered_ink = ink_pixel_count(&feathered_pixels, crop);
11963        let hard_ink = ink_pixel_count(&hard_pixels, crop);
11964
11965        assert!(
11966            feathered_ink * 5 >= hard_ink * 4,
11967            "feathered rounded border lost too much ink at fractional scale (feathered_ink={feathered_ink}, hard_ink={hard_ink})"
11968        );
11969    }
11970
11971    #[test]
11972    fn soft_control_border_and_chevrons_retain_visible_ink_when_feathering_is_enabled() {
11973        fn line_path(start: Point, end: Point) -> Path {
11974            let mut builder = PathBuilder::new();
11975            builder.move_to(start).line_to(end);
11976            builder.build()
11977        }
11978
11979        fn chevron_path(bounds: Rect, direction: f32) -> Path {
11980            let center = Point::new(
11981                bounds.x() + (bounds.width() * 0.5),
11982                bounds.y() + (bounds.height() * 0.5),
11983            );
11984            let mut builder = PathBuilder::new();
11985            if direction.is_sign_positive() {
11986                builder
11987                    .move_to(Point::new(bounds.x(), bounds.y() + (bounds.height() * 0.3)))
11988                    .line_to(Point::new(
11989                        center.x,
11990                        bounds.max_y() - (bounds.height() * 0.3),
11991                    ))
11992                    .line_to(Point::new(
11993                        bounds.max_x(),
11994                        bounds.y() + (bounds.height() * 0.3),
11995                    ));
11996            } else {
11997                builder
11998                    .move_to(Point::new(
11999                        bounds.x(),
12000                        bounds.max_y() - (bounds.height() * 0.3),
12001                    ))
12002                    .line_to(Point::new(center.x, bounds.y() + (bounds.height() * 0.3)))
12003                    .line_to(Point::new(
12004                        bounds.max_x(),
12005                        bounds.max_y() - (bounds.height() * 0.3),
12006                    ));
12007            }
12008            builder.build()
12009        }
12010
12011        let build_frame = || {
12012            let mut scene = Scene::new();
12013            scene.push(SceneCommand::FillRect {
12014                rect: Rect::new(0.0, 0.0, 220.0, 72.0),
12015                brush: Color::WHITE.into(),
12016            });
12017            scene.push(SceneCommand::StrokePath {
12018                path: Path::rounded_rect(Rect::new(10.0, 16.0, 170.0, 40.0), 6.0),
12019                brush: Color::rgba(0.47, 0.49, 0.53, 1.0).into(),
12020                stroke: StrokeStyle::new(1.0),
12021            });
12022            scene.push(SceneCommand::StrokePath {
12023                path: line_path(Point::new(154.0, 22.0), Point::new(154.0, 50.0)),
12024                brush: Color::rgba(0.73, 0.73, 0.75, 1.0).into(),
12025                stroke: StrokeStyle::new(1.0),
12026            });
12027            scene.push(SceneCommand::StrokePath {
12028                path: chevron_path(Rect::new(156.0, 18.0, 16.0, 14.0), -1.0),
12029                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12030                stroke: StrokeStyle::new(1.8),
12031            });
12032            scene.push(SceneCommand::StrokePath {
12033                path: chevron_path(Rect::new(156.0, 40.0, 16.0, 14.0), 1.0),
12034                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12035                stroke: StrokeStyle::new(1.8),
12036            });
12037            scene.push(SceneCommand::StrokePath {
12038                path: Path::rounded_rect(Rect::new(10.0, 16.0, 196.0, 40.0), 6.0),
12039                brush: Color::rgba(0.73, 0.73, 0.75, 1.0).into(),
12040                stroke: StrokeStyle::new(1.0),
12041            });
12042            scene.push(SceneCommand::StrokePath {
12043                path: chevron_path(Rect::new(178.0, 27.0, 18.0, 18.0), 1.0),
12044                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12045                stroke: StrokeStyle::new(1.8),
12046            });
12047
12048            SceneFrame {
12049                window_id: WindowId::new(102),
12050                viewport: Size::new(220.0, 72.0),
12051                surface_size: Size::new(220.0, 72.0),
12052                scale_factor: 1.0,
12053                dirty_regions: Vec::new(),
12054                layer_updates: Vec::new(),
12055                scene,
12056                font_registry: Arc::new(FontRegistry::new()),
12057                image_registry: Arc::new(ImageRegistry::new()),
12058                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12059            }
12060        };
12061
12062        let frame = build_frame();
12063
12064        let mut feathered = WgpuRenderer::default()
12065            .with_feathering_enabled(true)
12066            .with_feather_width(1.0);
12067        feathered.render(&frame).unwrap();
12068        let feathered_pixels = feathered.capture_last_frame_rgba(frame.window_id).unwrap();
12069
12070        let mut hard = WgpuRenderer::default().with_feathering_enabled(false);
12071        hard.render(&frame).unwrap();
12072        let hard_pixels = hard.capture_last_frame_rgba(frame.window_id).unwrap();
12073
12074        let number_input_crop = Rect::new(8.0, 14.0, 172.0, 44.0);
12075        let select_crop = Rect::new(8.0, 14.0, 200.0, 44.0);
12076        let feathered_number_input_ink = ink_pixel_count(&feathered_pixels, number_input_crop);
12077        let hard_number_input_ink = ink_pixel_count(&hard_pixels, number_input_crop);
12078        let feathered_select_ink = ink_pixel_count(&feathered_pixels, select_crop);
12079        let hard_select_ink = ink_pixel_count(&hard_pixels, select_crop);
12080
12081        assert!(
12082            feathered_number_input_ink * 3 >= hard_number_input_ink,
12083            "feathered number-input border or chevrons lost too much ink (feathered={feathered_number_input_ink}, hard={hard_number_input_ink})"
12084        );
12085        assert!(
12086            feathered_select_ink * 3 >= hard_select_ink,
12087            "feathered select border or chevron lost too much ink (feathered={feathered_select_ink}, hard={hard_select_ink})"
12088        );
12089    }
12090
12091    #[test]
12092    fn analytic_splitter_rects_stay_at_divider_location() {
12093        let divider = Rect::new(140.0, 10.0, 12.0, 84.0);
12094        let handle = Rect::new(144.0, 38.0, 4.0, 28.0);
12095        let mut scene = Scene::new();
12096        scene.push(SceneCommand::FillRect {
12097            rect: Rect::new(0.0, 0.0, 220.0, 108.0),
12098            brush: Color::WHITE.into(),
12099        });
12100        scene.push(SceneCommand::FillRect {
12101            rect: divider,
12102            brush: Color::rgba(0.94, 0.955, 0.975, 1.0).into(),
12103        });
12104        scene.push(SceneCommand::StrokeRect {
12105            rect: divider,
12106            brush: Color::rgba(0.58, 0.62, 0.68, 1.0).into(),
12107            stroke: StrokeStyle::new(1.0),
12108        });
12109        scene.push(SceneCommand::FillRect {
12110            rect: handle,
12111            brush: Color::rgba(0.58, 0.62, 0.68, 0.9).into(),
12112        });
12113
12114        let frame = SceneFrame {
12115            window_id: WindowId::new(103),
12116            viewport: Size::new(220.0, 108.0),
12117            surface_size: Size::new(220.0, 108.0),
12118            scale_factor: 1.0,
12119            dirty_regions: Vec::new(),
12120            layer_updates: Vec::new(),
12121            scene,
12122            font_registry: Arc::new(FontRegistry::new()),
12123            image_registry: Arc::new(ImageRegistry::new()),
12124            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12125        };
12126
12127        let mut renderer = WgpuRenderer::default();
12128        renderer.render(&frame).unwrap();
12129        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12130
12131        let misplaced_left_pixels =
12132            non_white_pixel_count(&pixels, Rect::new(0.0, 0.0, 100.0, 108.0));
12133        let divider_pixels = non_white_pixel_count(&pixels, Rect::new(138.0, 8.0, 18.0, 88.0));
12134
12135        assert_eq!(
12136            misplaced_left_pixels, 0,
12137            "splitter coverage rendered away from the divider"
12138        );
12139        assert!(
12140            divider_pixels > 250,
12141            "splitter divider did not render enough visible pixels at its expected location (divider_pixels={divider_pixels})"
12142        );
12143    }
12144
12145    #[test]
12146    fn transformed_layer_keeps_analytic_path_at_translated_location() {
12147        let layer_id = WidgetId::new(104);
12148        let window_id = WindowId::new(104);
12149        let build_layer = |x: f32| {
12150            let bounds = Rect::new(x, 12.0, 72.0, 52.0);
12151            let descriptor =
12152                SceneLayerDescriptor::new(SceneLayerId::from_widget(layer_id), layer_id, bounds)
12153                    .with_content_bounds(bounds)
12154                    .with_paint_bounds(bounds)
12155                    .with_cache_policy(LayerCachePolicy::Direct);
12156
12157            let mut layer_scene = Scene::new();
12158            layer_scene.push(SceneCommand::FillPath {
12159                path: Path::rounded_rect(Rect::new(x + 14.0, 24.0, 44.0, 24.0), 7.0),
12160                brush: Color::rgba(0.18, 0.32, 0.86, 1.0).into(),
12161            });
12162
12163            (
12164                descriptor.clone(),
12165                SceneLayer::from_descriptor(descriptor, layer_scene),
12166            )
12167        };
12168
12169        let build_frame = |descriptor: SceneLayerDescriptor, layer: SceneLayer, update_kind| {
12170            let mut scene = Scene::new();
12171            scene.push(SceneCommand::FillRect {
12172                rect: Rect::new(0.0, 0.0, 240.0, 92.0),
12173                brush: Color::WHITE.into(),
12174            });
12175            scene.push(SceneCommand::Layer(layer));
12176
12177            SceneFrame {
12178                window_id,
12179                viewport: Size::new(240.0, 92.0),
12180                surface_size: Size::new(240.0, 92.0),
12181                scale_factor: 1.0,
12182                dirty_regions: Vec::new(),
12183                layer_updates: vec![SceneLayerUpdate::from_descriptor(update_kind, descriptor)],
12184                scene,
12185                font_registry: Arc::new(FontRegistry::new()),
12186                image_registry: Arc::new(ImageRegistry::new()),
12187                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12188            }
12189        };
12190
12191        let (initial_descriptor, initial_layer) = build_layer(28.0);
12192        let (moved_descriptor, moved_layer) = build_layer(136.0);
12193
12194        let mut renderer = WgpuRenderer::default();
12195        let first = build_frame(
12196            initial_descriptor,
12197            initial_layer,
12198            SceneLayerUpdateKind::Content,
12199        );
12200        renderer.render(&first).unwrap();
12201
12202        let second = build_frame(
12203            moved_descriptor,
12204            moved_layer,
12205            SceneLayerUpdateKind::Transform,
12206        );
12207        renderer.render(&second).unwrap();
12208        let pixels = renderer.capture_last_frame_rgba(window_id).unwrap();
12209
12210        let old_location_pixels = non_white_pixel_count(&pixels, Rect::new(34.0, 18.0, 60.0, 40.0));
12211        let moved_location_pixels =
12212            non_white_pixel_count(&pixels, Rect::new(142.0, 18.0, 60.0, 40.0));
12213
12214        assert_eq!(
12215            old_location_pixels, 0,
12216            "translated feathered path left pixels at its previous layer location"
12217        );
12218        assert!(
12219            moved_location_pixels > 400,
12220            "translated feathered path did not render at its moved layer location (moved_location_pixels={moved_location_pixels})"
12221        );
12222    }
12223
12224    #[test]
12225    fn cached_layer_matches_direct_for_tight_rounded_border_at_fractional_scale() {
12226        let widget_id = WidgetId::new(100);
12227        let build_frame = |cache_policy| {
12228            let descriptor = SceneLayerDescriptor::new(
12229                SceneLayerId::from_widget(widget_id),
12230                widget_id,
12231                Rect::new(0.0, 0.0, 220.0, 64.0),
12232            )
12233            .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 64.0))
12234            .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 64.0))
12235            .with_cache_policy(cache_policy);
12236
12237            let mut layer_scene = Scene::new();
12238            layer_scene.push(SceneCommand::FillRect {
12239                rect: Rect::new(0.0, 0.0, 220.0, 64.0),
12240                brush: Color::WHITE.into(),
12241            });
12242            layer_scene.push(SceneCommand::StrokePath {
12243                path: Path::rounded_rect(Rect::new(0.0, 0.0, 220.0, 64.0), 10.0),
12244                brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
12245                stroke: StrokeStyle::new(1.0 / 1.5),
12246            });
12247
12248            let mut scene = Scene::new();
12249            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12250                descriptor.clone(),
12251                layer_scene,
12252            )));
12253
12254            SceneFrame {
12255                window_id: WindowId::new(100),
12256                viewport: Size::new(220.0, 64.0),
12257                surface_size: Size::new(330.0, 96.0),
12258                scale_factor: 1.5,
12259                dirty_regions: Vec::new(),
12260                layer_updates: vec![
12261                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12262                        .with_damage(Rect::new(0.0, 0.0, 220.0, 64.0)),
12263                ],
12264                scene,
12265                font_registry: Arc::new(FontRegistry::new()),
12266                image_registry: Arc::new(ImageRegistry::new()),
12267                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12268            }
12269        };
12270
12271        let mut renderer = WgpuRenderer::default();
12272        let direct = build_frame(LayerCachePolicy::Direct);
12273        renderer.render(&direct).unwrap();
12274        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12275
12276        let cached = build_frame(LayerCachePolicy::Cached);
12277        renderer.render(&cached).unwrap();
12278        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12279
12280        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12281    }
12282
12283    #[test]
12284    fn retained_packets_match_direct_for_theme_preview_style_cards_at_fractional_scale() {
12285        let handle = FontHandle::new(153);
12286        let mut fonts = FontRegistry::new();
12287        fonts.insert(handle, load_test_font());
12288
12289        let widget_id = WidgetId::new(154);
12290        let build_frame = |window_id, cache_policy| {
12291            let descriptor = SceneLayerDescriptor::new(
12292                SceneLayerId::from_widget(widget_id),
12293                widget_id,
12294                Rect::new(0.0, 0.0, 640.0, 220.0),
12295            )
12296            .with_content_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
12297            .with_paint_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
12298            .with_cache_policy(cache_policy)
12299            .with_composition_mode(LayerCompositionMode::Scroll);
12300
12301            let mut layer_scene = Scene::new();
12302            layer_scene.push(SceneCommand::FillRect {
12303                rect: Rect::new(0.0, 0.0, 640.0, 220.0),
12304                brush: Color::rgba(0.94, 0.95, 0.98, 1.0).into(),
12305            });
12306
12307            let card_specs = [
12308                (
12309                    56.0,
12310                    Color::rgba(0.99, 0.99, 1.0, 1.0),
12311                    Color::rgba(0.19, 0.46, 0.91, 1.0),
12312                    Color::rgba(0.15, 0.73, 0.70, 1.0),
12313                    Color::rgba(0.10, 0.13, 0.19, 1.0),
12314                    Color::rgba(0.39, 0.45, 0.54, 1.0),
12315                    Color::rgba(0.82, 0.85, 0.91, 1.0),
12316                    "Light theme",
12317                ),
12318                (
12319                    344.0,
12320                    Color::rgba(0.14, 0.16, 0.21, 1.0),
12321                    Color::rgba(0.45, 0.60, 0.98, 1.0),
12322                    Color::rgba(0.96, 0.54, 0.31, 1.0),
12323                    Color::rgba(0.94, 0.95, 0.98, 1.0),
12324                    Color::rgba(0.68, 0.72, 0.80, 1.0),
12325                    Color::rgba(0.28, 0.31, 0.38, 1.0),
12326                    "Dark theme",
12327                ),
12328            ];
12329
12330            for (card_x, surface, accent, secondary, text_color, subtle_text, border, title) in
12331                card_specs
12332            {
12333                let card_rect = Rect::new(card_x, 24.0, 240.0, 172.0);
12334                layer_scene.push(SceneCommand::FillPath {
12335                    path: Path::rounded_rect(card_rect, 18.0),
12336                    brush: surface.into(),
12337                });
12338                layer_scene.push(SceneCommand::StrokePath {
12339                    path: Path::rounded_rect(card_rect, 18.0),
12340                    brush: border.into(),
12341                    stroke: StrokeStyle::new(1.0),
12342                });
12343                layer_scene.push(SceneCommand::DrawText(TextRun {
12344                    rect: Rect::new(card_x + 20.0, 44.0, 172.0, 24.0),
12345                    text: title.to_string(),
12346                    style: TextStyle {
12347                        font: Some(handle),
12348                        font_size: 18.0,
12349                        line_height: 22.0,
12350                        color: text_color,
12351                        ..Default::default()
12352                    },
12353                }));
12354                layer_scene.push(SceneCommand::DrawText(TextRun {
12355                    rect: Rect::new(card_x + 20.0, 76.0, 188.0, 20.0),
12356                    text: format!(
12357                        "{} base surface with {} accent for primary actions.",
12358                        title.split_whitespace().next().unwrap().to_lowercase(),
12359                        title.split_whitespace().next().unwrap().to_lowercase(),
12360                    ),
12361                    style: TextStyle {
12362                        font: Some(handle),
12363                        font_size: 13.0,
12364                        line_height: 18.0,
12365                        color: subtle_text,
12366                        ..Default::default()
12367                    },
12368                }));
12369                layer_scene.push(SceneCommand::FillPath {
12370                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 108.0, 220.0, 36.0), 10.0),
12371                    brush: surface.into(),
12372                });
12373                layer_scene.push(SceneCommand::StrokePath {
12374                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 108.0, 220.0, 36.0), 10.0),
12375                    brush: border.into(),
12376                    stroke: StrokeStyle::new(1.0),
12377                });
12378                layer_scene.push(SceneCommand::DrawText(TextRun {
12379                    rect: Rect::new(card_x + 36.0, 118.0, 172.0, 16.0),
12380                    text: "Find layer, panel, or asset".to_string(),
12381                    style: TextStyle {
12382                        font: Some(handle),
12383                        font_size: 13.0,
12384                        line_height: 18.0,
12385                        color: subtle_text,
12386                        ..Default::default()
12387                    },
12388                }));
12389                layer_scene.push(SceneCommand::FillPath {
12390                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 156.0, 86.0, 28.0), 14.0),
12391                    brush: accent.into(),
12392                });
12393                layer_scene.push(SceneCommand::DrawText(TextRun {
12394                    rect: Rect::new(card_x + 38.0, 163.0, 48.0, 16.0),
12395                    text: "Inspect".to_string(),
12396                    style: TextStyle {
12397                        font: Some(handle),
12398                        font_size: 13.0,
12399                        line_height: 18.0,
12400                        color: Color::rgba(1.0, 1.0, 1.0, 1.0),
12401                        ..Default::default()
12402                    },
12403                }));
12404                layer_scene.push(SceneCommand::FillRect {
12405                    rect: Rect::new(card_x + 128.0, 160.0, 28.0, 16.0),
12406                    brush: secondary.into(),
12407                });
12408                layer_scene.push(SceneCommand::DrawText(TextRun {
12409                    rect: Rect::new(card_x + 164.0, 158.33333, 68.0, 20.0),
12410                    text: "Live updates".to_string(),
12411                    style: TextStyle {
12412                        font: Some(handle),
12413                        font_size: 14.0,
12414                        line_height: 20.0,
12415                        color: text_color,
12416                        ..Default::default()
12417                    },
12418                }));
12419            }
12420
12421            let mut scene = Scene::new();
12422            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12423                descriptor.clone(),
12424                layer_scene,
12425            )));
12426
12427            SceneFrame {
12428                window_id,
12429                viewport: Size::new(640.0, 220.0),
12430                surface_size: Size::new(960.0, 330.0),
12431                scale_factor: 1.5,
12432                dirty_regions: Vec::new(),
12433                layer_updates: vec![
12434                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12435                        .with_damage(Rect::new(0.0, 0.0, 640.0, 220.0)),
12436                ],
12437                scene,
12438                font_registry: Arc::new(fonts.clone()),
12439                image_registry: Arc::new(ImageRegistry::new()),
12440                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12441            }
12442        };
12443
12444        let mut renderer = WgpuRenderer::default();
12445        let direct = build_frame(WindowId::new(153), LayerCachePolicy::Direct);
12446        renderer.render(&direct).unwrap();
12447        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12448
12449        let cached = build_frame(WindowId::new(154), LayerCachePolicy::Cached);
12450        renderer.render(&cached).unwrap();
12451        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12452
12453        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12454    }
12455
12456    #[test]
12457    fn cached_layer_matches_direct_for_tight_tab_text_at_fractional_scale() {
12458        let handle = FontHandle::new(30);
12459        let mut fonts = FontRegistry::new();
12460        fonts.insert(handle, load_test_font());
12461
12462        let widget_id = WidgetId::new(101);
12463        let build_frame = |cache_policy| {
12464            let descriptor = SceneLayerDescriptor::new(
12465                SceneLayerId::from_widget(widget_id),
12466                widget_id,
12467                Rect::new(0.0, 0.0, 236.0, 44.0),
12468            )
12469            .with_content_bounds(Rect::new(0.0, 0.0, 236.0, 44.0))
12470            .with_paint_bounds(Rect::new(0.0, 0.0, 236.0, 44.0))
12471            .with_cache_policy(cache_policy);
12472
12473            let mut layer_scene = Scene::new();
12474            layer_scene.push(SceneCommand::FillRect {
12475                rect: Rect::new(0.0, 0.0, 236.0, 44.0),
12476                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
12477            });
12478            layer_scene.push(SceneCommand::DrawText(TextRun {
12479                rect: Rect::new(10.0, 10.0, 216.0, 20.0),
12480                text: "Inspector".to_string(),
12481                style: TextStyle {
12482                    font: Some(handle),
12483                    font_size: 12.0,
12484                    line_height: 16.0,
12485                    color: Color::rgba(0.15, 0.19, 0.26, 1.0),
12486                    ..TextStyle::default()
12487                },
12488            }));
12489
12490            let mut scene = Scene::new();
12491            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12492                descriptor.clone(),
12493                layer_scene,
12494            )));
12495
12496            SceneFrame {
12497                window_id: WindowId::new(101),
12498                viewport: Size::new(236.0, 44.0),
12499                surface_size: Size::new(354.0, 66.0),
12500                scale_factor: 1.5,
12501                dirty_regions: Vec::new(),
12502                layer_updates: vec![
12503                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12504                        .with_damage(Rect::new(0.0, 0.0, 236.0, 44.0)),
12505                ],
12506                scene,
12507                font_registry: Arc::new(fonts.clone()),
12508                image_registry: Arc::new(ImageRegistry::new()),
12509                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12510            }
12511        };
12512
12513        let mut renderer = WgpuRenderer::default();
12514        let direct = build_frame(LayerCachePolicy::Direct);
12515        renderer.render(&direct).unwrap();
12516        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12517
12518        let cached = build_frame(LayerCachePolicy::Cached);
12519        renderer.render(&cached).unwrap();
12520        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12521
12522        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12523    }
12524
12525    #[test]
12526    fn build_vertices_uses_registered_font_handle() {
12527        let handle = FontHandle::new(17);
12528        let mut fonts = FontRegistry::new();
12529        fonts.insert(handle, load_test_font());
12530
12531        let mut scene = Scene::new();
12532        scene.push(SceneCommand::DrawText(TextRun {
12533            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
12534            text: "registered".to_string(),
12535            style: TextStyle {
12536                font: Some(handle),
12537                ..TextStyle::new(Color::WHITE)
12538            },
12539        }));
12540
12541        let mut text_engine = TextEngine::new().unwrap();
12542        let vertices = build_vertices(
12543            &SceneFrame {
12544                window_id: WindowId::new(3),
12545                viewport: Size::new(160.0, 60.0),
12546                surface_size: Size::new(160.0, 60.0),
12547                scale_factor: 1.0,
12548                dirty_regions: Vec::new(),
12549                layer_updates: Vec::new(),
12550                scene,
12551                font_registry: Arc::new(fonts),
12552                image_registry: Arc::new(ImageRegistry::new()),
12553                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12554            },
12555            &mut text_engine,
12556        )
12557        .unwrap();
12558
12559        assert!(!vertices.is_empty());
12560    }
12561
12562    #[test]
12563    fn build_vertices_errors_for_unregistered_font_handle() {
12564        let mut scene = Scene::new();
12565        scene.push(SceneCommand::DrawText(TextRun {
12566            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
12567            text: "missing".to_string(),
12568            style: TextStyle {
12569                font: Some(FontHandle::new(404)),
12570                ..TextStyle::new(Color::WHITE)
12571            },
12572        }));
12573
12574        let mut text_engine = TextEngine::new().unwrap();
12575        let error = match build_vertices(
12576            &SceneFrame {
12577                window_id: WindowId::new(4),
12578                viewport: Size::new(160.0, 60.0),
12579                surface_size: Size::new(160.0, 60.0),
12580                scale_factor: 1.0,
12581                dirty_regions: Vec::new(),
12582                layer_updates: Vec::new(),
12583                scene,
12584                font_registry: Arc::new(FontRegistry::new()),
12585                image_registry: Arc::new(ImageRegistry::new()),
12586                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12587            },
12588            &mut text_engine,
12589        ) {
12590            Ok(_) => panic!("expected missing font handle to fail during shaping"),
12591            Err(error) => error,
12592        };
12593
12594        assert!(
12595            error
12596                .to_string()
12597                .contains("font handle 404 is not registered")
12598        );
12599    }
12600
12601    #[test]
12602    fn renderer_grows_atlas_pages_when_text_atlas_fills_mid_frame() {
12603        let mut scene = Scene::new();
12604        let text: String = (33u8..=126).map(char::from).collect();
12605        scene.push(SceneCommand::DrawText(TextRun {
12606            rect: Rect::new(4.0, 6.0, 1800.0, 32.0),
12607            text,
12608            style: TextStyle {
12609                font_size: 18.0,
12610                line_height: 22.0,
12611                ..TextStyle::new(Color::WHITE)
12612            },
12613        }));
12614
12615        let frame = SceneFrame {
12616            window_id: WindowId::new(16),
12617            viewport: Size::new(1800.0, 64.0),
12618            surface_size: Size::new(1800.0, 64.0),
12619            scale_factor: 1.0,
12620            dirty_regions: Vec::new(),
12621            layer_updates: Vec::new(),
12622            scene,
12623            font_registry: Arc::new(FontRegistry::new()),
12624            image_registry: Arc::new(ImageRegistry::new()),
12625            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12626        };
12627
12628        let mut renderer = WgpuRenderer::new();
12629        let mut text_engine = TextEngine::new().unwrap();
12630        // Tiny pages with room for several layers: the printable-ASCII run overflows the first
12631        // page, so the atlas must grow onto additional texture-array layers rather than reset.
12632        text_engine.atlas = TextAtlasPages::new(96, 96, 4);
12633        renderer.text_engine = Some(text_engine);
12634
12635        renderer.render(&frame).unwrap();
12636
12637        let active_text_engine = renderer
12638            .text_engine
12639            .as_ref()
12640            .expect("renderer keeps the same text engine -- no nuclear reset");
12641        // The engine was NOT replaced: it still has the small page size we configured (a reset
12642        // would have rebuilt it at the default page size).
12643        assert_eq!(active_text_engine.atlas.page_size(), (96, 96));
12644        // Overflowing one page grew the atlas onto more pages instead of resetting.
12645        assert!(
12646            active_text_engine.atlas.page_count() >= 2,
12647            "atlas should have grown onto multiple pages"
12648        );
12649        assert!(active_text_engine.glyph_cache_stats().0 > 32);
12650
12651        let stats = renderer
12652            .last_frame_stats(frame.window_id)
12653            .expect("renderer should record frame stats");
12654        assert!(stats.text_glyph_instance_count > 0);
12655
12656        let image = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12657        assert!(
12658            image
12659                .pixels()
12660                .chunks_exact(4)
12661                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE),
12662            "frame should render visible text across atlas pages"
12663        );
12664    }
12665
12666    #[test]
12667    fn multi_page_atlas_is_stable_across_frames() {
12668        // Rendering the same overflowing scene twice must not re-rasterize glyphs or churn pages.
12669        // This is the property that replaces the old "atlas full -> full reset every frame"
12670        // stutter: once warm, repeat frames are pure cache hits.
12671        let text: String = (33u8..=126).map(char::from).collect();
12672        let make_frame = || {
12673            let mut scene = Scene::new();
12674            scene.push(SceneCommand::DrawText(TextRun {
12675                rect: Rect::new(4.0, 6.0, 1800.0, 32.0),
12676                text: text.clone(),
12677                style: TextStyle {
12678                    font_size: 18.0,
12679                    line_height: 22.0,
12680                    ..TextStyle::new(Color::WHITE)
12681                },
12682            }));
12683            SceneFrame {
12684                window_id: WindowId::new(17),
12685                viewport: Size::new(1800.0, 64.0),
12686                surface_size: Size::new(1800.0, 64.0),
12687                scale_factor: 1.0,
12688                dirty_regions: Vec::new(),
12689                layer_updates: Vec::new(),
12690                scene,
12691                font_registry: Arc::new(FontRegistry::new()),
12692                image_registry: Arc::new(ImageRegistry::new()),
12693                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12694            }
12695        };
12696
12697        let mut renderer = WgpuRenderer::new();
12698        let mut text_engine = TextEngine::new().unwrap();
12699        text_engine.atlas = TextAtlasPages::new(96, 96, 4);
12700        renderer.text_engine = Some(text_engine);
12701
12702        renderer.render(&make_frame()).unwrap();
12703        let (entries_after_first, pages_after_first) = {
12704            let text_engine = renderer.text_engine.as_ref().unwrap();
12705            (
12706                text_engine.glyph_cache_stats().0,
12707                text_engine.atlas.page_count(),
12708            )
12709        };
12710        assert!(pages_after_first >= 2, "glyphs should span multiple pages");
12711
12712        renderer.render(&make_frame()).unwrap();
12713        let text_engine = renderer.text_engine.as_ref().unwrap();
12714        assert_eq!(
12715            text_engine.atlas.page_count(),
12716            pages_after_first,
12717            "page count must be stable across frames (no growth/thrash)"
12718        );
12719        assert_eq!(
12720            text_engine.atlas.page_size(),
12721            (96, 96),
12722            "engine must not have been reset"
12723        );
12724        assert_eq!(
12725            text_engine.glyph_cache_stats().0,
12726            entries_after_first,
12727            "no glyphs should be re-rasterized on the second frame"
12728        );
12729
12730        let image = renderer.capture_last_frame_rgba(WindowId::new(17)).unwrap();
12731        assert!(
12732            image
12733                .pixels()
12734                .chunks_exact(4)
12735                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE)
12736        );
12737    }
12738
12739    #[test]
12740    fn multi_page_atlas_evicts_without_corruption_under_pressure() {
12741        // A tight 2-page budget with a rotating glyph set forces LRU eviction across frames. The
12742        // atlas must never exceed its budget, the glyph cache must never dangle past the live
12743        // pages (coupled entries are dropped on eviction), and rendering must keep working.
12744        let texts = [
12745            "the quick brown fox",
12746            "JUMPS OVER THE LAZY",
12747            "0123456789 !?#@&*()",
12748            "Pack my box w/ jugs",
12749            "Sphinx of black quartz",
12750        ];
12751
12752        let mut renderer = WgpuRenderer::new();
12753        let mut text_engine = TextEngine::new().unwrap();
12754        text_engine.atlas = TextAtlasPages::new(64, 64, 2);
12755        renderer.text_engine = Some(text_engine);
12756
12757        for label in texts {
12758            let mut scene = Scene::new();
12759            scene.push(SceneCommand::DrawText(TextRun {
12760                rect: Rect::new(4.0, 6.0, 600.0, 28.0),
12761                text: label.to_string(),
12762                style: TextStyle {
12763                    font_size: 18.0,
12764                    line_height: 22.0,
12765                    ..TextStyle::new(Color::WHITE)
12766                },
12767            }));
12768            let frame = SceneFrame {
12769                window_id: WindowId::new(21),
12770                viewport: Size::new(600.0, 40.0),
12771                surface_size: Size::new(600.0, 40.0),
12772                scale_factor: 1.0,
12773                dirty_regions: Vec::new(),
12774                layer_updates: Vec::new(),
12775                scene,
12776                font_registry: Arc::new(FontRegistry::new()),
12777                image_registry: Arc::new(ImageRegistry::new()),
12778                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12779            };
12780
12781            renderer.render(&frame).unwrap();
12782
12783            let text_engine = renderer.text_engine.as_ref().unwrap();
12784            let pages = text_engine.atlas.page_count();
12785            assert!(pages <= 2, "atlas must respect the page budget");
12786            assert!(
12787                text_engine
12788                    .glyph_cache
12789                    .values()
12790                    .all(|cached| cached.page_index < pages),
12791                "every cached glyph must reference a live page after eviction"
12792            );
12793        }
12794
12795        let image = renderer.capture_last_frame_rgba(WindowId::new(21)).unwrap();
12796        assert!(
12797            image
12798                .pixels()
12799                .chunks_exact(4)
12800                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE)
12801        );
12802    }
12803
12804    #[test]
12805    fn retained_compositor_uses_registered_image_handle() {
12806        let handle = ImageHandle::new(23);
12807        let mut images = ImageRegistry::new();
12808        images.insert(
12809            handle,
12810            RegisteredImage::from_rgba8(
12811                2,
12812                2,
12813                vec![
12814                    255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
12815                ],
12816            )
12817            .unwrap(),
12818        );
12819
12820        let mut scene = Scene::new();
12821        scene.push(SceneCommand::DrawImage {
12822            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
12823            source: ImageSource::new(handle),
12824        });
12825
12826        let mut text_engine = TextEngine::new().unwrap();
12827        let mut compositor = RetainedCompositorState::default();
12828        let ops = prepare_with_compositor(
12829            &SceneFrame {
12830                window_id: WindowId::new(7),
12831                viewport: Size::new(96.0, 64.0),
12832                surface_size: Size::new(96.0, 64.0),
12833                scale_factor: 1.0,
12834                dirty_regions: Vec::new(),
12835                layer_updates: Vec::new(),
12836                scene,
12837                font_registry: Arc::new(FontRegistry::new()),
12838                image_registry: Arc::new(images),
12839                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12840            },
12841            &mut text_engine,
12842            &mut compositor,
12843        )
12844        .unwrap();
12845
12846        assert_eq!(ops.draw_ops.len(), 1);
12847        let op = &ops.draw_ops[0];
12848        assert!(
12849            matches!(op.kind, DrawOpKind::Image { handle: value, sampling: ImageSampling::Linear } if value == handle)
12850        );
12851        assert_eq!(op.vertices.len, 6);
12852    }
12853
12854    #[test]
12855    fn renderer_samples_persistent_external_texture_updates() {
12856        let handle = ImageHandle::new(2301);
12857        let window_id = WindowId::new(2301);
12858        let viewport = Size::new(16.0, 16.0);
12859        let registry = WgpuExternalTextureRegistry::new();
12860        let mut renderer = WgpuRenderer::new().with_external_texture_registry(registry.clone());
12861
12862        // The first target initialization publishes the renderer-owned device
12863        // and queue to the shared registry.
12864        renderer
12865            .render(&SceneFrame::new(window_id, viewport))
12866            .unwrap();
12867        let context = registry.context().expect("renderer context attached");
12868
12869        let direct_handle = ImageHandle::new(2302);
12870        let direct_texture = context.device().create_texture(&wgpu::TextureDescriptor {
12871            label: Some("SUI direct external texture test"),
12872            size: wgpu::Extent3d {
12873                width: 4,
12874                height: 3,
12875                depth_or_array_layers: 1,
12876            },
12877            mip_level_count: 1,
12878            sample_count: 1,
12879            dimension: wgpu::TextureDimension::D2,
12880            format: wgpu::TextureFormat::Rgba8UnormSrgb,
12881            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
12882            view_formats: &[],
12883        });
12884        let direct_descriptor = registry
12885            .register_texture(direct_handle, direct_texture)
12886            .unwrap();
12887        assert_eq!(
12888            (direct_descriptor.width(), direct_descriptor.height()),
12889            (4, 3)
12890        );
12891        assert!(registry.unregister(direct_handle));
12892
12893        let red = Arc::<[u8]>::from(
12894            [255, 0, 0, 255]
12895                .into_iter()
12896                .cycle()
12897                .take(2 * 2 * 4)
12898                .collect::<Vec<_>>(),
12899        );
12900        let descriptor = registry.upload_rgba8(handle, 2, 2, red, 1).unwrap();
12901        let first_binding_revision = registry.resolve(handle).unwrap().binding_revision;
12902        let mut images = ImageRegistry::new();
12903        images.insert_external(handle, descriptor);
12904
12905        let mut scene = Scene::new();
12906        scene.push(SceneCommand::Clear(Color::BLACK));
12907        scene.push(SceneCommand::DrawImage {
12908            rect: Rect::new(0.0, 0.0, viewport.width, viewport.height),
12909            source: ImageSource::new(handle),
12910        });
12911        let mut frame = SceneFrame::new(window_id, viewport);
12912        frame.scene = scene;
12913        frame.image_registry = Arc::new(images);
12914
12915        renderer.render(&frame).unwrap();
12916        let first = renderer.capture_last_frame_rgba(window_id).unwrap();
12917        assert_rgba_pixel_near(&first, 8, 8, [255, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
12918
12919        let green = Arc::<[u8]>::from(
12920            [0, 255, 0, 255]
12921                .into_iter()
12922                .cycle()
12923                .take(2 * 2 * 4)
12924                .collect::<Vec<_>>(),
12925        );
12926        assert_eq!(
12927            registry.upload_rgba8(handle, 2, 2, green, 2).unwrap(),
12928            descriptor
12929        );
12930        assert_eq!(
12931            registry.resolve(handle).unwrap().binding_revision,
12932            first_binding_revision,
12933            "same-size updates must reuse the persistent GPU allocation"
12934        );
12935
12936        // The retained scene is unchanged; rendering again samples the newly
12937        // uploaded contents through the same image handle and bind group.
12938        renderer.render(&frame).unwrap();
12939        let second = renderer.capture_last_frame_rgba(window_id).unwrap();
12940        assert_rgba_pixel_near(&second, 8, 8, [0, 255, 0, 255], RGBA_CHANNEL_TOLERANCE);
12941    }
12942
12943    #[test]
12944    fn retained_compositor_preserves_transformed_image_quad() {
12945        let handle = ImageHandle::new(24);
12946        let mut images = ImageRegistry::new();
12947        images.insert(
12948            handle,
12949            RegisteredImage::from_rgba8(
12950                2,
12951                2,
12952                vec![
12953                    255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
12954                ],
12955            )
12956            .unwrap(),
12957        );
12958
12959        let rect = Rect::new(4.0, 6.0, 32.0, 24.0);
12960        let transform = Transform::translation(40.0, 10.0).then(Transform::rotation(0.35));
12961        let mut scene = Scene::new();
12962        scene.push(SceneCommand::PushTransform { transform });
12963        scene.push(SceneCommand::DrawImage {
12964            rect,
12965            source: ImageSource::new(handle),
12966        });
12967        scene.push(SceneCommand::PopTransform);
12968
12969        let mut text_engine = TextEngine::new().unwrap();
12970        let vertices = build_vertices(
12971            &SceneFrame {
12972                window_id: WindowId::new(7),
12973                viewport: Size::new(128.0, 96.0),
12974                surface_size: Size::new(128.0, 96.0),
12975                scale_factor: 1.0,
12976                dirty_regions: Vec::new(),
12977                layer_updates: Vec::new(),
12978                scene,
12979                font_registry: Arc::new(FontRegistry::new()),
12980                image_registry: Arc::new(images),
12981                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12982            },
12983            &mut text_engine,
12984        )
12985        .unwrap();
12986
12987        let expected = transform.transform_point(rect.origin);
12988        let expected = to_ndc(expected.x, expected.y, Size::new(128.0, 96.0));
12989        assert!((vertices[0].position[0] - expected[0]).abs() < 0.001);
12990        assert!((vertices[0].position[1] - expected[1]).abs() < 0.001);
12991    }
12992
12993    #[test]
12994    fn retained_compositor_errors_for_unregistered_image_handle() {
12995        let mut scene = Scene::new();
12996        scene.push(SceneCommand::DrawImage {
12997            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
12998            source: ImageSource::new(ImageHandle::new(88)),
12999        });
13000
13001        let mut text_engine = TextEngine::new().unwrap();
13002        let mut compositor = RetainedCompositorState::default();
13003        let error = prepare_with_compositor(
13004            &SceneFrame {
13005                window_id: WindowId::new(8),
13006                viewport: Size::new(96.0, 64.0),
13007                surface_size: Size::new(96.0, 64.0),
13008                scale_factor: 1.0,
13009                dirty_regions: Vec::new(),
13010                layer_updates: Vec::new(),
13011                scene,
13012                font_registry: Arc::new(FontRegistry::new()),
13013                image_registry: Arc::new(ImageRegistry::new()),
13014                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13015            },
13016            &mut text_engine,
13017            &mut compositor,
13018        )
13019        .unwrap_err();
13020
13021        assert!(
13022            error
13023                .to_string()
13024                .contains("image handle 88 is not registered")
13025        );
13026    }
13027
13028    #[test]
13029    fn renderer_feather_width_is_configurable() {
13030        let mut renderer = WgpuRenderer::new().with_feather_width(2.5);
13031
13032        assert_eq!(renderer.feather_width(), 2.5);
13033        assert!(!renderer.feathering_enabled());
13034
13035        renderer.set_feathering_enabled(true);
13036
13037        assert!(renderer.feathering_enabled());
13038
13039        renderer.set_feather_width(-3.0);
13040
13041        assert_eq!(renderer.feather_width(), 0.0);
13042
13043        renderer.set_feathering_enabled(false);
13044
13045        assert!(!renderer.feathering_enabled());
13046    }
13047
13048    /// Minimal RGBA8 PNG encoder using a single zlib "stored" (uncompressed) block, so the
13049    /// capture test can persist a screenshot without pulling in an image/png dependency.
13050    fn encode_png_rgba8(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
13051        fn crc32(bytes: &[u8]) -> u32 {
13052            let mut crc: u32 = 0xFFFF_FFFF;
13053            for &byte in bytes {
13054                crc ^= byte as u32;
13055                for _ in 0..8 {
13056                    let mask = (crc & 1).wrapping_neg();
13057                    crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
13058                }
13059            }
13060            !crc
13061        }
13062
13063        fn adler32(bytes: &[u8]) -> u32 {
13064            let mut a: u32 = 1;
13065            let mut b: u32 = 0;
13066            for &byte in bytes {
13067                a = (a + byte as u32) % 65521;
13068                b = (b + a) % 65521;
13069            }
13070            (b << 16) | a
13071        }
13072
13073        fn write_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
13074            out.extend_from_slice(&(data.len() as u32).to_be_bytes());
13075            let mut crc_input = Vec::with_capacity(4 + data.len());
13076            crc_input.extend_from_slice(kind);
13077            crc_input.extend_from_slice(data);
13078            out.extend_from_slice(&crc_input);
13079            out.extend_from_slice(&crc32(&crc_input).to_be_bytes());
13080        }
13081
13082        // Raw image data: one filter byte (0 = None) per scanline, then RGBA pixels.
13083        let stride = width as usize * 4;
13084        let mut raw = Vec::with_capacity((stride + 1) * height as usize);
13085        for row in 0..height as usize {
13086            raw.push(0);
13087            raw.extend_from_slice(&rgba[row * stride..(row + 1) * stride]);
13088        }
13089
13090        // zlib stream: 0x78 0x01 header, stored deflate blocks, adler32 trailer.
13091        let mut zlib = vec![0x78, 0x01];
13092        let mut offset = 0;
13093        while offset < raw.len() {
13094            let block = (raw.len() - offset).min(0xFFFF);
13095            let last = offset + block >= raw.len();
13096            zlib.push(if last { 1 } else { 0 });
13097            zlib.extend_from_slice(&(block as u16).to_le_bytes());
13098            zlib.extend_from_slice(&(!(block as u16)).to_le_bytes());
13099            zlib.extend_from_slice(&raw[offset..offset + block]);
13100            offset += block;
13101        }
13102        zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
13103
13104        let mut png = Vec::new();
13105        png.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
13106        let mut ihdr = Vec::with_capacity(13);
13107        ihdr.extend_from_slice(&width.to_be_bytes());
13108        ihdr.extend_from_slice(&height.to_be_bytes());
13109        ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // bit depth 8, color type 6 (RGBA)
13110        write_chunk(&mut png, b"IHDR", &ihdr);
13111        write_chunk(&mut png, b"IDAT", &zlib);
13112        write_chunk(&mut png, b"IEND", &[]);
13113        png
13114    }
13115
13116    #[test]
13117    fn rounded_rect_primitives_render_to_png_capture() {
13118        // Exercises the new rounded-rect (per-corner radii + border + soft shadow) and the
13119        // linear-gradient brush end to end: build a scene, render headless, persist a PNG.
13120        let window_id = WindowId::new(4242);
13121        let viewport = Size::new(320.0, 240.0);
13122
13123        let mut scene = Scene::new();
13124        scene.push(SceneCommand::Clear(Color::rgba(0.12, 0.13, 0.16, 1.0)));
13125
13126        // A shadowed, bordered rounded card inside a larger clip. The clip is wide enough
13127        // that the soft shadow remains visible around the card.
13128        scene.push(SceneCommand::PushClip {
13129            rect: Rect::new(16.0, 16.0, 180.0, 150.0),
13130        });
13131        scene.push(SceneCommand::FillRoundedRect {
13132            rect: Rect::new(40.0, 44.0, 120.0, 84.0),
13133            radii: [16.0; 4],
13134            brush: Brush::Solid(Color::rgba(0.20, 0.55, 0.95, 1.0)),
13135            border: Some(Border {
13136                width: 3.0,
13137                color: Color::rgba(0.95, 0.97, 1.0, 1.0),
13138            }),
13139            shadow: Some(ShadowParams {
13140                offset_x: 0.0,
13141                offset_y: 6.0,
13142                blur: 8.0,
13143                spread: 1.0,
13144                color: Color::rgba(0.0, 0.0, 0.0, 0.55),
13145            }),
13146        });
13147        scene.push(SceneCommand::PopClip);
13148
13149        // A per-corner-radii rounded rect (sharp tl/br, round tr/bl).
13150        scene.push(SceneCommand::FillRoundedRect {
13151            rect: Rect::new(210.0, 30.0, 90.0, 70.0),
13152            radii: [2.0, 20.0, 2.0, 20.0],
13153            brush: Brush::Solid(Color::rgba(0.95, 0.45, 0.30, 1.0)),
13154            border: None,
13155            shadow: None,
13156        });
13157
13158        // A horizontal linear-gradient rounded rect.
13159        scene.push(SceneCommand::FillRoundedRect {
13160            rect: Rect::new(40.0, 160.0, 240.0, 56.0),
13161            radii: [10.0; 4],
13162            brush: Brush::LinearGradient {
13163                start: Point::new(40.0, 188.0),
13164                end: Point::new(280.0, 188.0),
13165                stops: vec![
13166                    GradientStop {
13167                        offset: 0.0,
13168                        color: Color::rgba(0.10, 0.80, 0.55, 1.0),
13169                    },
13170                    GradientStop {
13171                        offset: 1.0,
13172                        color: Color::rgba(0.55, 0.20, 0.85, 1.0),
13173                    },
13174                ],
13175            },
13176            border: None,
13177            shadow: None,
13178        });
13179
13180        let frame = SceneFrame {
13181            window_id,
13182            viewport,
13183            surface_size: viewport,
13184            scale_factor: 1.0,
13185            dirty_regions: Vec::new(),
13186            layer_updates: Vec::new(),
13187            scene,
13188            font_registry: Arc::new(FontRegistry::new()),
13189            image_registry: Arc::new(ImageRegistry::new()),
13190            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13191        };
13192
13193        let mut renderer = WgpuRenderer::new();
13194        renderer
13195            .render(&frame)
13196            .expect("headless render of rounded-rect primitives should succeed");
13197
13198        let image = renderer
13199            .capture_last_frame_rgba(window_id)
13200            .expect("capture of rendered frame should succeed");
13201
13202        // The frame must contain visibly painted content (the clear color is opaque, so we
13203        // additionally check that some pixels differ from the background).
13204        let bg = [
13205            (0.12_f32.powf(1.0 / 2.2) * 255.0) as u8,
13206            (0.13_f32.powf(1.0 / 2.2) * 255.0) as u8,
13207            (0.16_f32.powf(1.0 / 2.2) * 255.0) as u8,
13208        ];
13209        let non_background = image.pixels().chunks_exact(4).any(|pixel| {
13210            (pixel[0] as i32 - bg[0] as i32).abs()
13211                + (pixel[1] as i32 - bg[1] as i32).abs()
13212                + (pixel[2] as i32 - bg[2] as i32).abs()
13213                > 24
13214        });
13215        assert!(
13216            non_background,
13217            "rendered frame should contain the painted primitives"
13218        );
13219
13220        let png = encode_png_rgba8(image.width(), image.height(), image.pixels());
13221        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
13222        path.push("../../target");
13223        let _ = std::fs::create_dir_all(&path);
13224        path.push("rounded_rect_primitives_capture.png");
13225        std::fs::write(&path, &png).expect("writing capture PNG should succeed");
13226        eprintln!("wrote capture PNG to {}", path.display());
13227    }
13228
13229    /// Diagnostic microbenchmark for text policy cache behavior. It measures CPU-side scene
13230    /// preparation through the real text engine and reports cache behavior across coverage,
13231    /// color, LCD, and unsafe-LCD fallback scenarios. Run with `--ignored --nocapture`.
13232    #[test]
13233    #[ignore = "diagnostic benchmark for text render policy cache and atlas behavior"]
13234    fn text_render_policy_cache_benchmark() {
13235        let handle = FontHandle::new(7101);
13236        let mut fonts = FontRegistry::new();
13237        fonts.insert(handle, load_test_font());
13238        let fonts = Arc::new(fonts);
13239        let images = Arc::new(ImageRegistry::new());
13240        let layouts = Arc::new(TextLayoutRegistry::default());
13241        let viewport = Size::new(640.0, 760.0);
13242
13243        let frame = |window_id: u64,
13244                     policy: TextRenderPolicy,
13245                     color: Color,
13246                     transform: Option<Transform>|
13247         -> SceneFrame {
13248            let mut scene = Scene::new();
13249            scene.push(SceneCommand::PushTextRenderPolicy { policy });
13250            if let Some(transform) = transform {
13251                scene.push(SceneCommand::PushTransform { transform });
13252            }
13253            for row in 0..44 {
13254                scene.push(SceneCommand::DrawText(TextRun {
13255                    rect: Rect::new(18.0, 12.0 + row as f32 * 16.0, 600.0, 17.0),
13256                    text: format!(
13257                        "Atlas policy benchmark row {row:02}: minimum ill glyphs 1234567890"
13258                    ),
13259                    style: TextStyle {
13260                        font: Some(handle),
13261                        font_size: 12.0,
13262                        line_height: 16.0,
13263                        color,
13264                        ..TextStyle::default()
13265                    },
13266                }));
13267            }
13268            if transform.is_some() {
13269                scene.push(SceneCommand::PopTransform);
13270            }
13271            scene.push(SceneCommand::PopTextRenderPolicy);
13272            SceneFrame {
13273                window_id: WindowId::new(window_id),
13274                viewport,
13275                surface_size: viewport,
13276                scale_factor: 1.0,
13277                dirty_regions: Vec::new(),
13278                layer_updates: Vec::new(),
13279                scene,
13280                font_registry: Arc::clone(&fonts),
13281                image_registry: Arc::clone(&images),
13282                text_layout_registry: Arc::clone(&layouts),
13283            }
13284        };
13285
13286        let scenarios = [
13287            (
13288                "grayscale-perceptual",
13289                frame(
13290                    7201,
13291                    TextRenderPolicy::new()
13292                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13293                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13294                    None,
13295                ),
13296            ),
13297            (
13298                "coverage-linear",
13299                frame(
13300                    7202,
13301                    TextRenderPolicy::new().with_coverage_policy(TextRenderCoveragePolicy::Linear),
13302                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13303                    None,
13304                ),
13305            ),
13306            (
13307                "coverage-boost",
13308                frame(
13309                    7203,
13310                    TextRenderPolicy::new()
13311                        .with_coverage_policy(TextRenderCoveragePolicy::CoverageBoost(0.55)),
13312                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13313                    None,
13314                ),
13315            ),
13316            (
13317                "coverage-gamma",
13318                frame(
13319                    7204,
13320                    TextRenderPolicy::new()
13321                        .with_coverage_policy(TextRenderCoveragePolicy::Gamma(1.8)),
13322                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13323                    None,
13324                ),
13325            ),
13326            (
13327                "color-churn-light",
13328                frame(
13329                    7205,
13330                    TextRenderPolicy::new()
13331                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13332                    Color::rgba(0.88, 0.90, 0.94, 1.0),
13333                    None,
13334                ),
13335            ),
13336            (
13337                "lcd-rgb",
13338                frame(
13339                    7206,
13340                    TextRenderPolicy::new()
13341                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
13342                        .with_subpixel_order(TextSubpixelOrder::Rgb)
13343                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13344                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13345                    None,
13346                ),
13347            ),
13348            (
13349                "grayscale-rotated",
13350                frame(
13351                    7207,
13352                    TextRenderPolicy::new()
13353                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13354                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13355                    Some(Transform::rotation(0.08)),
13356                ),
13357            ),
13358            (
13359                "unsafe-lcd-fallback",
13360                frame(
13361                    7208,
13362                    TextRenderPolicy::new()
13363                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
13364                        .with_subpixel_order(TextSubpixelOrder::Rgb)
13365                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13366                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13367                    Some(Transform::rotation(0.08)),
13368                ),
13369            ),
13370        ];
13371
13372        let mut text_engine = TextEngine::new().expect("text engine should initialize");
13373        println!("\n=== Text Render Policy Cache Benchmark ===");
13374        for (name, frame) in scenarios {
13375            let before = text_engine.glyph_cache_stats();
13376            let first_start = std::time::Instant::now();
13377            let vertices = build_vertices(&frame, &mut text_engine)
13378                .expect("benchmark frame should build")
13379                .len();
13380            let first_us = first_start.elapsed().as_secs_f64() * 1_000_000.0;
13381            let after_first = text_engine.glyph_cache_stats();
13382
13383            let warm_repeats = 12usize;
13384            let warm_start = std::time::Instant::now();
13385            for _ in 0..warm_repeats {
13386                let _ = build_vertices(&frame, &mut text_engine)
13387                    .expect("warm benchmark frame should build");
13388            }
13389            let warm_avg_us =
13390                warm_start.elapsed().as_secs_f64() * 1_000_000.0 / warm_repeats as f64;
13391            let after_warm = text_engine.glyph_cache_stats();
13392
13393            println!(
13394                "{name:22} first={first_us:8.1}us warm_avg={warm_avg_us:8.1}us vertices={vertices:5} entries={} (+{}) hits=+{} misses=+{} first_misses=+{}",
13395                after_warm.0,
13396                after_warm.0.saturating_sub(before.0),
13397                after_warm.1.saturating_sub(before.1),
13398                after_warm.2.saturating_sub(before.2),
13399                after_first.2.saturating_sub(before.2),
13400            );
13401        }
13402        println!("==========================================\n");
13403    }
13404
13405    /// Renders a body-text + small-label sample across DPR, light/dark surfaces, and coverage
13406    /// policies. The validation reports core stem luma plus an edge-coverage ratio instead of raw
13407    /// pixel diffs, because small-text quality changes are perceptual and do not track total
13408    /// changed-pixel percentages well.
13409    #[test]
13410    fn text_coverage_quality_matrix_capture() {
13411        let handle = FontHandle::new(7001);
13412        let mut fonts = FontRegistry::new();
13413        fonts.insert(handle, load_test_font());
13414        let fonts = Arc::new(fonts);
13415
13416        // Body paragraph + a couple of small UI labels.
13417        let lines: [(&str, f32, f32); 5] = [
13418            ("The quick brown fox jumps over the lazy dog.", 20.0, 16.0),
13419            ("Pack my box with five dozen liquor jugs.", 20.0, 44.0),
13420            (
13421                "Body text at a typical reading size, 1234567890.",
13422                16.0,
13423                72.0,
13424            ),
13425            ("Small UI label", 12.0, 98.0),
13426            ("settings  ·  profile  ·  sign out", 11.0, 118.0),
13427        ];
13428
13429        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13430        enum MatrixPolicy {
13431            Linear,
13432            Perceptual,
13433            LcdRgb,
13434        }
13435
13436        impl MatrixPolicy {
13437            fn name(self) -> &'static str {
13438                match self {
13439                    Self::Linear => "linear",
13440                    Self::Perceptual => "perceptual",
13441                    Self::LcdRgb => "lcd-rgb",
13442                }
13443            }
13444
13445            fn configure(self, renderer: &mut WgpuRenderer) {
13446                match self {
13447                    Self::Linear => {
13448                        renderer.set_text_render_mode(TextRenderMode::Grayscale);
13449                        renderer.set_text_subpixel_order(TextSubpixelOrder::None);
13450                        renderer.set_text_coverage_policy(TextCoveragePolicy::Linear);
13451                    }
13452                    Self::Perceptual => {
13453                        renderer.set_text_render_mode(TextRenderMode::Grayscale);
13454                        renderer.set_text_subpixel_order(TextSubpixelOrder::None);
13455                        renderer.set_text_coverage_policy(TextCoveragePolicy::Perceptual);
13456                    }
13457                    Self::LcdRgb => {
13458                        renderer.set_text_render_mode(TextRenderMode::LcdSubpixel);
13459                        renderer.set_text_subpixel_order(TextSubpixelOrder::Rgb);
13460                        renderer.set_text_coverage_policy(TextCoveragePolicy::Perceptual);
13461                    }
13462                }
13463            }
13464        }
13465
13466        let render_sample = |policy: MatrixPolicy, scale: f32, bg: Color, fg: Color| -> RgbaImage {
13467            let policy_id = match policy {
13468                MatrixPolicy::Linear => 1,
13469                MatrixPolicy::Perceptual => 2,
13470                MatrixPolicy::LcdRgb => 3,
13471            };
13472            let window_id = WindowId::new(7100 + policy_id + (scale * 10.0) as u64);
13473            let viewport = Size::new(420.0, 140.0);
13474            let mut scene = Scene::new();
13475            scene.push(SceneCommand::Clear(bg));
13476            for (text, size, y) in lines {
13477                scene.push(SceneCommand::DrawText(TextRun {
13478                    rect: Rect::new(12.0, y, 400.0, size + 8.0),
13479                    text: text.to_string(),
13480                    style: TextStyle {
13481                        font: Some(handle),
13482                        font_size: size,
13483                        line_height: size + 6.0,
13484                        color: fg,
13485                        ..TextStyle::default()
13486                    },
13487                }));
13488            }
13489            let frame = SceneFrame {
13490                window_id,
13491                viewport,
13492                surface_size: Size::new(viewport.width * scale, viewport.height * scale),
13493                scale_factor: scale,
13494                dirty_regions: Vec::new(),
13495                layer_updates: Vec::new(),
13496                scene,
13497                font_registry: Arc::clone(&fonts),
13498                image_registry: Arc::new(ImageRegistry::new()),
13499                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13500            };
13501            let mut renderer = WgpuRenderer::new();
13502            policy.configure(&mut renderer);
13503            renderer
13504                .render(&frame)
13505                .expect("headless text render should succeed");
13506            renderer
13507                .capture_last_frame_rgba(window_id)
13508                .expect("capture of rendered text frame should succeed")
13509        };
13510
13511        #[derive(Debug, Clone, Copy)]
13512        struct InkStats {
13513            mean_luma: f32,
13514            core_luma: f32,
13515            foreground_weight: f32,
13516            edge_ratio: f32,
13517            inked_pixels: u64,
13518        }
13519
13520        fn luma(rgb: [u8; 3]) -> f32 {
13521            0.2126 * rgb[0] as f32 + 0.7152 * rgb[1] as f32 + 0.0722 * rgb[2] as f32
13522        }
13523
13524        fn ink_stats(image: &RgbaImage, bg: [u8; 3], fg: [u8; 3], dark_text: bool) -> InkStats {
13525            let bg_luma = luma(bg);
13526            let fg_luma = luma(fg);
13527            let contrast = (fg_luma - bg_luma).abs().max(1.0);
13528            let mut lumas: Vec<f32> = Vec::new();
13529            let mut edge_pixels = 0u64;
13530            let mut core_pixels = 0u64;
13531            for px in image.pixels().chunks_exact(4) {
13532                let d = (px[0] as i32 - bg[0] as i32).abs()
13533                    + (px[1] as i32 - bg[1] as i32).abs()
13534                    + (px[2] as i32 - bg[2] as i32).abs();
13535                if d > 10 {
13536                    let pixel_luma = luma([px[0], px[1], px[2]]);
13537                    let coverage = ((pixel_luma - bg_luma).abs() / contrast).clamp(0.0, 1.0);
13538                    if coverage >= 0.85 {
13539                        core_pixels += 1;
13540                    } else if coverage >= 0.10 {
13541                        edge_pixels += 1;
13542                    }
13543                    lumas.push(pixel_luma);
13544                }
13545            }
13546            let count = lumas.len() as u64;
13547            if count == 0 {
13548                return InkStats {
13549                    mean_luma: 0.0,
13550                    core_luma: 0.0,
13551                    foreground_weight: 0.0,
13552                    edge_ratio: 0.0,
13553                    inked_pixels: 0,
13554                };
13555            }
13556            let mean = lumas.iter().sum::<f32>() / count as f32;
13557            if dark_text {
13558                lumas.sort_by(|a, b| a.partial_cmp(b).unwrap());
13559            } else {
13560                lumas.sort_by(|a, b| b.partial_cmp(a).unwrap());
13561            }
13562            let q = (lumas.len() / 4).max(1);
13563            let core = lumas[..q].iter().sum::<f32>() / q as f32;
13564            let foreground_weight = if dark_text {
13565                bg_luma - core
13566            } else {
13567                core - bg_luma
13568            };
13569            InkStats {
13570                mean_luma: mean,
13571                core_luma: core,
13572                foreground_weight,
13573                edge_ratio: edge_pixels as f32 / core_pixels.max(1) as f32,
13574                inked_pixels: count,
13575            }
13576        }
13577
13578        let light_bg = Color::rgba(0.98, 0.98, 0.99, 1.0);
13579        let dark_bg = Color::rgba(0.08, 0.09, 0.11, 1.0);
13580        let light_bg8 = [250u8, 250, 252];
13581        let dark_bg8 = [22u8, 24, 28];
13582        let light_fg = Color::rgba(0.05, 0.05, 0.06, 1.0);
13583        let dark_fg = Color::rgba(0.95, 0.95, 0.96, 1.0);
13584        let light_fg8 = [13u8, 13, 15];
13585        let dark_fg8 = [242u8, 242, 245];
13586        let policies = [
13587            MatrixPolicy::Linear,
13588            MatrixPolicy::Perceptual,
13589            MatrixPolicy::LcdRgb,
13590        ];
13591        let scales = [1.0f32, 1.5, 2.0];
13592        let mut write_dir = None;
13593        if std::env::var_os("SUI_TEXT_COVERAGE_WRITE_PNGS").is_some() {
13594            let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
13595            dir.push("../../target/text-coverage-matrix");
13596            std::fs::create_dir_all(&dir).expect("creating text coverage capture dir should work");
13597            write_dir = Some(dir);
13598        }
13599
13600        for scale in scales {
13601            let mut linear_light_weight = None;
13602            let mut perceptual_light_weight = None;
13603            let mut linear_dark_weight = None;
13604            let mut perceptual_dark_weight = None;
13605
13606            for policy in policies {
13607                let light = render_sample(policy, scale, light_bg, light_fg);
13608                let dark = render_sample(policy, scale, dark_bg, dark_fg);
13609                let light_stats = ink_stats(&light, light_bg8, light_fg8, true);
13610                let dark_stats = ink_stats(&dark, dark_bg8, dark_fg8, false);
13611                assert!(light_stats.inked_pixels > 200);
13612                assert!(dark_stats.inked_pixels > 200);
13613                assert!(light_stats.edge_ratio.is_finite());
13614                assert!(dark_stats.edge_ratio.is_finite());
13615
13616                eprintln!(
13617                    "[text-quality {policy} @{scale:.1}x light] mean={:.1} core={:.1} weight={:.1} edge/core={:.2} n={}",
13618                    light_stats.mean_luma,
13619                    light_stats.core_luma,
13620                    light_stats.foreground_weight,
13621                    light_stats.edge_ratio,
13622                    light_stats.inked_pixels,
13623                    policy = policy.name(),
13624                );
13625                eprintln!(
13626                    "[text-quality {policy} @{scale:.1}x dark] mean={:.1} core={:.1} weight={:.1} edge/core={:.2} n={}",
13627                    dark_stats.mean_luma,
13628                    dark_stats.core_luma,
13629                    dark_stats.foreground_weight,
13630                    dark_stats.edge_ratio,
13631                    dark_stats.inked_pixels,
13632                    policy = policy.name(),
13633                );
13634
13635                match policy {
13636                    MatrixPolicy::Linear => {
13637                        linear_light_weight = Some(light_stats.foreground_weight);
13638                        linear_dark_weight = Some(dark_stats.foreground_weight);
13639                    }
13640                    MatrixPolicy::Perceptual => {
13641                        perceptual_light_weight = Some(light_stats.foreground_weight);
13642                        perceptual_dark_weight = Some(dark_stats.foreground_weight);
13643                    }
13644                    MatrixPolicy::LcdRgb => {}
13645                }
13646
13647                if let Some(dir) = write_dir.as_ref() {
13648                    for (image, surface) in [(&light, "light"), (&dark, "dark")] {
13649                        let png = encode_png_rgba8(image.width(), image.height(), image.pixels());
13650                        let mut path = dir.clone();
13651                        path.push(format!("text-{surface}-{}-{scale:.1}x.png", policy.name()));
13652                        std::fs::write(&path, &png)
13653                            .expect("writing text capture PNG should succeed");
13654                    }
13655                }
13656            }
13657
13658            assert!(
13659                perceptual_light_weight.expect("perceptual light stats")
13660                    >= linear_light_weight.expect("linear light stats") * 0.98
13661            );
13662            assert!(
13663                perceptual_dark_weight.expect("perceptual dark stats")
13664                    >= linear_dark_weight.expect("linear dark stats") * 0.98
13665            );
13666        }
13667    }
13668}