Skip to main content

cranpose_render_wgpu/
render.rs

1use std::{
2    borrow::Cow,
3    cell::Cell,
4    hash::{Hash, Hasher},
5    rc::Rc,
6    sync::{Arc, mpsc},
7    time::Duration,
8};
9
10use bytemuck::{Pod, Zeroable};
11use cranpose_core::{
12    NodeId,
13    collections::{bounded_lru::BoundedLruCache, map::HashMap},
14    hash::default as default_hash,
15};
16use cranpose_render_common::{
17    geometry::blur_reach,
18    graph::{DrawCommandId, quad_bounds},
19    software_text_raster::{
20        SoftwareGlyphAtlasGlyph, SoftwareGlyphAtlasKey, SoftwareGlyphAtlasPlacement,
21        SoftwareGlyphAtlasRunGlyph, SoftwareGlyphRasterCache, SoftwareTextFontSet,
22        collect_solid_text_atlas_run, rasterize_annotated_text_region,
23    },
24    text_mask_gamma::TextLuminance,
25};
26use cranpose_ui_graphics::{
27    BlendMode, Color, ColorFilter, FRAGMENT_KIND_ARC, FRAGMENT_KIND_FILL, FRAGMENT_KIND_LINE,
28    FRAGMENT_KIND_STROKE, FRAGMENT_KIND_TRAPEZOID, FxHasher, ImageBitmap, ImageSampling, Point,
29    RecordLane, RecordSegment, Rect, RenderHash, TileMode,
30};
31use smallvec::SmallVec;
32use web_time::Instant;
33
34use crate::{
35    DebugCpuAllocationStats,
36    ablation::{Ablation, ShapeAblation},
37    arc_trig_fill::ArcTrigFill,
38    collect::LayerScene,
39    debug_toggles::DebugToggle,
40    draw_pass::{
41        PassSegment, PassTarget, ResolvedComposite, ResolvedCompositeKind, SourceContent,
42        TrackedPass,
43    },
44    effect_renderer::{CompositeSampleMode, EffectRenderer, RoundedCompositeMask},
45    fixed_pipeline::{FixedPipeline, FixedPipelineJob},
46    frame::{AdmissionGate, FrameExecutor, StageSideScratch},
47    frame_graph::{
48        BufferUpload, FrameCommandRecorder, FrameCommandStats, FrameTextureDescriptor,
49        FrameUploadAllocators, UniformUpload, UploadAllocatorId, UploadAllocatorSpec, UploadMode,
50        WgpuFrameGraph, WgpuFrameGraphExecutor,
51    },
52    frame_packet::{CancelReason, FramePacket, FrameSceneStorage, PresentOutcome, RenderReturns},
53    geometry::{
54        DevicePixelBounds, SegmentTransform, anchored_device_rect, axis_aligned_quad_rect,
55        canonicalize_device_coordinate, canonicalized_scaled_quad, offscreen_byte_size,
56        scaled_quad, snap_delta_for_anchor, snapped_anchor_device_origin, translate_quad,
57        translation_stable_anchored_device_pixel_bounds,
58    },
59    glyph_run::{RunGlyphBox, RunGlyphScratch, RunGlyphs},
60    glyph_run_arena::{GlyphRunArena, GlyphRunSpan},
61    gpu_stats::{self, gpu_stats_enabled},
62    idle_pool::FrameScratch,
63    layer_cache::LayerCache,
64    lazy_resource::Pending,
65    offscreen::{COMPOSITION_BYTES_PER_PIXEL, OffscreenTarget},
66    output_conversion::OutputConverter,
67    pipeline_compiler::{CompileLane, CompilerSend, PipelineCompilation, PipelineCompiler},
68    record_columns::record_vertex_layouts,
69    rect_to_quad,
70    rrect_shadow::{SHADOW_QUAD_CORNERS, ShadowInstance, create_rrect_shadow_pipeline},
71    run_store::{ArenaBinding, PlacementData, RunBufferMode, RunDrawCall, RunStore, StoredTables},
72    scene::{
73        CompositorScene, DrawOp, DrawOpKind, DrawnText, ImageDraw, RunDraw, ShadowDraw, SnapAnchor,
74        TextDraw,
75    },
76    shaders,
77    shape_pipelines::{PipelineDemand, ShapePipelineFactory, ShapePipelines},
78    shared_shader::{ShaderCode, SharedShader},
79};
80const MAX_SHADOW_SURFACE_CACHE_ITEMS: usize = 512;
81const MAX_TRANSPARENT_SOURCES: usize = 16;
82const MAX_SHADOW_SURFACE_CACHE_BYTES: u64 = 384 * 1024 * 1024;
83
84static SKIP_SHADOWS: DebugToggle = DebugToggle::new("CRANPOSE_SKIP_SHADOWS");
85
86fn skip_shadow_draws() -> bool {
87    SKIP_SHADOWS.flag()
88}
89const MAX_TEXT_IMAGE_CACHE_ITEMS: usize = 1024;
90const MAX_TEXT_GLYPH_MASK_CACHE_ITEMS: usize = 8192;
91const MAX_TEXT_GLYPH_ATLAS_ITEMS: usize = 8192;
92/// The fewest text runs the run cache holds. It holds twice the runs the
93/// last frame drew when that is more, so a frame never evicts runs the next
94/// one draws again; idle runs leave it after `TEXT_GLYPH_RUN_IDLE_FRAMES`.
95const MIN_TEXT_GLYPH_RUN_CACHE_ITEMS: usize = 1024;
96const MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS: usize = 1024;
97/// Frames a text run may go undrawn before its glyphs and quads are freed,
98/// on the CPU and in retained GPU buffers alike. Shorter than the shape
99/// store's span: a list scrolling at speed leaves several screens of text
100/// behind each second, which at 120 frames held 12 to 19 MB of GPU quads on
101/// a scrolling feed, and the CPU runs, bounded only by their count, held
102/// another 4.6 MB of placements and quads.
103const TEXT_GLYPH_RUN_IDLE_FRAMES: u64 = 30;
104/// Frames a retained run's quads stay on the GPU undrawn. Writing a run's
105/// quads again costs far less than laying its glyphs out, which the CPU run
106/// keeps for [`TEXT_GLYPH_RUN_IDLE_FRAMES`]. On the desktop gauntlet at tier
107/// 16, 270 retained runs drew each frame while 30 frames held 650 of them;
108/// 8 frames hold 400 and write 25 runs a frame again instead of 16.
109const TEXT_GLYPH_GPU_RUN_IDLE_FRAMES: u64 = 8;
110/// Text runs with at least this many glyphs keep their quads in retained GPU
111/// buffers and draw on their own; shorter ones are written into the frame's
112/// shared quads each frame, where consecutive runs share a draw.
113const RETAINED_TEXT_GLYPH_RUN_MIN_QUADS: usize = 64;
114
115const TEXT_GLYPH_ATLAS_MIN_SIZE: u32 = 512;
116const TEXT_GLYPH_ATLAS_MAX_SIZE: u32 = 4096;
117const _: () = assert!(TEXT_GLYPH_ATLAS_MAX_SIZE <= u16::MAX as u32);
118const TEXT_GLYPH_ATLAS_PADDING: u32 = 1;
119const MAX_TEXT_LINE_INDEX_CACHE_ITEMS: usize = 512;
120const MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER: usize = 2;
121
122const CACHE_MISS_WARMUP_FRAMES: u8 = 1;
123pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color {
124    r: cranpose_render_common::FRAME_CLEAR_COLOR[0] as f64,
125    g: cranpose_render_common::FRAME_CLEAR_COLOR[1] as f64,
126    b: cranpose_render_common::FRAME_CLEAR_COLOR[2] as f64,
127    a: cranpose_render_common::FRAME_CLEAR_COLOR[3] as f64,
128};
129const MAX_TEXTURE_CACHE_ITEMS: usize = 256;
130const MAX_IMAGE_TEXTURE_CACHE_BYTES: usize = 256 * 1024 * 1024;
131const MAX_EXTERNAL_TEXTURE_BINDINGS: usize = 8;
132
133const DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS: f64 = 4.0;
134
135fn wgpu_render_stage_telemetry_threshold_ms() -> Option<f64> {
136    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
137    *THRESHOLD_MS.get_or_init(|| {
138        let explicit =
139            crate::debug_toggles::debug_toggle("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY_MS")
140                .and_then(|value| value.parse::<f64>().ok())
141                .filter(|value| value.is_finite() && *value >= 0.0);
142        explicit.or_else(|| {
143            std::env::var_os("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY")
144                .is_some()
145                .then_some(DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS)
146        })
147    })
148}
149
150pub(crate) fn instant_ms(start: Instant, end: Instant) -> f64 {
151    end.duration_since(start).as_secs_f64() * 1000.0
152}
153
154pub(crate) fn should_log_wgpu_render_stage(start: Instant, end: Instant) -> Option<f64> {
155    let threshold_ms = wgpu_render_stage_telemetry_threshold_ms()?;
156    let total_ms = instant_ms(start, end);
157    (total_ms >= threshold_ms).then_some(total_ms)
158}
159
160pub static PRESENTED_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
161
162pub fn frames_presented() -> u64 {
163    PRESENTED_FRAMES.load(std::sync::atomic::Ordering::Relaxed)
164}
165
166fn text_atlas_fallback_diag_enabled() -> bool {
167    cranpose_core::env_flag!("CRANPOSE_TEXT_ATLAS_FALLBACK_DIAG")
168}
169
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171struct ShadowSurfaceCacheKey {
172    content_hash: u64,
173    pixel_size: [u32; 2],
174    root_scale_bits: u32,
175    blur_radius_bits: u32,
176}
177
178struct CachedShadowSurface {
179    target: Rc<OffscreenTarget>,
180    byte_size: u64,
181}
182
183type DeviceRect4 = (f32, f32, f32, f32);
184/// A rect of whole target pixels: x, y, width, height.
185pub(crate) type TargetRect = (u32, u32, u32, u32);
186
187/// The target pixels a clipped shape variant keeps of `placement`'s records
188/// under `viewport`, as a scissor that stands in for its clip test: every
189/// pixel whose centre, moved by the viewport's offset, lies inside the
190/// device clip, inclusive of its edges, as the shader compares them. `None`
191/// without a clip or under a turn, where the variant tests the clip itself.
192/// An empty clip keeps an empty scissor.
193pub(crate) fn clip_scissor(
194    placement: &crate::scene::Placement,
195    root_scale: f32,
196    viewport: ViewportUniformParams,
197) -> Option<TargetRect> {
198    if !viewport.transform.is_identity() {
199        return None;
200    }
201    let [x, y, width, height] = crate::run_store::device_clip(placement, root_scale)?;
202    let columns = kept_pixels(x, x + width, viewport.offset[0], viewport.width);
203    let rows = kept_pixels(y, y + height, viewport.offset[1], viewport.height);
204    Some((
205        columns.start,
206        rows.start,
207        columns.end - columns.start,
208        rows.end - rows.start,
209    ))
210}
211
212/// The pixels along one axis whose centre, moved by `offset`, lies within
213/// `low..=high`, within `0..extent`: stepped with the shader's own float
214/// sums so the edges fall where its comparisons put them.
215fn kept_pixels(low: f32, high: f32, offset: f32, extent: u32) -> std::ops::Range<u32> {
216    let centre = |pixel: u32| pixel as f32 + 0.5 + offset;
217    let guess = |edge: f32| (edge - offset - 0.5).ceil().clamp(0.0, extent as f32) as u32;
218    let mut start = guess(low);
219    while start > 0 && centre(start - 1) >= low {
220        start -= 1;
221    }
222    while start < extent && centre(start) < low {
223        start += 1;
224    }
225    let mut end = guess(high).max(start);
226    while end > start && centre(end - 1) > high {
227        end -= 1;
228    }
229    while end < extent && centre(end) <= high {
230        end += 1;
231    }
232    start..end
233}
234
235/// The pixels both scissors keep, `None` when they share none.
236pub(crate) fn intersect_target_rects(a: TargetRect, b: TargetRect) -> Option<TargetRect> {
237    let left = a.0.max(b.0);
238    let top = a.1.max(b.1);
239    let right = (a.0 + a.2).min(b.0 + b.2);
240    let bottom = (a.1 + a.3).min(b.1 + b.3);
241    (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
242}
243
244/// A draw's scissor cut down to the pixels its pass segment may touch;
245/// `None` when nothing of it remains.
246pub(crate) fn bounded_scissor(
247    scissor: (u32, u32, u32, u32),
248    bound: Option<(u32, u32, u32, u32)>,
249) -> Option<(u32, u32, u32, u32)> {
250    let Some((bx, by, bw, bh)) = bound else {
251        return Some(scissor);
252    };
253    let (x, y, width, height) = scissor;
254    let left = x.max(bx);
255    let top = y.max(by);
256    let right = (x + width).min(bx + bw);
257    let bottom = (y + height).min(by + bh);
258    (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
259}
260
261#[derive(Clone, Copy, Debug, PartialEq)]
262pub(crate) struct GlyphExtent {
263    left: f32,
264    top: f32,
265    right: f32,
266    bottom: f32,
267}
268
269impl GlyphExtent {
270    pub(crate) const EMPTY: Self = Self {
271        left: f32::INFINITY,
272        top: f32::INFINITY,
273        right: f32::NEG_INFINITY,
274        bottom: f32::NEG_INFINITY,
275    };
276
277    pub(crate) fn add(&mut self, rect: [f32; 4]) {
278        self.left = self.left.min(rect[0]);
279        self.top = self.top.min(rect[1]);
280        self.right = self.right.max(rect[2]);
281        self.bottom = self.bottom.max(rect[3]);
282    }
283}
284
285/// The scissor an unturned shared glyph run needs and the target pixels it
286/// touches. A run whose quads all lie inside `scissor` needs none of its own,
287/// which lets it share a draw with its neighbours. A turned run never needs
288/// one: its quads were cut to its clip before the turn.
289fn shared_glyph_clip(
290    extent: GlyphExtent,
291    scissor: TargetRect,
292    viewport: ViewportUniformParams,
293) -> (Option<TargetRect>, TargetRect) {
294    let GlyphExtent {
295        left,
296        top,
297        right,
298        bottom,
299    } = extent;
300    if left > right {
301        return (Some(scissor), scissor);
302    }
303    let left = (left - viewport.offset[0]).floor().max(0.0);
304    let top = (top - viewport.offset[1]).floor().max(0.0);
305    let right = (right - viewport.offset[0]).ceil();
306    let bottom = (bottom - viewport.offset[1]).ceil();
307    let (x, y, width, height) = scissor;
308    let inside = left >= x as f32
309        && top >= y as f32
310        && right <= (x + width) as f32
311        && bottom <= (y + height) as f32;
312    if !inside || right <= left || bottom <= top {
313        return (Some(scissor), scissor);
314    }
315    let bounds = (
316        left as u32,
317        top as u32,
318        (right - left) as u32,
319        (bottom - top) as u32,
320    );
321    (None, bounds)
322}
323
324fn intersect_device_rects(a: DeviceRect4, b: DeviceRect4) -> Option<DeviceRect4> {
325    let left = a.0.max(b.0);
326    let top = a.1.max(b.1);
327    let right = (a.0 + a.2).min(b.0 + b.2);
328    let bottom = (a.1 + a.3).min(b.1 + b.3);
329    (right > left && bottom > top).then_some((left, top, right - left, bottom - top))
330}
331
332pub(crate) fn anchored_rect_to_device(
333    rect: Rect,
334    snap_anchor: Option<SnapAnchor>,
335    root_scale: f32,
336) -> DeviceRect4 {
337    let device = anchored_device_rect(rect, snap_anchor, root_scale);
338    (device.x, device.y, device.width, device.height)
339}
340
341fn mask_rect(rect: Rect) -> [f32; 4] {
342    [rect.x, rect.y, rect.width, rect.height]
343}
344
345#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
346struct TextImageCacheKey(u64);
347
348struct CachedTextImage {
349    image: ImageBitmap,
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
353struct TextGlyphRunCacheKey(u64);
354
355#[derive(Clone, Copy)]
356struct CachedTextGlyphQuad {
357    x: i32,
358    y: i32,
359    width: usize,
360    height: usize,
361    color: (f32, f32, f32, f32),
362    uv: ImageUvRect,
363}
364
365struct CachedTextGlyphRun {
366    /// The run's glyphs that draw: zero-sized and transparent ones are left
367    /// out when the run is collected.
368    glyphs: RunGlyphs,
369    bounds: GlyphRunBounds,
370    /// Where each of `glyphs` sits in the atlas at `atlas_generation`. A
371    /// glyph's quad is derived from the two as it is drawn, so no glyph is
372    /// held twice.
373    atlas_entries: Option<Rc<[GlyphAtlasEntry]>>,
374    atlas_generation: u64,
375    /// The frame the run last drew in; see [`TEXT_GLYPH_RUN_IDLE_FRAMES`].
376    last_frame: Cell<u64>,
377}
378
379/// A cached run drawn as quads: its glyphs and their atlas entries, each
380/// quad derived as it is read.
381#[derive(Clone, Copy)]
382struct GlyphRunQuads<'a> {
383    glyphs: &'a RunGlyphs,
384    entries: &'a [GlyphAtlasEntry],
385    /// One atlas texel's share of the atlas side: see
386    /// [`TextGlyphAtlas::texel`].
387    texel: f32,
388    bounds: GlyphRunBounds,
389}
390
391/// The pixel box a run's drawing glyphs cover, from its raster origin.
392#[derive(Clone, Copy, Debug, PartialEq)]
393struct GlyphRunBounds {
394    min: [i32; 2],
395    max: [i32; 2],
396}
397
398impl GlyphRunBounds {
399    fn of(glyphs: impl IntoIterator<Item = SoftwareGlyphAtlasPlacement>) -> Self {
400        let mut bounds = Self {
401            min: [i32::MAX; 2],
402            max: [i32::MIN; 2],
403        };
404        for glyph in glyphs {
405            let width = i32::try_from(glyph.width).unwrap_or(i32::MAX);
406            let height = i32::try_from(glyph.height).unwrap_or(i32::MAX);
407            bounds.min = [bounds.min[0].min(glyph.x), bounds.min[1].min(glyph.y)];
408            bounds.max = [
409                bounds.max[0].max(glyph.x.saturating_add(width)),
410                bounds.max[1].max(glyph.y.saturating_add(height)),
411            ];
412        }
413        bounds
414    }
415
416    /// The box the glyphs cover from `origin`, as left, top, right, bottom.
417    fn at(self, origin: [f32; 2]) -> [f32; 4] {
418        [
419            origin[0] + self.min[0] as f32,
420            origin[1] + self.min[1] as f32,
421            origin[0] + self.max[0] as f32,
422            origin[1] + self.max[1] as f32,
423        ]
424    }
425
426    /// Whether every glyph of the run at `source_raster_rect` lies inside
427    /// what `viewport` shows of `clip`, so none needs its own test.
428    fn within_viewport(
429        self,
430        source_raster_rect: Rect,
431        clip: Option<Rect>,
432        viewport: ViewportUniformParams,
433        root_scale: f32,
434    ) -> bool {
435        if self.min[0] > self.max[0] || !root_scale.is_finite() || root_scale <= 0.0 {
436            return false;
437        }
438        let left = (source_raster_rect.x + self.min[0] as f32) / root_scale;
439        let top = (source_raster_rect.y + self.min[1] as f32) / root_scale;
440        let right = (source_raster_rect.x + self.max[0] as f32) / root_scale;
441        let bottom = (source_raster_rect.y + self.max[1] as f32) / root_scale;
442        let viewport_rect = viewport.scene_rect(root_scale);
443        let visible = match clip {
444            Some(clip) => clip.intersect(viewport_rect),
445            None => Some(viewport_rect),
446        };
447        visible
448            .is_some_and(|visible| visible.contains(left, top) && visible.contains(right, bottom))
449    }
450}
451
452/// A text's glyph run as the frame found it.
453struct TextGlyphRunLookup {
454    glyphs: RunGlyphs,
455    bounds: GlyphRunBounds,
456    /// Whether the run came from the cache rather than from this frame's
457    /// collection.
458    cached: bool,
459    /// The glyphs' atlas entries, while the atlas they were taken from holds.
460    entries: Option<Rc<[GlyphAtlasEntry]>>,
461}
462
463/// A text's glyph run and where it draws.
464struct TextGlyphRunDraw<'a> {
465    text_draw: &'a TextDraw,
466    raster_rect: Rect,
467    run_key: TextGlyphRunCacheKey,
468    run: TextGlyphRunLookup,
469}
470
471/// Logs why a text fell back from the glyph atlas, when
472/// `CRANPOSE_TEXT_ATLAS_FALLBACK_DIAG` asks.
473fn log_text_atlas_fallback(text_draw: &TextDraw) {
474    if !text_atlas_fallback_diag_enabled() {
475        return;
476    }
477    let preview: String = text_draw.text.string().text().chars().take(96).collect();
478    log::warn!(
479        "[text-atlas-fallback] node={:?} spans={} links={} text_len={} preview={:?} span_style={:?} paragraph_style={:?}",
480        text_draw.node_id,
481        text_draw.text.string().span_styles().len(),
482        text_draw.text.string().links().len(),
483        text_draw.text.string().text().len(),
484        preview,
485        text_draw.text_style.span_style,
486        text_draw.text_style.paragraph_style,
487    );
488}
489
490impl GlyphRunQuads<'_> {
491    fn len(&self) -> usize {
492        self.entries.len()
493    }
494
495    /// Each glyph as an instance at `origin`. Every glyph of a run draws: its
496    /// collection leaves out the zero-sized and the transparent ones.
497    fn instances_at(&self, origin: [f32; 2]) -> impl Iterator<Item = GlyphInstance> + '_ {
498        let texel = self.texel;
499        self.glyphs
500            .boxes()
501            .zip(self.entries)
502            .map(move |(glyph, entry)| {
503                let x0 = origin[0] + glyph.x as f32;
504                let y0 = origin[1] + glyph.y as f32;
505                let uv = glyph_atlas_uv_rect(*entry, texel);
506                GlyphInstance {
507                    rect: [
508                        x0,
509                        y0,
510                        x0 + f32::from(glyph.width),
511                        y0 + f32::from(glyph.height),
512                    ],
513                    uv: [uv.min[0], uv.min[1], uv.max[0], uv.max[1]],
514                    uv_bounds: uv.sample_bounds,
515                    color: [
516                        glyph.color.0.clamp(0.0, 1.0),
517                        glyph.color.1.clamp(0.0, 1.0),
518                        glyph.color.2.clamp(0.0, 1.0),
519                        glyph.color.3.clamp(0.0, 1.0),
520                    ],
521                }
522            })
523    }
524
525    fn iter(&self) -> impl Iterator<Item = CachedTextGlyphQuad> + '_ {
526        self.glyphs
527            .boxes()
528            .zip(self.entries)
529            .map(|(glyph, entry)| cached_text_glyph_quad(&glyph, *entry, self.texel))
530    }
531}
532
533struct CachedGpuTextGlyphRun {
534    span: GlyphRunSpan,
535    atlas_generation: u64,
536    /// The frame the run last drew in; a run idle for
537    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] gives its quads back.
538    last_frame: Cell<u64>,
539}
540
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
542struct TextLineIndexCacheKey(usize);
543
544struct CachedTextLineIndex {
545    text: std::sync::Weak<cranpose_ui::text::RenderString>,
546    len: usize,
547    starts: Rc<[usize]>,
548}
549
550struct TextLineIndexCache {
551    entries: BoundedLruCache<TextLineIndexCacheKey, CachedTextLineIndex>,
552}
553
554impl TextLineIndexCache {
555    fn new(capacity: usize) -> Self {
556        Self {
557            entries: BoundedLruCache::with_capacity_at_least_one(capacity),
558        }
559    }
560
561    fn line_starts(&mut self, text: &Arc<cranpose_ui::text::RenderString>) -> Rc<[usize]> {
562        let key = TextLineIndexCacheKey(Arc::as_ptr(text) as usize);
563        if let Some(cached) = self.entries.get(&key)
564            && cached.len == text.text().len()
565            && cached
566                .text
567                .upgrade()
568                .is_some_and(|cached_text| Arc::ptr_eq(&cached_text, text))
569        {
570            return cached.starts.clone();
571        }
572
573        let starts = Rc::<[usize]>::from(line_start_offsets(text.text()));
574        self.entries.put(
575            key,
576            CachedTextLineIndex {
577                text: Arc::downgrade(text),
578                len: text.text().len(),
579                starts: starts.clone(),
580            },
581        );
582        starts
583    }
584}
585
586#[derive(Default)]
587struct DeviceErrorSentry {
588    errors: std::sync::atomic::AtomicU64,
589    poisoned: std::sync::atomic::AtomicBool,
590}
591
592impl DeviceErrorSentry {
593    fn record(&self, error: &wgpu::Error) {
594        use std::sync::atomic::Ordering;
595        self.poisoned.store(true, Ordering::Release);
596        let count = self.errors.fetch_add(1, Ordering::Relaxed) + 1;
597        if count.is_power_of_two() {
598            log::error!("[gpu-device] uncaptured wgpu error #{count}: {error}");
599        }
600    }
601
602    fn take_poison(&self) -> bool {
603        self.poisoned
604            .swap(false, std::sync::atomic::Ordering::AcqRel)
605    }
606
607    fn error_count(&self) -> u64 {
608        self.errors.load(std::sync::atomic::Ordering::Relaxed)
609    }
610}
611
612fn is_blend_mode_supported(mode: BlendMode) -> bool {
613    matches!(
614        mode,
615        BlendMode::Src | BlendMode::SrcOver | BlendMode::DstOut
616    )
617}
618
619pub(crate) fn blend_state_for_mode(mode: BlendMode) -> wgpu::BlendState {
620    match mode {
621        BlendMode::Src => wgpu::BlendState::REPLACE,
622        BlendMode::DstOut => wgpu::BlendState {
623            color: wgpu::BlendComponent {
624                src_factor: wgpu::BlendFactor::Zero,
625                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
626                operation: wgpu::BlendOperation::Add,
627            },
628            alpha: wgpu::BlendComponent {
629                src_factor: wgpu::BlendFactor::Zero,
630                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
631                operation: wgpu::BlendOperation::Add,
632            },
633        },
634        _ => wgpu::BlendState::ALPHA_BLENDING,
635    }
636}
637
638pub(crate) fn supported_blend_mode(mode: BlendMode) -> BlendMode {
639    if is_blend_mode_supported(mode) {
640        return mode;
641    }
642
643    BlendMode::SrcOver
644}
645
646pub(crate) fn hash_f32_for_cache<H: Hasher>(value: f32, state: &mut H) {
647    value.to_bits().hash(state);
648}
649
650fn hash_text_raster_geometry_for_cache<H: Hasher>(
651    rect: Rect,
652    static_text_motion: bool,
653    state: &mut H,
654) {
655    hash_f32_for_cache(rect.width, state);
656    hash_f32_for_cache(rect.height, state);
657    static_text_motion.hash(state);
658    if !static_text_motion {
659        hash_f32_for_cache(rect.x.fract(), state);
660        hash_f32_for_cache(rect.y.fract(), state);
661    }
662}
663
664/// Hashes what a text draws apart from where and how large its rect is.
665fn hash_text_draw_for_cache<H: Hasher>(
666    text_draw: &TextDraw,
667    raster_rect: Rect,
668    text_scale: f32,
669    state: &mut H,
670) {
671    text_draw.text.render_hash().hash(state);
672    text_draw.style_hash.hash(state);
673    text_draw.color.render_hash().hash(state);
674    hash_text_gradient_phase_for_cache(text_draw, raster_rect, state);
675    text_draw.font_size.to_bits().hash(state);
676    text_scale.to_bits().hash(state);
677    text_draw.layout_options.hash(state);
678}
679
680pub(crate) fn hash_text_gradient_phase_for_cache<H: Hasher>(
681    text_draw: &TextDraw,
682    raster_rect: Rect,
683    state: &mut H,
684) {
685    if text_draw.text.gradient() {
686        for coordinate in [raster_rect.x, raster_rect.y] {
687            let phase = if coordinate >= 0.0 {
688                coordinate.rem_euclid(4.0)
689            } else {
690                coordinate
691            };
692            phase.to_bits().hash(state);
693        }
694    }
695}
696
697/// Where a text draws in the scene, snapped, and the scale its glyphs
698/// raster at; `None` for a text that draws nothing.
699pub(crate) fn text_logical_geometry_for_draw(
700    text_draw: &TextDraw,
701    root_scale: f32,
702) -> Option<(Rect, f32)> {
703    if text_draw.text.is_empty()
704        || text_draw.rect.width <= 0.0
705        || text_draw.rect.height <= 0.0
706        || !root_scale.is_finite()
707        || root_scale <= 0.0
708    {
709        return None;
710    }
711
712    let text_scale = text_draw.scale * root_scale;
713    if !text_scale.is_finite() || text_scale <= 0.0 {
714        return None;
715    }
716
717    let snap_delta = text_draw
718        .snap_anchor
719        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
720        .unwrap_or_default();
721    let logical_rect = text_draw.rect.translate(snap_delta.x, snap_delta.y);
722    Some((logical_rect, text_scale))
723}
724
725pub(crate) fn text_raster_geometry_for_draw(
726    text_draw: &TextDraw,
727    root_scale: f32,
728) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
729    text_logical_geometry_for_draw(text_draw, root_scale)
730        .map(|logical| text_raster_geometry_at(text_draw, logical, root_scale))
731}
732
733/// The raster geometry of a text whose logical geometry is
734/// `(logical_rect, text_scale)`: see [`text_raster_geometry_for_draw`].
735fn text_raster_geometry_at(
736    text_draw: &TextDraw,
737    (logical_rect, text_scale): (Rect, f32),
738    root_scale: f32,
739) -> (Rect, Rect, Option<Rect>, f32, bool) {
740    let static_text_motion = text_draw.text.static_motion();
741    let clip = text_draw.clip;
742    let mut raster_rect = Rect {
743        x: logical_rect.x * root_scale,
744        y: logical_rect.y * root_scale,
745        width: logical_rect.width * root_scale,
746        height: logical_rect.height * root_scale,
747    };
748    if text_draw.snap_anchor.is_some() {
749        raster_rect.x = canonicalize_device_coordinate(raster_rect.x);
750        raster_rect.y = canonicalize_device_coordinate(raster_rect.y);
751    }
752    if static_text_motion {
753        raster_rect.x = raster_rect.x.round();
754        raster_rect.y = raster_rect.y.round();
755    }
756    raster_rect.width = raster_rect.width.ceil().max(1.0);
757    raster_rect.height = raster_rect.height.ceil().max(1.0);
758    (
759        logical_rect,
760        raster_rect,
761        clip,
762        text_scale,
763        static_text_motion,
764    )
765}
766
767fn text_draw_is_visible_in_viewport(
768    logical_rect: Rect,
769    clip: Option<Rect>,
770    viewport: ViewportUniformParams,
771    root_scale: f32,
772) -> bool {
773    draw_rect_is_visible_in_viewport(logical_rect, clip, viewport, root_scale)
774}
775
776fn expand_rect(rect: Rect, margin_x: f32, margin_y: f32) -> Rect {
777    Rect {
778        x: rect.x - margin_x,
779        y: rect.y - margin_y,
780        width: rect.width + margin_x * 2.0,
781        height: rect.height + margin_y * 2.0,
782    }
783}
784
785fn draw_rect_is_visible_in_viewport(
786    rect: Rect,
787    clip: Option<Rect>,
788    viewport: ViewportUniformParams,
789    root_scale: f32,
790) -> bool {
791    if !root_scale.is_finite() || root_scale <= 0.0 {
792        return false;
793    }
794    rect_is_visible_in_rect(rect, clip, viewport.scene_rect(root_scale))
795}
796
797fn rect_is_visible_in_rect(rect: Rect, clip: Option<Rect>, viewport_rect: Rect) -> bool {
798    let visible_rect = match clip {
799        Some(clip) => clip.intersect(viewport_rect),
800        None => Some(viewport_rect),
801    };
802    visible_rect.is_some_and(|visible| rect.intersect(visible).is_some())
803}
804
805fn snapped_quad_bounds(quad: [[f32; 2]; 4], anchor: Option<SnapAnchor>, root_scale: f32) -> Rect {
806    let snap_delta = anchor
807        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
808        .unwrap_or_default();
809    quad_bounds(translate_quad(quad, snap_delta))
810}
811
812/// The logical rect a draw may touch: its snapped bounds within its clip,
813/// `None` when the clip leaves nothing.
814fn clipped_bounds(rect: Rect, clip: Option<Rect>) -> Option<Rect> {
815    match clip {
816        Some(clip) => rect.intersect(clip),
817        None => Some(rect),
818    }
819}
820
821pub(crate) fn text_draw_bounds(text: &TextDraw, root_scale: f32) -> Option<Rect> {
822    text_logical_geometry_for_draw(text, root_scale)
823        .and_then(|(logical_rect, _)| clipped_bounds(logical_rect, text.clip))
824}
825
826pub(crate) fn image_draw_bounds(image: &ImageDraw, root_scale: f32) -> Option<Rect> {
827    clipped_bounds(
828        snapped_quad_bounds(image.quad, image.snap_anchor, root_scale),
829        image.clip,
830    )
831}
832
833pub(crate) fn run_draw_bounds(run: &RunDraw, root_scale: f32) -> Option<Rect> {
834    let snap_delta = run
835        .placement
836        .snap_anchor
837        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
838        .unwrap_or_default();
839    clipped_bounds(
840        run.bounds.translate(snap_delta.x, snap_delta.y),
841        run.placement.clip,
842    )
843}
844
845/// The logical geometry of `text` (see [`text_logical_geometry_for_draw`])
846/// when it draws any pixel inside `viewport_rect`.
847pub(crate) fn text_draw_geometry_in_rect(
848    text: &TextDraw,
849    viewport_rect: Rect,
850    root_scale: f32,
851) -> Option<(Rect, f32)> {
852    text_logical_geometry_for_draw(text, root_scale).filter(|(logical_rect, _)| {
853        clipped_bounds(*logical_rect, text.clip)
854            .is_some_and(|bounds| bounds.intersect(viewport_rect).is_some())
855    })
856}
857
858fn cached_text_glyph_quad(
859    glyph: &RunGlyphBox,
860    entry: GlyphAtlasEntry,
861    texel: f32,
862) -> CachedTextGlyphQuad {
863    CachedTextGlyphQuad {
864        x: glyph.x,
865        y: glyph.y,
866        width: usize::from(glyph.width),
867        height: usize::from(glyph.height),
868        color: (
869            glyph.color.0.clamp(0.0, 1.0),
870            glyph.color.1.clamp(0.0, 1.0),
871            glyph.color.2.clamp(0.0, 1.0),
872            glyph.color.3.clamp(0.0, 1.0),
873        ),
874        uv: glyph_atlas_uv_rect(entry, texel),
875    }
876}
877
878/// `quad` at `source_raster_rect`'s origin. `None` for a quad that draws
879/// nothing.
880fn cached_text_glyph_instance(
881    source_raster_rect: Rect,
882    quad: &CachedTextGlyphQuad,
883) -> Option<GlyphInstance> {
884    if quad.width == 0 || quad.height == 0 || quad.color.3 <= 0.0 {
885        return None;
886    }
887    let x0 = source_raster_rect.x + quad.x as f32;
888    let y0 = source_raster_rect.y + quad.y as f32;
889    Some(GlyphInstance {
890        rect: [x0, y0, x0 + quad.width as f32, y0 + quad.height as f32],
891        uv: [
892            quad.uv.min[0],
893            quad.uv.min[1],
894            quad.uv.max[0],
895            quad.uv.max[1],
896        ],
897        uv_bounds: quad.uv.sample_bounds,
898        color: [quad.color.0, quad.color.1, quad.color.2, quad.color.3],
899    })
900}
901
902fn cached_text_glyph_quad_logical_rect(
903    source_raster_rect: Rect,
904    quad: &CachedTextGlyphQuad,
905    root_scale: f32,
906) -> Option<Rect> {
907    if !root_scale.is_finite() || root_scale <= 0.0 {
908        return None;
909    }
910    Some(Rect {
911        x: (source_raster_rect.x + quad.x as f32) / root_scale,
912        y: (source_raster_rect.y + quad.y as f32) / root_scale,
913        width: quad.width as f32 / root_scale,
914        height: quad.height as f32 / root_scale,
915    })
916}
917
918fn cached_text_glyph_quad_is_visible_in_viewport(
919    source_raster_rect: Rect,
920    quad: &CachedTextGlyphQuad,
921    clip: Option<Rect>,
922    viewport: ViewportUniformParams,
923    root_scale: f32,
924) -> bool {
925    cached_text_glyph_quad_logical_rect(source_raster_rect, quad, root_scale)
926        .is_some_and(|rect| draw_rect_is_visible_in_viewport(rect, clip, viewport, root_scale))
927}
928
929pub(crate) fn hash_device_offset<H: Hasher>(
930    value: f32,
931    origin: f32,
932    root_scale: f32,
933    state: &mut H,
934) {
935    hash_f32_for_cache((value - origin) * root_scale, state);
936}
937
938pub(crate) fn hash_device_rect<H: Hasher>(
939    rect: Rect,
940    origin_x: f32,
941    origin_y: f32,
942    root_scale: f32,
943    state: &mut H,
944) {
945    hash_device_offset(rect.x, origin_x, root_scale, state);
946    hash_device_offset(rect.y, origin_y, root_scale, state);
947    hash_device_offset(rect.width, 0.0, root_scale, state);
948    hash_device_offset(rect.height, 0.0, root_scale, state);
949}
950
951/// Hashes the rect `placement` is clipped to, `clip`, and its rounding, in
952/// device pixels from `origin`.
953fn hash_placement_clips<H: Hasher>(
954    placement: &crate::scene::Placement,
955    clip: Option<Rect>,
956    (origin_x, origin_y): (f32, f32),
957    root_scale: f32,
958    state: &mut H,
959) {
960    let rounding = placement.rounding;
961    for (rect, radius) in [
962        (clip, 0.0),
963        (
964            rounding.map(|rounding| rounding.rect),
965            rounding.map_or(0.0, |rounding| rounding.radius),
966        ),
967    ] {
968        rect.is_some().hash(state);
969        if let Some(rect) = rect {
970            let [x, y, width, height] =
971                crate::run_store::placement_device_rect(placement, rect, root_scale);
972            for value in [
973                x - origin_x,
974                y - origin_y,
975                width,
976                height,
977                radius * root_scale,
978            ] {
979                hash_f32_for_cache(value, state);
980            }
981        }
982    }
983}
984
985pub(crate) fn hash_run_item_with_clip<H: Hasher>(
986    run: &RunDraw,
987    clip: Option<Rect>,
988    origin_x: f32,
989    origin_y: f32,
990    root_scale: f32,
991    state: &mut H,
992) {
993    let tables = run.tables();
994    tables.fingerprint().hash(state);
995    run.segments.start.hash(state);
996    run.segments.end.hash(state);
997    let placement = &run.placement;
998    let snap = placement
999        .snap_anchor
1000        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
1001        .unwrap_or_default();
1002    let offset = Point::new(placement.offset.x + snap.x, placement.offset.y + snap.y);
1003    let canonicalize = placement.snap_anchor.is_some();
1004    canonicalize.hash(state);
1005    for segment in &tables.segments[run.segments.start as usize..run.segments.end as usize] {
1006        if segment.lane != RecordLane::Shapes {
1007            continue;
1008        }
1009        let exact_placement =
1010            !canonicalize || segment.kinds & ((1u8 << FRAGMENT_KIND_ARC) | LINE_KINDS) != 0;
1011        exact_placement.hash(state);
1012        if exact_placement {
1013            for value in [offset.x, offset.y, origin_x, origin_y, root_scale] {
1014                hash_f32_for_cache(value, state);
1015            }
1016            continue;
1017        }
1018        for index in segment.start..segment.start + segment.count {
1019            let record = tables
1020                .shapes
1021                .get(index as usize)
1022                .expect("shape segment record");
1023            let half_width = if record.is_stroked() {
1024                record.stroke_width * 0.5
1025            } else {
1026                0.0
1027            };
1028            let [left, top, right, bottom] = crate::run_geometry::device_shape_edges(
1029                record.rect,
1030                half_width,
1031                offset,
1032                root_scale,
1033                canonicalize,
1034            );
1035            for value in [left - origin_x, top - origin_y, right - left, bottom - top] {
1036                hash_f32_for_cache(value, state);
1037            }
1038        }
1039    }
1040    hash_placement_clips(placement, clip, (origin_x, origin_y), root_scale, state);
1041    if tables.segments[run.segments.start as usize..run.segments.end as usize]
1042        .iter()
1043        .any(|segment| segment.gradient || segment.vertex_gradient)
1044    {
1045        let dither = placement
1046            .snap_anchor
1047            .map(|anchor| snapped_anchor_device_origin(anchor, root_scale))
1048            .unwrap_or_default();
1049        hash_f32_for_cache(dither.x - origin_x, state);
1050        hash_f32_for_cache(dither.y - origin_y, state);
1051    }
1052    hash_f32_for_cache(placement.alpha, state);
1053    match &placement.color_filter {
1054        Some(filter) => {
1055            1u8.hash(state);
1056            filter.render_hash().hash(state);
1057        }
1058        None => 0u8.hash(state),
1059    }
1060}
1061
1062pub(crate) fn shadow_content_hash(shadow: &ShadowDraw, root_scale: f32) -> u64 {
1063    let mut hasher = FxHasher::default();
1064    let origin = shape_shadow_bounds(shadow).unwrap_or(Rect {
1065        x: 0.0,
1066        y: 0.0,
1067        width: 0.0,
1068        height: 0.0,
1069    });
1070    let device = anchored_device_rect(
1071        origin,
1072        shadow
1073            .shapes
1074            .as_ref()
1075            .and_then(|run| run.placement.snap_anchor),
1076        root_scale,
1077    );
1078    for run in shadow.shapes.iter().chain(&shadow.post_blur_cutouts) {
1079        hash_run_item_with_clip(
1080            run,
1081            run.placement.clip,
1082            device.x.floor(),
1083            device.y.floor(),
1084            root_scale,
1085            &mut hasher,
1086        );
1087    }
1088    hasher.finish()
1089}
1090
1091fn shape_shadow_surface_cache_key(
1092    shadow: &ShadowDraw,
1093    device_bounds: DevicePixelBounds,
1094    pixel_radius: f32,
1095    root_scale: f32,
1096) -> Option<ShadowSurfaceCacheKey> {
1097    (root_scale.is_finite() && root_scale > 0.0).then(|| ShadowSurfaceCacheKey {
1098        content_hash: shadow_content_hash(shadow, root_scale),
1099        pixel_size: [device_bounds.width, device_bounds.height],
1100        root_scale_bits: root_scale.to_bits(),
1101        blur_radius_bits: pixel_radius.to_bits(),
1102    })
1103}
1104
1105fn shape_shadow_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1106    shadow.shapes.as_ref().map(|run| run.bounds)
1107}
1108
1109pub(crate) fn shadow_draw_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1110    shape_shadow_bounds(shadow)
1111        .into_iter()
1112        .chain(shadow.texts.iter().map(|text| text.rect))
1113        .reduce(|a, b| Rect {
1114            x: a.x.min(b.x),
1115            y: a.y.min(b.y),
1116            width: (a.x + a.width).max(b.x + b.width) - a.x.min(b.x),
1117            height: (a.y + a.height).max(b.y + b.height) - a.y.min(b.y),
1118        })
1119}
1120
1121/// The shape shader's source for `mode`, built when its module is parsed.
1122fn shape_shader_code(mode: RunBufferMode) -> ShaderCode {
1123    if mode.trig_fill {
1124        ShaderCode::wgsl(|| Cow::Owned(shaders::filling_shape_shader()))
1125    } else if mode.storage {
1126        ShaderCode::wgsl(|| Cow::Owned(shaders::storage_shape_shader()))
1127    } else {
1128        shaders::SHAPE
1129    }
1130}
1131
1132/// The vertex entry point of every fullscreen strip.
1133pub(crate) const FULLSCREEN_VS: &str = "fullscreen_vs";
1134
1135/// A pipeline that draws one full-screen triangle strip from `fullscreen_vs`
1136/// into a single color target, the shape every effect and composite pass
1137/// shares; `constants` fixes the shader's override constants.
1138#[expect(clippy::too_many_arguments)]
1139pub(crate) fn create_fullscreen_strip_pipeline(
1140    device: &wgpu::Device,
1141    cache: Option<&wgpu::PipelineCache>,
1142    log_label: &str,
1143    label: &'static str,
1144    layout: &wgpu::PipelineLayout,
1145    (vertex_module, fragment_module): (&wgpu::ShaderModule, &wgpu::ShaderModule),
1146    (vertex_entry, fragment_entry): (&'static str, &'static str),
1147    constants: &[(&str, f64)],
1148    (target, depth_stencil): (wgpu::ColorTargetState, Option<wgpu::DepthStencilState>),
1149) -> wgpu::RenderPipeline {
1150    create_render_pipeline_logged(
1151        device,
1152        cache,
1153        log_label,
1154        wgpu::RenderPipelineDescriptor {
1155            label: Some(label),
1156            layout: Some(layout),
1157            vertex: wgpu::VertexState {
1158                module: vertex_module,
1159                entry_point: Some(vertex_entry),
1160                buffers: &[],
1161                compilation_options: wgpu::PipelineCompilationOptions {
1162                    constants,
1163                    ..wgpu::PipelineCompilationOptions::default()
1164                },
1165            },
1166            fragment: Some(wgpu::FragmentState {
1167                module: fragment_module,
1168                entry_point: Some(fragment_entry),
1169                targets: &[Some(target)],
1170                compilation_options: wgpu::PipelineCompilationOptions {
1171                    constants,
1172                    ..wgpu::PipelineCompilationOptions::default()
1173                },
1174            }),
1175            primitive: wgpu::PrimitiveState {
1176                topology: wgpu::PrimitiveTopology::TriangleStrip,
1177                strip_index_format: None,
1178                front_face: wgpu::FrontFace::Ccw,
1179                cull_mode: None,
1180                ..Default::default()
1181            },
1182            depth_stencil,
1183            multisample: wgpu::MultisampleState::default(),
1184            multiview_mask: None,
1185            cache: None,
1186        },
1187    )
1188}
1189
1190pub(crate) fn create_render_pipeline_logged<'a>(
1191    device: &wgpu::Device,
1192    cache: Option<&'a wgpu::PipelineCache>,
1193    tag: &str,
1194    mut descriptor: wgpu::RenderPipelineDescriptor<'a>,
1195) -> wgpu::RenderPipeline {
1196    descriptor.cache = cache;
1197    build_pipeline_logged(tag, || device.create_render_pipeline(&descriptor))
1198}
1199
1200pub(crate) fn build_pipeline_logged<T>(tag: &str, build: impl FnOnce() -> T) -> T {
1201    let started = Instant::now();
1202    let pipeline = build();
1203    log::info!(
1204        "[pipeline-create] {tag} {:.1}ms on {}",
1205        instant_ms(started, Instant::now()),
1206        std::thread::current().name().unwrap_or("unnamed thread"),
1207    );
1208    crate::thread_state::with(|state| {
1209        if state.off_frame_builds.get() {
1210            PIPELINES_CREATED_OFF_FRAME.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1211        } else {
1212            PIPELINES_CREATED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1213            state.thread_builds.set(state.thread_builds.get() + 1);
1214        }
1215    });
1216    #[cfg(not(target_arch = "wasm32"))]
1217    crate::pipeline_disk_cache::note_change();
1218    pipeline
1219}
1220
1221/// Pipelines this process has built on a thread that draws.
1222///
1223/// A build runs the backend's shader compiler, and whoever asks for one while
1224/// drawing waits for it there. A count that grows across an interaction names
1225/// work a person waited on, whatever the driver's own caches made a compile
1226/// cost on this machine. Builds handed to [`crate::pipeline_compiler`] are
1227/// counted apart, by [`pipelines_created_off_frame`]: they cost a frame
1228/// nothing.
1229static PIPELINES_CREATED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1230static PIPELINES_CREATED_OFF_FRAME: std::sync::atomic::AtomicU64 =
1231    std::sync::atomic::AtomicU64::new(0);
1232
1233/// The pipelines this thread has built while drawing: a frame that drew
1234/// with this unchanged built nothing itself.
1235#[cfg(not(target_arch = "wasm32"))]
1236fn thread_builds() -> u64 {
1237    crate::thread_state::with(|state| state.thread_builds.get())
1238}
1239
1240/// Declares that pipelines built on this thread are built away from any
1241/// frame. The compiler thread says so once, when it starts.
1242#[cfg(not(target_arch = "wasm32"))]
1243pub(crate) fn mark_thread_off_frame() {
1244    crate::thread_state::with(|state| state.off_frame_builds.set(true));
1245}
1246
1247pub fn pipelines_created() -> u64 {
1248    PIPELINES_CREATED.load(std::sync::atomic::Ordering::Relaxed)
1249}
1250
1251/// Pipelines built away from every frame, on the compiler thread.
1252pub fn pipelines_created_off_frame() -> u64 {
1253    PIPELINES_CREATED_OFF_FRAME.load(std::sync::atomic::Ordering::Relaxed)
1254}
1255
1256#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1257#[repr(u8)]
1258pub(crate) enum RunTier {
1259    Store = 0,
1260    Arena = 1,
1261    Either = 2,
1262}
1263
1264#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1265pub(crate) struct ShapeVariant {
1266    kinds: u8,
1267    brush: Option<u8>,
1268    solid: bool,
1269    /// How its records meet their placements' clips. A rounded clip gives
1270    /// every fragment its coverage, on the general entry points.
1271    clip: SegmentClip,
1272    interior: bool,
1273    dither: bool,
1274    ablation: ShapeAblation,
1275}
1276
1277const FLAT_FILL_ENTRIES: [[(&str, &str); 2]; 2] = [
1278    [
1279        ("vs_record_plain_fill", "fs_plain_fill"),
1280        ("vs_record_dithered_fill", "fs_dithered_fill"),
1281    ],
1282    [
1283        ("vs_record_clipped_fill", "fs_clipped_fill"),
1284        ("vs_record_solid", "fs_solid"),
1285    ],
1286];
1287
1288/// The entry points of a variant that draws slices of path fills alone and
1289/// flat: a solid brush, and a gradient between two stops from the vertices.
1290const SLICE_ENTRIES: [(&str, &str); 2] = [
1291    ("vs_record_slice", "fs_slice"),
1292    ("vs_record_gradient_slice", "fs_gradient_slice"),
1293];
1294
1295const ALL_SHAPE_KINDS: u8 =
1296    (1 << FRAGMENT_KIND_FILL) | (1 << FRAGMENT_KIND_STROKE) | (1 << FRAGMENT_KIND_ARC) | LINE_KINDS;
1297/// The kinds the shader draws from line records: segments, and slices of
1298/// path fills. A variant compiles in the code of only those it draws.
1299const LINE_KINDS: u8 = (1 << FRAGMENT_KIND_LINE) | TRAPEZOID_KIND;
1300const TRAPEZOID_KIND: u8 = 1 << FRAGMENT_KIND_TRAPEZOID;
1301
1302fn variant_kinds(kinds: u8) -> u8 {
1303    if kinds.count_ones() <= 1 {
1304        kinds
1305    } else {
1306        (ALL_SHAPE_KINDS & !LINE_KINDS) | (kinds & LINE_KINDS)
1307    }
1308}
1309
1310impl ShapeVariant {
1311    /// Every kind but slices of path fills, which only a segment holding
1312    /// them compiles in.
1313    const GENERAL: Self = Self {
1314        kinds: ALL_SHAPE_KINDS & !TRAPEZOID_KIND,
1315        brush: None,
1316        solid: false,
1317        clip: SegmentClip::Tested,
1318        interior: true,
1319        dither: false,
1320        ablation: ShapeAblation {
1321            material: false,
1322            fill: false,
1323        },
1324    };
1325
1326    /// The variant `segment` draws with. `vertex_gradients` says a rect
1327    /// fill may take its gradient from its vertices here; a segment of
1328    /// slices of path fills may wherever it is drawn `flat`. Under a rounded
1329    /// clip the variant keeps the general entry points, which carry the
1330    /// clip's radius to the fragment, but compiles in only the segment's
1331    /// kinds and brush: the general program with every kind and brush is
1332    /// twice the code (Mali-G76: 108-115 ms to compile or link, the
1333    /// specialized ones 22-62).
1334    pub(crate) fn of_segment(
1335        segment: &RecordSegment,
1336        clip: SegmentClip,
1337        ablation: ShapeAblation,
1338        laid: bool,
1339        (flat, vertex_gradients): (bool, bool),
1340    ) -> Self {
1341        if !shape_variants_enabled() {
1342            return Self {
1343                kinds: Self::GENERAL.kinds | (segment.kinds & TRAPEZOID_KIND),
1344                ablation,
1345                ..Self::GENERAL
1346            }
1347            .clipped_by(clip);
1348        }
1349        let vertex_gradients = if segment.kinds == TRAPEZOID_KIND {
1350            flat
1351        } else {
1352            vertex_gradients
1353        };
1354        let gradient = segment.gradient || (segment.vertex_gradient && !vertex_gradients);
1355        Self {
1356            kinds: variant_kinds(segment.kinds),
1357            brush: gradient
1358                .then(|| segment.uniform_brush())
1359                .flatten()
1360                .map(|brush| brush as u8),
1361            solid: !gradient,
1362            clip,
1363            // A rounded clip's corners are not opaque: no interior path.
1364            interior: clip != SegmentClip::Rounded
1365                && gradient
1366                && segment.interiors
1367                && !(laid && segment.occluders && !segment.bare_interiors),
1368            dither: segment.vertex_gradient && vertex_gradients,
1369            ablation,
1370        }
1371    }
1372
1373    /// The one kind the variant draws, as the shader's packed kind names
1374    /// it: a slice of a path fill is a line record.
1375    fn kind(self) -> Option<u8> {
1376        (self.kinds.count_ones() == 1).then(|| match self.kinds.trailing_zeros() {
1377            FRAGMENT_KIND_TRAPEZOID => FRAGMENT_KIND_LINE as u8,
1378            kind => kind as u8,
1379        })
1380    }
1381
1382    /// The vertex and fragment entry points of this variant, for records
1383    /// drawn `flat` (none of them turned).
1384    fn entries(self, flat: bool) -> (&'static str, &'static str) {
1385        let fill = self.kind() == Some(FRAGMENT_KIND_FILL as u8);
1386        if self.rounded() {
1387            ("vs_record", "fs_main")
1388        } else if self.solid && flat && self.kinds == TRAPEZOID_KIND {
1389            SLICE_ENTRIES[usize::from(self.dither)]
1390        } else if self.solid && fill && flat {
1391            FLAT_FILL_ENTRIES[usize::from(self.clip == SegmentClip::Tested)]
1392                [usize::from(self.dither)]
1393        } else if self.solid {
1394            ("vs_record_solid", "fs_solid")
1395        } else if fill && !self.ablation.material {
1396            ("vs_record_gradient_fill", "fs_gradient_fill")
1397        } else {
1398            ("vs_record", "fs_main")
1399        }
1400    }
1401
1402    fn general(self) -> Self {
1403        Self {
1404            kinds: (ALL_SHAPE_KINDS & !LINE_KINDS) | (self.kinds & LINE_KINDS),
1405            ablation: self.ablation,
1406            ..Self::GENERAL
1407        }
1408        .clipped_by(self.clip)
1409    }
1410
1411    /// The variant, keeping the rounded clip `clip` names: the general
1412    /// variant tests every rect clip, but no fallback may drop a rounding.
1413    fn clipped_by(self, clip: SegmentClip) -> Self {
1414        if clip == SegmentClip::Rounded {
1415            Self { clip, ..self }
1416        } else {
1417            self
1418        }
1419    }
1420
1421    fn rounded(self) -> bool {
1422        self.clip == SegmentClip::Rounded
1423    }
1424
1425    fn joined(self) -> Self {
1426        if self.solid {
1427            Self {
1428                dither: true,
1429                ..self
1430            }
1431        } else {
1432            Self {
1433                interior: true,
1434                ..self
1435            }
1436        }
1437    }
1438}
1439
1440/// How a segment's draw meets its placement's clip: a scissor or no clip
1441/// leaves the shader nothing to test, a rect clip off the scissor's grid is
1442/// tested per fragment, and a rounded clip gives every fragment coverage.
1443#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1444pub(crate) enum SegmentClip {
1445    Untested,
1446    Tested,
1447    Rounded,
1448}
1449
1450impl SegmentClip {
1451    /// The clip a draw under `placement` tests, given whether its rect clip
1452    /// became the draw's scissor.
1453    pub(crate) fn of(placement: &crate::scene::Placement, scissored: bool) -> Self {
1454        if placement.clip_rounded() {
1455            Self::Rounded
1456        } else if placement.clip.is_some() && !scissored {
1457            Self::Tested
1458        } else {
1459            Self::Untested
1460        }
1461    }
1462}
1463
1464static SHAPE_VARIANTS: DebugToggle = DebugToggle::new("CRANPOSE_SHAPE_VARIANTS");
1465
1466fn shape_variants_enabled() -> bool {
1467    !SHAPE_VARIANTS.equals("0")
1468}
1469
1470/// What every draw of one pass shares: its target's size and whether the
1471/// pass has a depth buffer its opaque interiors fill first.
1472#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1473pub(crate) struct PassFrame {
1474    pub(crate) size: (u32, u32),
1475    pub(crate) depth: bool,
1476}
1477
1478impl PassFrame {
1479    /// The scissor a draw bounded by `scissor`, or by nothing, sets.
1480    pub(crate) fn scissor(self, scissor: Option<(u32, u32, u32, u32)>) -> (u32, u32, u32, u32) {
1481        scissor.unwrap_or((0, 0, self.size.0, self.size.1))
1482    }
1483}
1484
1485/// Which of a pass's two stages a shape draw records: the front-to-back
1486/// opaque interiors, or the paint in draw order.
1487#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1488pub(crate) enum RunStage {
1489    Interiors,
1490    Paint,
1491}
1492
1493/// The depth buffer of a pass that lays opaque interiors down first.
1494pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
1495
1496/// How a pipeline meets its pass's depth buffer.
1497#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1498pub(crate) enum ShapeDepth {
1499    /// The pass has no depth buffer.
1500    Off,
1501    /// Paints what the opaque interiors of later records leave visible.
1502    Tested,
1503    /// Lays down opaque interiors, front to back, ahead of the paint.
1504    Interior,
1505}
1506
1507impl ShapeDepth {
1508    fn stencil_state(self) -> Option<wgpu::DepthStencilState> {
1509        let (depth_write_enabled, depth_compare) = match self {
1510            Self::Off => return None,
1511            Self::Tested => (false, wgpu::CompareFunction::Less),
1512            Self::Interior => (true, wgpu::CompareFunction::Less),
1513        };
1514        Some(wgpu::DepthStencilState {
1515            format: DEPTH_FORMAT,
1516            depth_write_enabled: Some(depth_write_enabled),
1517            depth_compare: Some(depth_compare),
1518            stencil: wgpu::StencilState::default(),
1519            bias: wgpu::DepthBiasState::default(),
1520        })
1521    }
1522}
1523
1524/// Depth steps one draw apart in a pass's order, as the shaders'
1525/// `DEPTH_STEP`.
1526const PASS_DEPTH_STEP: f32 = 1.0 / 1_048_576.0;
1527
1528/// The depth of the draw at `index` in its pass's order, as the shaders'
1529/// `record_depth` and `batch_depth` place it: later draws nearer.
1530pub(crate) fn pass_order_depth(index: u32) -> f32 {
1531    (1.0 - (index as f32 + 1.0) * PASS_DEPTH_STEP).max(0.0)
1532}
1533
1534/// The depth state of a glyph or image pipeline: in a pass with a depth
1535/// buffer it paints what later opaque interiors leave visible, as shapes do.
1536pub(crate) fn overlay_depth_state(depth: bool) -> Option<wgpu::DepthStencilState> {
1537    if depth {
1538        ShapeDepth::Tested.stencil_state()
1539    } else {
1540        None
1541    }
1542}
1543
1544/// Which records a shape pipeline draws turned, as `SHAPE_TURNS` in the
1545/// shape shader: none, every one, or each as its placement says.
1546#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1547pub(crate) enum ShapeTurns {
1548    None,
1549    All,
1550    Mixed,
1551}
1552
1553impl ShapeTurns {
1554    /// The turns of records placed under `turn`, in a pass whose flat and
1555    /// turned records alternate often when `mixed`.
1556    pub(crate) fn of(turn: SegmentTransform, mixed: bool) -> Self {
1557        if mixed {
1558            Self::Mixed
1559        } else if turn.is_identity() {
1560            Self::None
1561        } else {
1562            Self::All
1563        }
1564    }
1565
1566    fn constant(self) -> f64 {
1567        match self {
1568            Self::None => 0.0,
1569            Self::All => 1.0,
1570            Self::Mixed => 2.0,
1571        }
1572    }
1573}
1574
1575#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1576pub(crate) struct ShapePipelineKey {
1577    pub(crate) blend_mode: BlendMode,
1578    pub(crate) tier: RunTier,
1579    pub(crate) variant: ShapeVariant,
1580    pub(crate) turns: ShapeTurns,
1581    pub(crate) depth: ShapeDepth,
1582}
1583
1584/// Packs a key's fields into a number, low bit first.
1585#[derive(Default)]
1586struct KeyWriter {
1587    bits: u64,
1588    width: u32,
1589}
1590
1591impl KeyWriter {
1592    fn put(&mut self, value: u64, width: u32) {
1593        self.bits |= value << self.width;
1594        self.width += width;
1595    }
1596
1597    fn put_byte(&mut self, value: Option<u8>) {
1598        self.put(u64::from(value.is_some()), 1);
1599        self.put(u64::from(value.unwrap_or_default()), 8);
1600    }
1601}
1602
1603/// Unpacks what [`KeyWriter`] packed, low bit first.
1604/// The bits a key's shape kinds take: one per fragment kind.
1605const KIND_BITS: u32 = FRAGMENT_KIND_TRAPEZOID + 1;
1606
1607struct KeyReader(u64);
1608
1609impl KeyReader {
1610    fn take(&mut self, width: u32) -> u64 {
1611        let value = self.0 & ((1 << width) - 1);
1612        self.0 >>= width;
1613        value
1614    }
1615
1616    fn take_flag(&mut self) -> bool {
1617        self.take(1) == 1
1618    }
1619
1620    fn take_byte(&mut self) -> Option<u8> {
1621        let present = self.take_flag();
1622        let value = u8::try_from(self.take(8)).ok()?;
1623        present.then_some(value)
1624    }
1625
1626    fn take_kinds(&mut self) -> Option<u8> {
1627        u8::try_from(self.take(KIND_BITS))
1628            .ok()
1629            .filter(|kinds| *kinds != 0)
1630    }
1631}
1632
1633impl ShapePipelineKey {
1634    pub(crate) const DISK_LAYOUT: [u8; 8] = *b"CPKEY003";
1635
1636    /// The flat solid rect fill of a pass without a depth buffer, which
1637    /// every screen draws: on all 38 demo pages, and in a launch's first
1638    /// frames, which draw without the depth pre-pass.
1639    #[cfg(not(target_arch = "wasm32"))]
1640    const SOLID_RECT: Self = Self {
1641        blend_mode: BlendMode::SrcOver,
1642        tier: RunTier::Arena,
1643        variant: ShapeVariant {
1644            kinds: 1 << FRAGMENT_KIND_FILL,
1645            brush: None,
1646            solid: true,
1647            clip: SegmentClip::Untested,
1648            interior: false,
1649            dither: false,
1650            ablation: ShapeAblation {
1651                material: false,
1652                fill: false,
1653            },
1654        },
1655        turns: ShapeTurns::None,
1656        depth: ShapeDepth::Off,
1657    };
1658
1659    /// The key as a number a later launch reads back with
1660    /// [`Self::from_bits`], to build the pipeline ahead of its first frame.
1661    pub(crate) fn to_bits(self) -> u64 {
1662        let mut bits = KeyWriter::default();
1663        bits.put(self.blend_mode as u64, 5);
1664        bits.put(self.tier as u64, 2);
1665        let variant = self.variant;
1666        bits.put(u64::from(variant.kinds), KIND_BITS);
1667        bits.put_byte(variant.brush);
1668        bits.put(u64::from(variant.solid), 1);
1669        bits.put(
1670            match variant.clip {
1671                SegmentClip::Untested => 0,
1672                SegmentClip::Tested => 1,
1673                SegmentClip::Rounded => 2,
1674            },
1675            2,
1676        );
1677        bits.put(u64::from(variant.interior), 1);
1678        bits.put(u64::from(variant.dither), 1);
1679        bits.put(u64::from(variant.ablation.material), 1);
1680        bits.put(u64::from(variant.ablation.fill), 1);
1681        bits.put(
1682            match self.turns {
1683                ShapeTurns::None => 0,
1684                ShapeTurns::All => 1,
1685                ShapeTurns::Mixed => 2,
1686            },
1687            2,
1688        );
1689        bits.put(
1690            match self.depth {
1691                ShapeDepth::Off => 0,
1692                ShapeDepth::Tested => 1,
1693                ShapeDepth::Interior => 2,
1694            },
1695            2,
1696        );
1697        bits.bits
1698    }
1699
1700    /// The key [`Self::to_bits`] packed, or `None` for a number no key
1701    /// packs to.
1702    pub(crate) fn from_bits(packed: u64) -> Option<Self> {
1703        let mut bits = KeyReader(packed);
1704        let blend_mode = *BlendMode::ALL.get(usize::try_from(bits.take(5)).ok()?)?;
1705        let tier = match bits.take(2) {
1706            0 => RunTier::Store,
1707            1 => RunTier::Arena,
1708            2 => RunTier::Either,
1709            _ => return None,
1710        };
1711        let kinds = bits.take_kinds()?;
1712        let brush = bits.take_byte();
1713        let solid = bits.take_flag();
1714        let clip = match bits.take(2) {
1715            0 => SegmentClip::Untested,
1716            1 => SegmentClip::Tested,
1717            2 => SegmentClip::Rounded,
1718            _ => return None,
1719        };
1720        let interior = bits.take_flag();
1721        let dither = bits.take_flag();
1722        let ablation = ShapeAblation {
1723            material: bits.take_flag(),
1724            fill: bits.take_flag(),
1725        };
1726        let turns = match bits.take(2) {
1727            0 => ShapeTurns::None,
1728            1 => ShapeTurns::All,
1729            2 => ShapeTurns::Mixed,
1730            _ => return None,
1731        };
1732        let depth = match bits.take(2) {
1733            0 => ShapeDepth::Off,
1734            1 => ShapeDepth::Tested,
1735            2 => ShapeDepth::Interior,
1736            _ => return None,
1737        };
1738        (bits.0 == 0).then_some(Self {
1739            blend_mode,
1740            tier,
1741            variant: ShapeVariant {
1742                kinds,
1743                brush,
1744                solid,
1745                clip,
1746                interior,
1747                dither,
1748                ablation,
1749            },
1750            turns,
1751            depth,
1752        })
1753    }
1754
1755    #[cfg(test)]
1756    pub(crate) fn general_for(blend_mode: BlendMode, tier: RunTier) -> Self {
1757        Self {
1758            blend_mode,
1759            tier,
1760            variant: ShapeVariant::GENERAL,
1761            turns: ShapeTurns::None,
1762            depth: ShapeDepth::Off,
1763        }
1764    }
1765
1766    /// The pipeline that lays down the opaque interiors of this key's
1767    /// draws, if they have any: plain source-over draws. A turned record's
1768    /// layer draws in place only under a rigid turn, which keeps the
1769    /// interior's half-pixel inset from the fill's edge exact. The interior
1770    /// shader reads only the tier and the turns, so every variant shares one
1771    /// pipeline per tier and turns: one compile, and draws of different
1772    /// variants lay their interiors down together.
1773    pub(crate) fn interior(self) -> Option<Self> {
1774        (self.depth == ShapeDepth::Tested
1775            && !self.variant.rounded()
1776            && self.blend_mode == BlendMode::SrcOver
1777            && !self.variant.ablation.material
1778            && !self.variant.ablation.fill)
1779            .then_some(Self {
1780                variant: ShapeVariant::GENERAL,
1781                depth: ShapeDepth::Interior,
1782                ..self
1783            })
1784    }
1785
1786    pub(crate) fn general(self) -> Self {
1787        Self {
1788            tier: RunTier::Either,
1789            variant: self.variant.general(),
1790            ..self
1791        }
1792    }
1793
1794    pub(crate) fn is_general(self) -> bool {
1795        self.variant == self.variant.general()
1796    }
1797
1798    pub(crate) fn joined(self) -> Self {
1799        Self {
1800            variant: self.variant.joined(),
1801            ..self
1802        }
1803    }
1804}
1805
1806/// The entry points and pipeline constants of the shape program a key names.
1807pub(crate) struct ShapeProgram {
1808    pub(crate) vertex_entry: &'static str,
1809    pub(crate) fragment_entry: &'static str,
1810    pub(crate) constants: [(&'static str, f64); 14],
1811}
1812
1813impl ShapePipelineKey {
1814    pub(crate) fn program(self, mode: RunBufferMode) -> ShapeProgram {
1815        let Self {
1816            tier,
1817            variant,
1818            turns,
1819            depth,
1820            ..
1821        } = self;
1822        let constants = [
1823            ("SHAPE_KIND_FIXED", variant.kind().map_or(-1.0, f64::from)),
1824            ("SHAPE_KINDS", f64::from(variant.kinds)),
1825            ("BRUSH_KIND_FIXED", variant.brush.map_or(-1.0, f64::from)),
1826            ("SHAPE_SOLID", f64::from(u8::from(variant.solid))),
1827            (
1828                "SHAPE_CLIPPED",
1829                f64::from(u8::from(variant.clip != SegmentClip::Untested)),
1830            ),
1831            ("SHAPE_ROUNDED_CLIP", f64::from(u8::from(variant.rounded()))),
1832            (
1833                "SHAPE_INTERIOR",
1834                f64::from(u8::from(variant.interior && !variant.rounded())),
1835            ),
1836            ("SHAPE_DITHER", f64::from(u8::from(variant.dither))),
1837            ("SHAPE_TURNS", turns.constant()),
1838            ("SHAPE_TIER", f64::from(tier as u8)),
1839            ("SHAPE_BANDS", f64::from(u8::from(mode.storage))),
1840            ("SHAPE_TRIG_FILLED", f64::from(u8::from(mode.trig_fill))),
1841            ("SHAPE_FLAT", f64::from(u8::from(variant.ablation.material))),
1842            ("SHAPE_DISCARD", f64::from(u8::from(variant.ablation.fill))),
1843        ];
1844        let (vertex_entry, fragment_entry) = if depth == ShapeDepth::Interior {
1845            ("vs_record_interior", "fs_interior")
1846        } else {
1847            variant.entries(turns == ShapeTurns::None)
1848        };
1849        ShapeProgram {
1850            vertex_entry,
1851            fragment_entry,
1852            constants,
1853        }
1854    }
1855}
1856
1857pub(crate) fn create_shape_pipeline(
1858    device: &wgpu::Device,
1859    cache: Option<&wgpu::PipelineCache>,
1860    surface_format: wgpu::TextureFormat,
1861    shader: &SharedShader,
1862    key: ShapePipelineKey,
1863    mode: RunBufferMode,
1864) -> wgpu::RenderPipeline {
1865    let ShapePipelineKey {
1866        blend_mode,
1867        tier,
1868        variant,
1869        turns,
1870        depth,
1871    } = key;
1872    let ShapeProgram {
1873        vertex_entry,
1874        fragment_entry,
1875        constants,
1876    } = key.program(mode);
1877    let blend = (depth != ShapeDepth::Interior).then(|| blend_state_for_mode(blend_mode));
1878    let instance_layout = record_vertex_layouts().map(Some);
1879    let stages = shader.stages((vertex_entry, fragment_entry), &constants);
1880
1881    create_render_pipeline_logged(
1882        device,
1883        cache,
1884        &format!(
1885            "shape blend={blend_mode:?} tier={tier:?} variant={variant:?} turns={turns:?} depth={depth:?}"
1886        ),
1887        wgpu::RenderPipelineDescriptor {
1888            label: Some("Shape Pipeline"),
1889            layout: Some(shader.layout()),
1890            vertex: wgpu::VertexState {
1891                module: &stages.vertex,
1892                entry_point: Some(vertex_entry),
1893                compilation_options: wgpu::PipelineCompilationOptions {
1894                    constants: stages.constants,
1895                    ..wgpu::PipelineCompilationOptions::default()
1896                },
1897                buffers: &instance_layout,
1898            },
1899            fragment: Some(wgpu::FragmentState {
1900                module: &stages.fragment,
1901                entry_point: Some(fragment_entry),
1902                compilation_options: wgpu::PipelineCompilationOptions {
1903                    constants: stages.constants,
1904                    ..wgpu::PipelineCompilationOptions::default()
1905                },
1906                targets: &[Some(wgpu::ColorTargetState {
1907                    format: surface_format,
1908                    blend,
1909                    write_mask: wgpu::ColorWrites::ALL,
1910                })],
1911            }),
1912            primitive: wgpu::PrimitiveState {
1913                topology: wgpu::PrimitiveTopology::TriangleList,
1914                strip_index_format: None,
1915                front_face: wgpu::FrontFace::Ccw,
1916                cull_mode: None,
1917                unclipped_depth: false,
1918                polygon_mode: wgpu::PolygonMode::Fill,
1919                conservative: false,
1920            },
1921            depth_stencil: depth.stencil_state(),
1922            multisample: wgpu::MultisampleState::default(),
1923            multiview_mask: None,
1924            cache: None,
1925        },
1926    )
1927}
1928fn create_image_pipeline(
1929    device: &wgpu::Device,
1930    cache: Option<&wgpu::PipelineCache>,
1931    surface_format: wgpu::TextureFormat,
1932    shader: &SharedShader,
1933    blend_mode: BlendMode,
1934    variant: ImageVariant,
1935) -> wgpu::RenderPipeline {
1936    let module = shader.module();
1937    let ImageVariant {
1938        depth,
1939        alpha_mask,
1940        rounded,
1941    } = variant;
1942    let (vertex_entry, fragment_entry) = match (alpha_mask, rounded) {
1943        (false, false) => ("image_vs_main", "image_fs_main"),
1944        (true, false) => ("image_vs_main", "image_mask_fs_main"),
1945        (false, true) => ("image_rounded_vs_main", "image_rounded_fs_main"),
1946        (true, true) => ("image_rounded_vs_main", "image_mask_rounded_fs_main"),
1947    };
1948    // A rounded image reads its clip from an instance beside its vertices.
1949    let buffers = [Some(Vertex::desc()), Some(DeviceRoundedClip::desc())];
1950    create_render_pipeline_logged(
1951        device,
1952        cache,
1953        &format!(
1954            "image blend={blend_mode:?} depth={depth} alpha_mask={alpha_mask} rounded={rounded}"
1955        ),
1956        wgpu::RenderPipelineDescriptor {
1957            label: Some("Image Pipeline"),
1958            layout: Some(shader.layout()),
1959            vertex: wgpu::VertexState {
1960                module,
1961                entry_point: Some(vertex_entry),
1962                compilation_options: wgpu::PipelineCompilationOptions::default(),
1963                buffers: if rounded { &buffers } else { &buffers[..1] },
1964            },
1965            fragment: Some(wgpu::FragmentState {
1966                module,
1967                entry_point: Some(fragment_entry),
1968                compilation_options: wgpu::PipelineCompilationOptions::default(),
1969                targets: &[Some(wgpu::ColorTargetState {
1970                    format: surface_format,
1971                    blend: Some(blend_state_for_mode(blend_mode)),
1972                    write_mask: wgpu::ColorWrites::ALL,
1973                })],
1974            }),
1975            primitive: wgpu::PrimitiveState {
1976                topology: wgpu::PrimitiveTopology::TriangleList,
1977                strip_index_format: None,
1978                front_face: wgpu::FrontFace::Ccw,
1979                cull_mode: None,
1980                unclipped_depth: false,
1981                polygon_mode: wgpu::PolygonMode::Fill,
1982                conservative: false,
1983            },
1984            depth_stencil: overlay_depth_state(depth),
1985            multisample: wgpu::MultisampleState::default(),
1986            multiview_mask: None,
1987            cache: None,
1988        },
1989    )
1990}
1991
1992fn create_glyph_atlas_pipeline(
1993    device: &wgpu::Device,
1994    cache: Option<&wgpu::PipelineCache>,
1995    surface_format: wgpu::TextureFormat,
1996    shader: &SharedShader,
1997    (depth, quads): (bool, GlyphQuads),
1998) -> wgpu::RenderPipeline {
1999    let module = shader.module();
2000    create_render_pipeline_logged(
2001        device,
2002        cache,
2003        match (depth, quads) {
2004            (false, GlyphQuads::Plain) => "glyph-atlas",
2005            (true, GlyphQuads::Plain) => "glyph-atlas depth",
2006            (false, GlyphQuads::Aligned) => "glyph-atlas aligned",
2007            (true, GlyphQuads::Aligned) => "glyph-atlas aligned depth",
2008            (false, GlyphQuads::Turned) => "glyph-atlas turned",
2009            (true, GlyphQuads::Turned) => "glyph-atlas turned depth",
2010        },
2011        wgpu::RenderPipelineDescriptor {
2012            label: Some("Glyph Atlas Pipeline"),
2013            layout: Some(shader.layout()),
2014            vertex: wgpu::VertexState {
2015                module,
2016                entry_point: Some(match quads {
2017                    GlyphQuads::Plain => "glyph_atlas_vs_main",
2018                    GlyphQuads::Aligned => "glyph_atlas_aligned_vs_main",
2019                    GlyphQuads::Turned => "glyph_atlas_turned_vs_main",
2020                }),
2021                compilation_options: wgpu::PipelineCompilationOptions::default(),
2022                buffers: &[Some(match quads {
2023                    GlyphQuads::Turned => TurnedGlyph::desc(),
2024                    GlyphQuads::Plain | GlyphQuads::Aligned => GlyphInstance::desc(),
2025                })],
2026            },
2027            fragment: Some(wgpu::FragmentState {
2028                module,
2029                entry_point: Some(match quads {
2030                    GlyphQuads::Aligned => "glyph_atlas_aligned_fs_main",
2031                    GlyphQuads::Plain | GlyphQuads::Turned => "glyph_atlas_fs_main",
2032                }),
2033                compilation_options: wgpu::PipelineCompilationOptions::default(),
2034                targets: &[Some(wgpu::ColorTargetState {
2035                    format: surface_format,
2036                    blend: Some(blend_state_for_mode(BlendMode::SrcOver)),
2037                    write_mask: wgpu::ColorWrites::ALL,
2038                })],
2039            }),
2040            primitive: wgpu::PrimitiveState {
2041                topology: wgpu::PrimitiveTopology::TriangleStrip,
2042                strip_index_format: None,
2043                front_face: wgpu::FrontFace::Ccw,
2044                cull_mode: None,
2045                unclipped_depth: false,
2046                polygon_mode: wgpu::PolygonMode::Fill,
2047                conservative: false,
2048            },
2049            depth_stencil: overlay_depth_state(depth),
2050            multisample: wgpu::MultisampleState::default(),
2051            multiview_mask: None,
2052            cache: None,
2053        },
2054    )
2055}
2056
2057#[repr(C)]
2058#[derive(Copy, Clone, Debug, Pod, Zeroable)]
2059pub(crate) struct Vertex {
2060    position: [f32; 2],
2061    color: [f32; 4],
2062    uv: [f32; 2],
2063    uv_bounds: [f32; 4],
2064}
2065
2066impl Vertex {
2067    const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
2068        0 => Float32x2,
2069        1 => Float32x4,
2070        2 => Float32x2,
2071        3 => Float32x4,
2072    ];
2073
2074    fn desc() -> wgpu::VertexBufferLayout<'static> {
2075        wgpu::VertexBufferLayout {
2076            array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
2077            step_mode: wgpu::VertexStepMode::Vertex,
2078            attributes: &Self::ATTRIBS,
2079        }
2080    }
2081}
2082
2083/// The corners a glyph instance draws as a triangle strip: top-left,
2084/// top-right, bottom-left, bottom-right.
2085const GLYPH_QUAD_CORNERS: u32 = 4;
2086
2087/// One glyph quad as the glyph pipeline draws it: an instance whose four
2088/// corners the vertex stage picks from `rect` and `uv`.
2089#[repr(C)]
2090#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
2091pub(crate) struct GlyphInstance {
2092    rect: [f32; 4],
2093    uv: [f32; 4],
2094    uv_bounds: [f32; 4],
2095    color: [f32; 4],
2096}
2097
2098impl GlyphInstance {
2099    const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
2100        0 => Float32x4,
2101        1 => Float32x4,
2102        2 => Float32x4,
2103        3 => Float32x4
2104    ];
2105
2106    fn desc() -> wgpu::VertexBufferLayout<'static> {
2107        wgpu::VertexBufferLayout {
2108            array_stride: std::mem::size_of::<GlyphInstance>() as wgpu::BufferAddress,
2109            step_mode: wgpu::VertexStepMode::Instance,
2110            attributes: &Self::ATTRIBS,
2111        }
2112    }
2113
2114    /// The part of the quad inside `edges` (left, top, right, bottom, in the
2115    /// quad's own space), its atlas coordinates cut to match; `None` when
2116    /// none of it is inside.
2117    pub(crate) fn clipped_to(self, edges: [f32; 4]) -> Option<Self> {
2118        let [x0, y0, x1, y1] = self.rect;
2119        let rect = [
2120            x0.max(edges[0]),
2121            y0.max(edges[1]),
2122            x1.min(edges[2]),
2123            y1.min(edges[3]),
2124        ];
2125        if rect[2] <= rect[0] || rect[3] <= rect[1] {
2126            return None;
2127        }
2128        if rect == self.rect {
2129            return Some(self);
2130        }
2131        let [u0, v0, u1, v1] = self.uv;
2132        let u = |x: f32| u0 + (x - x0) / (x1 - x0) * (u1 - u0);
2133        let v = |y: f32| v0 + (y - y0) / (y1 - y0) * (v1 - v0);
2134        Some(Self {
2135            rect,
2136            uv: [u(rect[0]), v(rect[1]), u(rect[2]), v(rect[3])],
2137            ..self
2138        })
2139    }
2140}
2141
2142/// Hands `sink` each quad of a glyph run at `source_raster_rect` that the
2143/// viewport shows, as an instance cut to `cut` when the text is cut.
2144#[inline]
2145fn for_each_visible_glyph(
2146    source_raster_rect: Rect,
2147    quads: GlyphRunQuads<'_>,
2148    (clip, cut): (Option<Rect>, Option<[f32; 4]>),
2149    viewport: ViewportUniformParams,
2150    root_scale: f32,
2151    mut sink: impl FnMut(GlyphInstance),
2152) {
2153    let whole_run_visible =
2154        quads
2155            .bounds
2156            .within_viewport(source_raster_rect, clip, viewport, root_scale);
2157    for quad in quads.iter() {
2158        if !whole_run_visible
2159            && !cached_text_glyph_quad_is_visible_in_viewport(
2160                source_raster_rect,
2161                &quad,
2162                clip,
2163                viewport,
2164                root_scale,
2165            )
2166        {
2167            continue;
2168        }
2169        let Some(glyph) = cached_text_glyph_instance(source_raster_rect, &quad) else {
2170            continue;
2171        };
2172        let glyph = match cut {
2173            Some(edges) => glyph.clipped_to(edges),
2174            None => Some(glyph),
2175        };
2176        if let Some(glyph) = glyph {
2177            sink(glyph);
2178        }
2179    }
2180}
2181
2182/// A glyph quad of a layer drawn in place under a turn, with the turn that
2183/// places it: glyphs of layers turned differently then share a draw, and
2184/// every other glyph keeps [`GlyphInstance`]'s smaller layout.
2185#[repr(C)]
2186#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
2187pub(crate) struct TurnedGlyph {
2188    glyph: GlyphInstance,
2189    /// The turn, row-major.
2190    turn: [f32; 4],
2191    /// The turn's translation in `xy`.
2192    translation: [f32; 4],
2193}
2194
2195impl TurnedGlyph {
2196    const ATTRIBS: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
2197        0 => Float32x4,
2198        1 => Float32x4,
2199        2 => Float32x4,
2200        3 => Float32x4,
2201        4 => Float32x4,
2202        5 => Float32x4
2203    ];
2204
2205    pub(crate) fn new(glyph: GlyphInstance, turn: SegmentTransform) -> Self {
2206        let (linear, [x, y], _) = turn.uniform_parts();
2207        Self {
2208            glyph,
2209            turn: linear,
2210            translation: [x, y, 0.0, 0.0],
2211        }
2212    }
2213
2214    fn desc() -> wgpu::VertexBufferLayout<'static> {
2215        wgpu::VertexBufferLayout {
2216            array_stride: std::mem::size_of::<TurnedGlyph>() as wgpu::BufferAddress,
2217            step_mode: wgpu::VertexStepMode::Instance,
2218            attributes: &Self::ATTRIBS,
2219        }
2220    }
2221}
2222
2223/// The glyph quads a pass draws from its shared buffers: the plain ones and
2224/// those of layers drawn in place under a turn.
2225#[derive(Default)]
2226pub(crate) struct GlyphInstances {
2227    pub(crate) plain: FrameScratch<GlyphInstance>,
2228    pub(crate) turned: FrameScratch<TurnedGlyph>,
2229}
2230
2231impl GlyphInstances {
2232    pub(crate) fn clear(&mut self) {
2233        self.plain.clear();
2234        self.turned.clear();
2235    }
2236
2237    /// Ends a frame: see [`FrameScratch::end_frame`]. Passes need the
2238    /// most glyphs at startup, when nothing is cached yet.
2239    pub(crate) fn end_frame(&mut self) {
2240        self.plain.end_frame();
2241        self.turned.end_frame();
2242    }
2243
2244    fn lens(&self) -> (usize, usize) {
2245        (self.plain.len(), self.turned.len())
2246    }
2247
2248    /// How many turned glyphs, or plain ones, the pass holds.
2249    fn len_of(&self, turned: bool) -> usize {
2250        if turned {
2251            self.turned.len()
2252        } else {
2253            self.plain.len()
2254        }
2255    }
2256
2257    fn truncate(&mut self, (plain, turned): (usize, usize)) {
2258        self.plain.truncate(plain);
2259        self.turned.truncate(turned);
2260    }
2261}
2262
2263/// A text clip's edges in device pixels of the space its glyph quads are
2264/// laid out in, before a viewport transform moves them.
2265fn glyph_clip_edges(clip: Rect, root_scale: f32) -> [f32; 4] {
2266    [
2267        canonicalize_device_coordinate(clip.x * root_scale),
2268        canonicalize_device_coordinate(clip.y * root_scale),
2269        canonicalize_device_coordinate((clip.x + clip.width) * root_scale),
2270        canonicalize_device_coordinate((clip.y + clip.height) * root_scale),
2271    ]
2272}
2273
2274/// Where the glyph quads of a text are cut, in the quads' own space. Under a
2275/// turned viewport the cut is the text's `clip` itself, before the turn,
2276/// which no scissor can follow; the text then draws without one. Otherwise
2277/// it is the pixel edges of the text's `scissor`, its draw rect within its
2278/// clip: cut there, the quads cover exactly the pixels the scissor would
2279/// pass, with the same texels, so the text needs no scissor of its own and
2280/// draws in one call with its neighbours, even where a last line's
2281/// descenders or a glyph's padding reach past its draw rect.
2282fn glyph_cut_edges(
2283    clip: Option<Rect>,
2284    scissor: TargetRect,
2285    viewport: ViewportUniformParams,
2286    root_scale: f32,
2287) -> Option<[f32; 4]> {
2288    if !viewport.transform.is_identity() {
2289        return clip.map(|clip| glyph_clip_edges(clip, root_scale));
2290    }
2291    let (x, y, width, height) = scissor;
2292    let [offset_x, offset_y] = viewport.offset;
2293    Some([
2294        x as f32 + offset_x,
2295        y as f32 + offset_y,
2296        (x + width) as f32 + offset_x,
2297        (y + height) as f32 + offset_y,
2298    ])
2299}
2300
2301#[repr(C)]
2302#[derive(Copy, Clone, Debug, Pod, Zeroable)]
2303struct Uniforms {
2304    viewport: [f32; 2],
2305    viewport_offset: [f32; 2],
2306    transform: [f32; 4],
2307    translation: [f32; 2],
2308    reserved: [f32; 2],
2309    inverse: [f32; 4],
2310    origin: [f32; 2],
2311    origin_reserved: [f32; 2],
2312    placement: PlacementData,
2313}
2314
2315impl Uniforms {
2316    fn of(params: ViewportUniformParams, placement: PlacementData, tier: RunTier) -> Self {
2317        let (transform, translation, inverse) = params.transform.uniform_parts();
2318        Self {
2319            viewport: [params.width as f32, params.height as f32],
2320            viewport_offset: params.offset,
2321            transform,
2322            translation,
2323            reserved: [params.depth_base, f32::from(tier as u8)],
2324            inverse,
2325            origin: params.origin,
2326            origin_reserved: [0.0; 2],
2327            placement,
2328        }
2329    }
2330}
2331
2332static SURVIVE_GPU_ERRORS: DebugToggle = DebugToggle::new("CRANPOSE_SURVIVE_GPU_ERRORS");
2333
2334fn survive_gpu_errors_enabled() -> bool {
2335    !SURVIVE_GPU_ERRORS.equals("0")
2336}
2337
2338struct CachedImageTexture {
2339    bind_groups: ImageBindGroups,
2340    _texture: wgpu::Texture,
2341    _view: wgpu::TextureView,
2342    bytes: usize,
2343}
2344
2345struct ImageBindGroups {
2346    alpha_mask: bool,
2347    nearest: wgpu::BindGroup,
2348    linear: wgpu::BindGroup,
2349}
2350
2351impl ImageBindGroups {
2352    fn binding(&self, sampling: ImageSampling) -> ImageBinding {
2353        ImageBinding {
2354            bind_group: match sampling {
2355                ImageSampling::Nearest => self.nearest.clone(),
2356                ImageSampling::Linear => self.linear.clone(),
2357            },
2358            alpha_mask: self.alpha_mask,
2359        }
2360    }
2361}
2362
2363/// What an image's draw binds: its texture's bind group for the draw's
2364/// sampling, which keeps the texture alive whatever the cache evicts before
2365/// the pass is drawn, and whether the texture is an alpha mask.
2366pub(crate) struct ImageBinding {
2367    bind_group: wgpu::BindGroup,
2368    alpha_mask: bool,
2369}
2370
2371#[derive(Clone, Copy)]
2372struct GlyphAtlasEntry {
2373    x: u16,
2374    y: u16,
2375    width: u16,
2376    height: u16,
2377}
2378
2379fn next_glyph_atlas_size(current: u32, max: u32) -> u32 {
2380    current.saturating_mul(2).clamp(1, max.max(1))
2381}
2382
2383/// The samplers the glyph atlas binds: nearest for glyphs on the pixel grid,
2384/// linear for glyphs a segment transform turns.
2385#[derive(Clone, Copy)]
2386struct GlyphSamplers<'a> {
2387    nearest: &'a wgpu::Sampler,
2388    linear: &'a wgpu::Sampler,
2389}
2390
2391/// A glyph's atlas slot: its mask corrected for the luminance class of the
2392/// text it is drawn in, so one glyph in light and dark text takes two slots.
2393#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2394struct GlyphAtlasSlotKey {
2395    glyph: SoftwareGlyphAtlasKey,
2396    luminance: TextLuminance,
2397}
2398
2399impl GlyphAtlasSlotKey {
2400    fn new(glyph: SoftwareGlyphAtlasKey, color: Color) -> Self {
2401        Self {
2402            glyph,
2403            luminance: TextLuminance::of_color(color),
2404        }
2405    }
2406}
2407
2408/// Slots of [`RunAtlasEntries`], by glyph id.
2409const RUN_ATLAS_ENTRY_SLOTS: usize = 64;
2410
2411/// The atlas entries a run's preparation has looked up, by glyph id: a run
2412/// repeats its letters, and each atlas lookup hashes the slot key and moves
2413/// the entry up the atlas's recency order, where the first lookup already
2414/// put it for this frame.
2415struct RunAtlasEntries {
2416    slots: [Option<(GlyphAtlasSlotKey, GlyphAtlasEntry)>; RUN_ATLAS_ENTRY_SLOTS],
2417}
2418
2419impl RunAtlasEntries {
2420    fn new() -> Self {
2421        Self {
2422            slots: [None; RUN_ATLAS_ENTRY_SLOTS],
2423        }
2424    }
2425
2426    /// `glyph`'s entry from an earlier glyph of the run, else from
2427    /// `look_up`, remembered for the rest of it.
2428    fn entry(
2429        &mut self,
2430        renderer: &mut GpuRenderer,
2431        glyph: &SoftwareGlyphAtlasPlacement,
2432        look_up: impl FnOnce(&mut GpuRenderer) -> Result<GlyphAtlasEntry, String>,
2433    ) -> Result<GlyphAtlasEntry, String> {
2434        let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2435        let slot = &mut self.slots[glyph.key.glyph_id as usize % RUN_ATLAS_ENTRY_SLOTS];
2436        if let Some((seen, entry)) = *slot
2437            && seen == key
2438        {
2439            renderer.frame_stats.record_text_glyph_atlas_hits(1);
2440            return Ok(entry);
2441        }
2442        let entry = look_up(renderer)?;
2443        *slot = Some((key, entry));
2444        Ok(entry)
2445    }
2446}
2447
2448struct TextGlyphAtlas {
2449    texture: wgpu::Texture,
2450    _view: wgpu::TextureView,
2451    texel_bind_group: Rc<wgpu::BindGroup>,
2452    filtered_bind_group: Rc<wgpu::BindGroup>,
2453    entries: BoundedLruCache<GlyphAtlasSlotKey, GlyphAtlasEntry>,
2454    generation: u64,
2455    size: u32,
2456    max_size: u32,
2457    cursor_x: u32,
2458    cursor_y: u32,
2459    row_height: u32,
2460    /// The glyphs placed since [`Self::flush_uploads`], in the order they
2461    /// were placed, and their coverage one after another.
2462    pending: Vec<GlyphAtlasEntry>,
2463    pending_coverage: Vec<u8>,
2464    upload_scratch: Vec<u8>,
2465}
2466
2467impl TextGlyphAtlas {
2468    fn new(
2469        device: &wgpu::Device,
2470        image_layout: &wgpu::BindGroupLayout,
2471        samplers: GlyphSamplers<'_>,
2472        size: u32,
2473    ) -> Self {
2474        // The side stays a power of two, whose texel is exact: see
2475        // [`TextGlyphAtlas::texel`].
2476        let device_max = device.limits().max_texture_dimension_2d.max(1);
2477        let max_size = TEXT_GLYPH_ATLAS_MAX_SIZE.min(1 << device_max.ilog2());
2478        let size = size
2479            .next_power_of_two()
2480            .clamp(TEXT_GLYPH_ATLAS_MIN_SIZE.min(max_size), max_size);
2481        let texture = Self::create_texture(device, size);
2482        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2483        let bind = |label: &'static str, sampler: &wgpu::Sampler| {
2484            Rc::new(device.create_bind_group(&wgpu::BindGroupDescriptor {
2485                label: Some(label),
2486                layout: image_layout,
2487                entries: &[
2488                    wgpu::BindGroupEntry {
2489                        binding: 0,
2490                        resource: wgpu::BindingResource::TextureView(&view),
2491                    },
2492                    wgpu::BindGroupEntry {
2493                        binding: 1,
2494                        resource: wgpu::BindingResource::Sampler(sampler),
2495                    },
2496                ],
2497            }))
2498        };
2499        let texel_bind_group = bind("Text Glyph Atlas Bind Group", samplers.nearest);
2500        let filtered_bind_group = bind("Filtered Text Glyph Atlas Bind Group", samplers.linear);
2501        Self {
2502            texture,
2503            _view: view,
2504            texel_bind_group,
2505            filtered_bind_group,
2506            entries: BoundedLruCache::with_capacity_at_least_one(MAX_TEXT_GLYPH_ATLAS_ITEMS),
2507            generation: 0,
2508            size,
2509            max_size,
2510            cursor_x: TEXT_GLYPH_ATLAS_PADDING,
2511            cursor_y: TEXT_GLYPH_ATLAS_PADDING,
2512            row_height: 0,
2513            pending: Vec::new(),
2514            pending_coverage: Vec::new(),
2515            upload_scratch: Vec::new(),
2516        }
2517    }
2518
2519    fn create_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture {
2520        device.create_texture(&wgpu::TextureDescriptor {
2521            label: Some("Text Glyph Atlas Texture"),
2522            size: wgpu::Extent3d {
2523                width: size,
2524                height: size,
2525                depth_or_array_layers: 1,
2526            },
2527            mip_level_count: 1,
2528            sample_count: 1,
2529            dimension: wgpu::TextureDimension::D2,
2530            format: wgpu::TextureFormat::R8Unorm,
2531            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2532            view_formats: &[],
2533        })
2534    }
2535
2536    fn reset(
2537        &mut self,
2538        device: &wgpu::Device,
2539        image_layout: &wgpu::BindGroupLayout,
2540        samplers: GlyphSamplers<'_>,
2541    ) {
2542        let generation = self.generation.wrapping_add(1);
2543        let grown = next_glyph_atlas_size(self.size, self.max_size);
2544        let mut next = Self::new(device, image_layout, samplers, grown);
2545        next.generation = generation;
2546        *self = next;
2547    }
2548
2549    /// The atlas bound for glyphs drawn under `transform`: texel for texel
2550    /// on the pixel grid, filtered once a transform turns the glyph quads
2551    /// off it.
2552    fn bind_group(&self, transform: SegmentTransform) -> Rc<wgpu::BindGroup> {
2553        Rc::clone(if transform.is_identity() {
2554            &self.texel_bind_group
2555        } else {
2556            &self.filtered_bind_group
2557        })
2558    }
2559
2560    fn generation(&self) -> u64 {
2561        self.generation
2562    }
2563
2564    fn size(&self) -> u32 {
2565        self.size
2566    }
2567
2568    /// One texel's share of the atlas side. The side is a power of two, so
2569    /// this reciprocal is exact and a coordinate times it is the coordinate
2570    /// divided by the side: a glyph's quad takes eight of them.
2571    fn texel(&self) -> f32 {
2572        (self.size() as f32).recip()
2573    }
2574
2575    fn entry(&mut self, key: &GlyphAtlasSlotKey) -> Option<GlyphAtlasEntry> {
2576        self.entries.get(key).copied()
2577    }
2578
2579    fn allocate(&mut self, width: u32, height: u32) -> Option<GlyphAtlasEntry> {
2580        let max_extent = self.size.saturating_sub(TEXT_GLYPH_ATLAS_PADDING * 2);
2581        if width == 0 || height == 0 || width > max_extent || height > max_extent {
2582            return None;
2583        }
2584
2585        if self.cursor_x + width + TEXT_GLYPH_ATLAS_PADDING > self.size {
2586            self.cursor_x = TEXT_GLYPH_ATLAS_PADDING;
2587            self.cursor_y = self
2588                .cursor_y
2589                .saturating_add(self.row_height)
2590                .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2591            self.row_height = 0;
2592        }
2593        if self.cursor_y > self.size - height - TEXT_GLYPH_ATLAS_PADDING {
2594            return None;
2595        }
2596
2597        let entry = GlyphAtlasEntry {
2598            x: self.cursor_x as u16,
2599            y: self.cursor_y as u16,
2600            width: width as u16,
2601            height: height as u16,
2602        };
2603        self.cursor_x = self
2604            .cursor_x
2605            .saturating_add(width)
2606            .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2607        self.row_height = self.row_height.max(height);
2608        Some(entry)
2609    }
2610
2611    /// The atlas entry of `glyph`, placed now if the atlas does not hold it
2612    /// yet; a placed glyph reaches the texture at [`Self::flush_uploads`].
2613    /// `None` when the atlas is full.
2614    fn upload_glyph(
2615        &mut self,
2616        glyph: &SoftwareGlyphAtlasGlyph,
2617        frame_stats: &mut gpu_stats::FrameStats,
2618    ) -> Option<GlyphAtlasEntry> {
2619        let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2620        if let Some(entry) = self.entry(&key) {
2621            frame_stats.record_text_glyph_atlas_hits(1);
2622            return Some(entry);
2623        }
2624
2625        let width = u32::try_from(glyph.mask.width).ok()?;
2626        let height = u32::try_from(glyph.mask.height).ok()?;
2627        let entry = self.allocate(width, height)?;
2628        let correction = key.luminance.correction();
2629        self.pending_coverage.extend(
2630            glyph
2631                .mask
2632                .alpha
2633                .iter()
2634                .map(|&coverage| correction.apply(coverage)),
2635        );
2636        self.pending.push(entry);
2637        frame_stats.record_text_glyph_atlas_miss(width, height);
2638        self.entries.put(key, entry);
2639        Some(entry)
2640    }
2641
2642    /// Writes the glyphs placed since the last call to the texture, one
2643    /// write for each run of them placed side by side on a row. The atlas
2644    /// never places a glyph where one was, so the run's padding and the
2645    /// rows under its shorter glyphs are empty, and the write leaves them
2646    /// so. A frame calls this before it submits draws that read them.
2647    fn flush_uploads(
2648        &mut self,
2649        queue: &wgpu::Queue,
2650        executor: &mut WgpuFrameGraphExecutor,
2651        frame_stats: &mut gpu_stats::FrameStats,
2652    ) {
2653        let mut coverage = 0;
2654        let mut run_start = 0;
2655        while run_start < self.pending.len() {
2656            let first = self.pending[run_start];
2657            let mut run_end = run_start + 1;
2658            while self
2659                .pending
2660                .get(run_end)
2661                .is_some_and(|next| next.y == first.y && next.x > self.pending[run_end - 1].x)
2662            {
2663                run_end += 1;
2664            }
2665            let run = &self.pending[run_start..run_end];
2666            let last = run[run.len() - 1];
2667            let x = u32::from(first.x);
2668            let width = u32::from(last.x) + u32::from(last.width) - x;
2669            let height = run
2670                .iter()
2671                .map(|entry| u32::from(entry.height))
2672                .max()
2673                .unwrap_or(0);
2674            self.upload_scratch.clear();
2675            self.upload_scratch.resize((width * height) as usize, 0);
2676            for entry in run {
2677                let glyph_width = usize::from(entry.width);
2678                let left = usize::from(entry.x) - x as usize;
2679                for row in 0..usize::from(entry.height) {
2680                    let source = coverage + row * glyph_width;
2681                    let target = row * width as usize + left;
2682                    self.upload_scratch[target..target + glyph_width]
2683                        .copy_from_slice(&self.pending_coverage[source..source + glyph_width]);
2684                }
2685                coverage += glyph_width * usize::from(entry.height);
2686            }
2687            let upload_stats = executor.upload_texture(
2688                queue,
2689                wgpu::TexelCopyTextureInfo {
2690                    texture: &self.texture,
2691                    mip_level: 0,
2692                    origin: wgpu::Origin3d {
2693                        x,
2694                        y: u32::from(first.y),
2695                        z: 0,
2696                    },
2697                    aspect: wgpu::TextureAspect::All,
2698                },
2699                &self.upload_scratch,
2700                wgpu::TexelCopyBufferLayout {
2701                    offset: 0,
2702                    bytes_per_row: Some(width),
2703                    rows_per_image: Some(height),
2704                },
2705                wgpu::Extent3d {
2706                    width,
2707                    height,
2708                    depth_or_array_layers: 1,
2709                },
2710            );
2711            frame_stats.record_command_stats(upload_stats);
2712            run_start = run_end;
2713        }
2714        self.pending.clear();
2715        self.pending_coverage.clear();
2716    }
2717}
2718
2719/// The image pipeline a draw takes: in a pass with depth or not, for an
2720/// alpha mask or a color image, and taking a rounded clip in place or not.
2721#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2722pub(crate) struct ImageVariant {
2723    depth: bool,
2724    alpha_mask: bool,
2725    rounded: bool,
2726}
2727
2728pub(crate) struct ImageDrawCmd {
2729    index_start: u32,
2730    scissor: (u32, u32, u32, u32),
2731    image: ImageBinding,
2732    /// The rounded clip whose coverage the image takes in place: its index
2733    /// among the pass's clip instances.
2734    clip: Option<u32>,
2735}
2736
2737impl ImageVariant {
2738    /// The variant `cmd` draws with in a pass with a depth buffer or not.
2739    fn of(cmd: &ImageDrawCmd, depth: bool) -> Self {
2740        Self {
2741            depth,
2742            alpha_mask: cmd.image.alpha_mask,
2743            rounded: cmd.clip.is_some(),
2744        }
2745    }
2746}
2747
2748impl ImageDrawCmd {
2749    /// Target pixels the draw can touch: its scissor.
2750    pub(crate) fn bounds(&self) -> TargetRect {
2751        self.scissor
2752    }
2753}
2754
2755/// Which glyph pipeline draws a stretch of quads: plain quads, sampled
2756/// within their glyph's texel centers; plain quads on whole pixels at one
2757/// texel a pixel, whose samples land on those centers unclamped; or quads
2758/// of a layer drawn in place under a turn, which are [`TurnedGlyph`]s.
2759#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2760pub(crate) enum GlyphQuads {
2761    Plain,
2762    Aligned,
2763    Turned,
2764}
2765
2766impl GlyphQuads {
2767    fn turned(self) -> bool {
2768        self == Self::Turned
2769    }
2770
2771    /// The plain kind that fits quads whose every corner is `aligned`.
2772    fn plain(aligned: bool) -> Self {
2773        if aligned { Self::Aligned } else { Self::Plain }
2774    }
2775}
2776
2777/// Whether a plain glyph quad at `rect` lands on whole pixels of a target
2778/// whose origin sits at `offset`: its quads hold one texel a pixel.
2779fn glyph_rect_aligned(rect: [f32; 4], offset: [f32; 2]) -> bool {
2780    let whole = |value: f32| value.fract() == 0.0;
2781    whole(rect[0] - offset[0])
2782        && whole(rect[1] - offset[1])
2783        && whole(rect[2] - offset[0])
2784        && whole(rect[3] - offset[1])
2785}
2786
2787#[derive(Clone)]
2788enum GlyphDrawSource {
2789    Shared {
2790        instance_start: u32,
2791        instance_count: u32,
2792        quads: GlyphQuads,
2793    },
2794    Retained {
2795        run: Rc<CachedGpuTextGlyphRun>,
2796        uniform_slot: usize,
2797        aligned: bool,
2798    },
2799}
2800
2801#[derive(Clone)]
2802pub(crate) struct GlyphDrawCmd {
2803    atlas: Rc<wgpu::BindGroup>,
2804    source: GlyphDrawSource,
2805    /// The scissor the text's own clip needs, `None` when its quads lie
2806    /// inside that clip anyway and only the batch's bound applies.
2807    scissor: Option<(u32, u32, u32, u32)>,
2808    /// Target pixels the draw can touch, for ordering it against others.
2809    bounds: (u32, u32, u32, u32),
2810}
2811
2812/// One draw of a glyph batch: a stretch of shared quads, or a retained run.
2813struct GlyphDraw<'a> {
2814    atlas: &'a Rc<wgpu::BindGroup>,
2815    scissor: Option<(u32, u32, u32, u32)>,
2816    step: GlyphDrawStep<'a>,
2817}
2818
2819enum GlyphDrawStep<'a> {
2820    /// A stretch of the shared instances of one kind.
2821    Shared(std::ops::Range<u32>, GlyphQuads),
2822    Retained {
2823        run: &'a CachedGpuTextGlyphRun,
2824        uniform_slot: usize,
2825        aligned: bool,
2826    },
2827}
2828
2829/// The draws a batch's glyph commands take: consecutive shared commands with
2830/// one atlas and one scissor whose quads follow each other in the frame's
2831/// shared buffer draw as one.
2832struct GlyphDraws<'a> {
2833    cmds: &'a [GlyphDrawCmd],
2834}
2835
2836impl<'a> GlyphDraws<'a> {
2837    fn new(cmds: &'a [GlyphDrawCmd]) -> Self {
2838        Self { cmds }
2839    }
2840}
2841
2842impl<'a> Iterator for GlyphDraws<'a> {
2843    type Item = GlyphDraw<'a>;
2844
2845    fn next(&mut self) -> Option<Self::Item> {
2846        let (first, rest) = self.cmds.split_first()?;
2847        self.cmds = rest;
2848        let step = match &first.source {
2849            GlyphDrawSource::Retained {
2850                run,
2851                uniform_slot,
2852                aligned,
2853            } => GlyphDrawStep::Retained {
2854                run,
2855                uniform_slot: *uniform_slot,
2856                aligned: *aligned,
2857            },
2858            GlyphDrawSource::Shared {
2859                instance_start,
2860                instance_count,
2861                quads,
2862            } => {
2863                let mut end = instance_start + instance_count;
2864                while let Some((next, rest)) = self.cmds.split_first() {
2865                    match next.source {
2866                        GlyphDrawSource::Shared {
2867                            instance_start,
2868                            instance_count,
2869                            quads: next_quads,
2870                        } if instance_start == end
2871                            && next_quads == *quads
2872                            && next.scissor == first.scissor
2873                            && Rc::ptr_eq(&next.atlas, &first.atlas) =>
2874                        {
2875                            end += instance_count;
2876                            self.cmds = rest;
2877                        }
2878                        _ => break,
2879                    }
2880                }
2881                GlyphDrawStep::Shared(*instance_start..end, *quads)
2882            }
2883        };
2884        Some(GlyphDraw {
2885            atlas: &first.atlas,
2886            scissor: first.scissor,
2887            step,
2888        })
2889    }
2890}
2891
2892impl GlyphDrawCmd {
2893    /// The quads the command draws, which pick its pipeline.
2894    fn quads(&self) -> GlyphQuads {
2895        match &self.source {
2896            GlyphDrawSource::Shared { quads, .. } => *quads,
2897            GlyphDrawSource::Retained { aligned, .. } => GlyphQuads::plain(*aligned),
2898        }
2899    }
2900
2901    fn shared(
2902        (instances, quads): (std::ops::Range<usize>, GlyphQuads),
2903        scissor: Option<(u32, u32, u32, u32)>,
2904        bounds: (u32, u32, u32, u32),
2905        atlas: Rc<wgpu::BindGroup>,
2906    ) -> Self {
2907        let start = u32::try_from(instances.start).unwrap_or(u32::MAX);
2908        let end = u32::try_from(instances.end).unwrap_or(u32::MAX);
2909        Self {
2910            atlas,
2911            source: GlyphDrawSource::Shared {
2912                instance_start: start,
2913                instance_count: end.saturating_sub(start),
2914                quads,
2915            },
2916            scissor,
2917            bounds,
2918        }
2919    }
2920
2921    fn retained(
2922        (run, uniform_slot, aligned): (Rc<CachedGpuTextGlyphRun>, usize, bool),
2923        scissor: (u32, u32, u32, u32),
2924        atlas: Rc<wgpu::BindGroup>,
2925    ) -> Self {
2926        Self {
2927            atlas,
2928            source: GlyphDrawSource::Retained {
2929                run,
2930                uniform_slot,
2931                aligned,
2932            },
2933            scissor: Some(scissor),
2934            bounds: scissor,
2935        }
2936    }
2937
2938    /// Target pixels the draw can touch.
2939    pub(crate) fn bounds(&self) -> (u32, u32, u32, u32) {
2940        self.bounds
2941    }
2942
2943    /// Whether the draw's quads are [`TurnedGlyph`]s, or `None` for a
2944    /// retained run, which draws on its own.
2945    fn turned(&self) -> Option<bool> {
2946        match self.source {
2947            GlyphDrawSource::Shared { quads, .. } => Some(quads.turned()),
2948            GlyphDrawSource::Retained { .. } => None,
2949        }
2950    }
2951}
2952
2953/// The kind of glyph draw, turned (`true`) or plain, that can move after
2954/// every draw of the other kind in `draws` without moving past a draw it
2955/// shares a pixel with: glyphs blend, so only draws that share pixels must
2956/// keep their order. The fewer kind is tried first, which checks fewer
2957/// pairs. `None` when neither can move, a retained run is among them, or
2958/// the kinds do not change back and forth.
2959pub(crate) fn movable_glyph_kind<T>(
2960    draws: &[T],
2961    kind: impl Fn(&T) -> Option<bool>,
2962    bounds: impl Fn(&T) -> TargetRect,
2963) -> Option<bool> {
2964    let mut turned = 0;
2965    for draw in draws {
2966        turned += usize::from(kind(draw)?);
2967    }
2968    let changes = draws
2969        .windows(2)
2970        .filter(|pair| kind(&pair[0]) != kind(&pair[1]))
2971        .count();
2972    if changes < 2 {
2973        return None;
2974    }
2975    let fewer = turned * 2 < draws.len();
2976    [fewer, !fewer].into_iter().find(|&moved| {
2977        draws.iter().enumerate().all(|(index, draw)| {
2978            kind(draw) != Some(moved)
2979                || draws[index + 1..].iter().all(|later| {
2980                    kind(later) == Some(moved)
2981                        || !crate::draw_pass::target_rects_overlap(bounds(draw), bounds(later))
2982                })
2983        })
2984    })
2985}
2986
2987/// Moves a glyph batch's retained runs after its shared quads, each in its
2988/// order, when no run shares a pixel with a shared draw after it: the
2989/// shared quads around a run, which follow each other in the frame's
2990/// buffer, then draw at once. A card's body text, a retained run between
2991/// its title and its labels, split them into two draws. Returns how many
2992/// shared draws lead the batch, none when its runs keep their places;
2993/// `moved` is scratch.
2994pub(crate) fn defer_retained_glyph_runs(
2995    cmds: &mut [GlyphDrawCmd],
2996    moved: &mut Vec<GlyphDrawCmd>,
2997) -> usize {
2998    let retained = |cmd: &GlyphDrawCmd| cmd.turned().is_none();
2999    let shared = cmds.iter().filter(|cmd| !retained(cmd)).count();
3000    if cmds[..shared].iter().all(|cmd| !retained(cmd)) {
3001        return shared;
3002    }
3003    let deferrable = cmds.iter().enumerate().all(|(index, cmd)| {
3004        !retained(cmd)
3005            || cmds[index + 1..].iter().all(|later| {
3006                retained(later)
3007                    || !crate::draw_pass::target_rects_overlap(cmd.bounds(), later.bounds())
3008            })
3009    });
3010    if !deferrable {
3011        return 0;
3012    }
3013    moved.clear();
3014    let mut kept = 0;
3015    for read in 0..cmds.len() {
3016        if retained(&cmds[read]) {
3017            moved.push(cmds[read].clone());
3018        } else {
3019            cmds.swap(kept, read);
3020            kept += 1;
3021        }
3022    }
3023    for (slot, cmd) in cmds[kept..].iter_mut().zip(moved.drain(..)) {
3024        *slot = cmd;
3025    }
3026    shared
3027}
3028
3029/// Moves a glyph batch's draws of the kind [`movable_glyph_kind`] picks
3030/// after those of the other kind, each kind in its order, so each draws
3031/// once instead of once per change between them. `moved` is scratch.
3032pub(crate) fn group_glyph_kinds(cmds: &mut [GlyphDrawCmd], moved: &mut Vec<GlyphDrawCmd>) {
3033    let Some(kind) = movable_glyph_kind(cmds, GlyphDrawCmd::turned, GlyphDrawCmd::bounds) else {
3034        return;
3035    };
3036    moved.clear();
3037    let mut kept = 0;
3038    for read in 0..cmds.len() {
3039        if cmds[read].turned() == Some(kind) {
3040            moved.push(cmds[read].clone());
3041        } else {
3042            cmds.swap(kept, read);
3043            kept += 1;
3044        }
3045    }
3046    for (slot, cmd) in cmds[kept..].iter_mut().zip(moved.drain(..)) {
3047        *slot = cmd;
3048    }
3049}
3050
3051#[derive(Clone, Copy, Debug, PartialEq)]
3052struct ImageUvRect {
3053    min: [f32; 2],
3054    max: [f32; 2],
3055    sample_bounds: [f32; 4],
3056}
3057
3058/// A growable vertex buffer and index buffer pair.
3059/// One pass's image and shared glyph quads: the frame's vertex and index
3060/// uploads they were appended to.
3061pub(crate) struct ImageSlot {
3062    vertices: BufferUpload,
3063    indices: BufferUpload,
3064    /// The rounded clips the pass's images take in place, one instance each.
3065    clips: Option<BufferUpload>,
3066}
3067
3068fn image_vertex_spec() -> UploadAllocatorSpec {
3069    UploadAllocatorSpec::vertex("Image Vertex Buffer", std::mem::size_of::<Vertex>() as u64)
3070}
3071
3072fn image_index_spec() -> UploadAllocatorSpec {
3073    UploadAllocatorSpec::index("Image Index Buffer", std::mem::size_of::<u32>() as u64)
3074}
3075
3076fn glyph_instance_spec() -> UploadAllocatorSpec {
3077    UploadAllocatorSpec::vertex(
3078        "Glyph Instance Buffer",
3079        std::mem::size_of::<GlyphInstance>() as u64,
3080    )
3081}
3082
3083fn turned_glyph_spec() -> UploadAllocatorSpec {
3084    UploadAllocatorSpec::vertex(
3085        "Turned Glyph Instance Buffer",
3086        std::mem::size_of::<TurnedGlyph>() as u64,
3087    )
3088}
3089
3090#[derive(Default)]
3091struct ViewportUniforms {
3092    uploads: FrameUploadAllocators,
3093    slots: Vec<UniformUpload>,
3094}
3095
3096impl ViewportUniforms {
3097    fn begin_frame(&mut self) {
3098        self.slots.clear();
3099        self.uploads.reset();
3100    }
3101
3102    fn claim(
3103        &mut self,
3104        device: &wgpu::Device,
3105        layout: &wgpu::BindGroupLayout,
3106        uniforms: &Uniforms,
3107    ) -> usize {
3108        let slot = self.slots.len();
3109        self.slots.push(self.uploads.upload_uniform(
3110            UploadAllocatorId::Viewport,
3111            UploadAllocatorSpec::uniform(
3112                "Viewport Uniform Buffer",
3113                "Viewport Uniform Bind Group",
3114                std::mem::size_of::<Uniforms>() as u64,
3115            ),
3116            device,
3117            layout,
3118            bytemuck::bytes_of(uniforms),
3119        ));
3120        slot
3121    }
3122
3123    fn bind(&self, pass: &mut TrackedPass<'_, '_>, slot: usize) -> Result<(), String> {
3124        let uniform = self
3125            .slots
3126            .get(slot)
3127            .ok_or_else(|| "viewport uniform slot was never claimed this frame".to_string())?;
3128        pass.set_bind_group(0, &uniform.bind_group, &[uniform.offset]);
3129        Ok(())
3130    }
3131
3132    fn stage_pending(
3133        &mut self,
3134        device: &wgpu::Device,
3135        recorder: &mut impl FrameCommandRecorder,
3136    ) -> FrameCommandStats {
3137        self.uploads.stage_pending(|buffer, offset, bytes| {
3138            recorder.stage_frame_buffer_copy(device, buffer, offset, bytes)
3139        })
3140    }
3141}
3142
3143#[derive(Clone, Copy, Debug, PartialEq)]
3144pub(crate) struct ViewportUniformParams {
3145    pub(crate) width: u32,
3146    pub(crate) height: u32,
3147    pub(crate) offset: [f32; 2],
3148    pub(crate) transform: SegmentTransform,
3149    /// Where the drawn vertices' origin sits in the segment's device space,
3150    /// added before the transform: zero, except for a retained glyph run
3151    /// drawn under a transform, whose vertices sit at its raster origin. The
3152    /// sum is the one the shared path writes, so both draw the same pixels.
3153    pub(crate) origin: [f32; 2],
3154    /// The pass-order index of the batch's first shape record, from which
3155    /// each record's depth counts.
3156    pub(crate) depth_base: f32,
3157}
3158
3159impl ViewportUniformParams {
3160    /// The logical rect of the drawn scene that the target shows.
3161    pub(crate) fn scene_rect(self, root_scale: f32) -> Rect {
3162        segment_scene_rect(
3163            self.transform,
3164            Rect {
3165                x: self.offset[0],
3166                y: self.offset[1],
3167                width: self.width as f32,
3168                height: self.height as f32,
3169            },
3170            root_scale,
3171        )
3172    }
3173}
3174
3175/// The logical rect of a scene drawn under `transform` that the device rect
3176/// `device` of the target's scene space shows: the rect itself when the
3177/// scene is not transformed, else the bounds it maps back to.
3178pub(crate) fn segment_scene_rect(
3179    transform: SegmentTransform,
3180    device: Rect,
3181    root_scale: f32,
3182) -> Rect {
3183    let device = if transform.is_identity() {
3184        device
3185    } else {
3186        transform.segment_bounds(device)
3187    };
3188    Rect {
3189        x: device.x / root_scale,
3190        y: device.y / root_scale,
3191        width: device.width / root_scale,
3192        height: device.height / root_scale,
3193    }
3194}
3195
3196/// A stored run's draws for one pass: the tables current when it was
3197/// prepared, the uniform slot holding its placement, and the range of the
3198/// pass's run draws with the pipeline and vertex range of each segment's
3199/// quads and bands.
3200pub(crate) struct StoreRunBatch {
3201    pub(crate) tables: StoredTables,
3202    pub(crate) uniform_slot: usize,
3203    pub(crate) draws: std::ops::Range<usize>,
3204    /// The scissor an unturned run's clip puts on its paint: see
3205    /// [`clip_scissor`].
3206    pub(crate) clip: Option<TargetRect>,
3207}
3208
3209struct CompositionTarget {
3210    target: Rc<OffscreenTarget>,
3211    output_bind_group: wgpu::BindGroup,
3212}
3213
3214/// Where a frame renders: straight into the presentable image, or into the
3215/// reusable composition target that the output conversion then copies out.
3216enum FrameRoot {
3217    Surface(Rc<OffscreenTarget>),
3218    Composition(CompositionTarget),
3219}
3220
3221impl FrameRoot {
3222    fn target(&self) -> &Rc<OffscreenTarget> {
3223        match self {
3224            Self::Surface(target) => target,
3225            Self::Composition(composition) => &composition.target,
3226        }
3227    }
3228
3229    /// The output conversion's destination and source bind group; nothing
3230    /// when the frame already rendered into the presentable image.
3231    fn output<'a>(
3232        &'a self,
3233        output_view: Option<&'a wgpu::TextureView>,
3234        screenshot_bind_group: Option<&'a wgpu::BindGroup>,
3235    ) -> Option<(&'a wgpu::TextureView, &'a wgpu::BindGroup)> {
3236        match self {
3237            Self::Surface(_) => None,
3238            Self::Composition(composition) => output_view.map(|view| {
3239                (
3240                    view,
3241                    screenshot_bind_group.unwrap_or(&composition.output_bind_group),
3242                )
3243            }),
3244        }
3245    }
3246}
3247
3248/// What a presentable image must allow to be the frame's root target:
3249/// rendering, and the copies a capture and the opaque-prefix cache take of
3250/// the page and put back.
3251const DIRECT_SURFACE_ROOT_USAGES: wgpu::TextureUsages = wgpu::TextureUsages::RENDER_ATTACHMENT
3252    .union(wgpu::TextureUsages::COPY_SRC)
3253    .union(wgpu::TextureUsages::COPY_DST);
3254
3255/// The usages to ask of a presentable image: rendering, and whichever of
3256/// the copies and sampling the surface offers. Sampling lets a frame whose
3257/// backdrops read the page draw straight into the image too.
3258pub fn presentable_root_usages(supported: wgpu::TextureUsages) -> wgpu::TextureUsages {
3259    wgpu::TextureUsages::RENDER_ATTACHMENT
3260        | (supported & (DIRECT_SURFACE_ROOT_USAGES | wgpu::TextureUsages::TEXTURE_BINDING))
3261}
3262
3263/// Whether the presented image can be the frame's root target: its bytes
3264/// are the composition format (so the 8-bit output conversion would be an
3265/// identity), it is the viewport's size, it can be copied as the page is,
3266/// and it can be sampled when the frame `reads_page` through a backdrop.
3267/// Metal's images cannot be sampled, so only a frame without backdrops
3268/// draws straight into one there.
3269fn surface_is_direct_root(
3270    texture: &wgpu::Texture,
3271    composition_format: wgpu::TextureFormat,
3272    viewport: (u32, u32),
3273    reads_page: bool,
3274) -> bool {
3275    let usage = texture.usage();
3276    texture.format().remove_srgb_suffix() == composition_format
3277        && usage.contains(DIRECT_SURFACE_ROOT_USAGES)
3278        && (!reads_page || usage.contains(wgpu::TextureUsages::TEXTURE_BINDING))
3279        && (texture.width(), texture.height()) == viewport
3280}
3281
3282#[derive(Clone, Copy)]
3283enum OutputMode {
3284    Display,
3285    Screenshot,
3286}
3287
3288pub struct GpuRenderer {
3289    pub(crate) device: Arc<wgpu::Device>,
3290    pub(crate) queue: Arc<wgpu::Queue>,
3291    device_errors: Arc<DeviceErrorSentry>,
3292    renderer_epoch: u64,
3293    pub(crate) composition_format: wgpu::TextureFormat,
3294    #[cfg(not(target_arch = "wasm32"))]
3295    display_format: wgpu::TextureFormat,
3296    composition_target: Option<CompositionTarget>,
3297    output_converter: OutputConverter,
3298    screenshot_converter: OutputConverter,
3299    adapter_backend: wgpu::Backend,
3300    pipeline_cache: Option<wgpu::PipelineCache>,
3301    #[cfg(not(target_arch = "wasm32"))]
3302    _pipeline_cache_watcher: Option<crate::pipeline_disk_cache::PersistWatcher>,
3303    /// The pipelines recent launches of another build drew with, built once
3304    /// this renderer's first frame is drawn.
3305    #[cfg(not(target_arch = "wasm32"))]
3306    recent_after_update: Option<Arc<crate::pipeline_records::PipelineRecords>>,
3307    /// What this renderer draws with, for the next launches.
3308    recorder: crate::pipeline_recorder::PipelineRecorder,
3309    /// The background compiler, which builds a pass's missing pipelines side
3310    /// by side.
3311    pipeline_compiler: PipelineCompiler,
3312    /// Where the background compiler says a pipeline a placeholder waited
3313    /// for landed.
3314    #[cfg(not(target_arch = "wasm32"))]
3315    landing: Option<Arc<crate::pipeline_compiler::Landing>>,
3316    /// The pipelines the background threads had built when this frame
3317    /// started.
3318    #[cfg(not(target_arch = "wasm32"))]
3319    built_at_frame_start: u64,
3320    /// Whether this frame drew a placeholder in place of an effect whose
3321    /// pipelines were compiling.
3322    pub(crate) drew_placeholder: bool,
3323    shape_pipelines: ShapePipelines,
3324    /// Image and glyph pipelines for passes without and with a depth buffer.
3325    image_pipeline: [FixedPipeline; 8],
3326    image_pipeline_dst_out: [FixedPipeline; 8],
3327    /// Indexed by depth, then turned: see [`GpuRenderer::glyph_atlas_pipeline`].
3328    glyph_atlas_pipeline: [FixedPipeline; 6],
3329    /// Round rect shadow pipelines without and with a depth buffer.
3330    rrect_shadow_pipeline: [FixedPipeline; 2],
3331    image_shader: SharedShader,
3332    glyph_atlas_shader: SharedShader,
3333    rrect_shadow_shader: SharedShader,
3334    /// Transient depth buffers by target size, for passes that lay opaque
3335    /// interiors down first, dropped once no frame has used them for
3336    /// [`crate::idle_pool::IDLE_FRAMES`].
3337    depth_targets: crate::idle_pool::IdlePool<((u32, u32), wgpu::TextureView)>,
3338    pub(crate) depth_gate: crate::depth_gate::DepthGate,
3339    /// The size of the atlas the layer surfaces drawn again go into.
3340    pub(crate) surface_atlas_sizes: crate::frame::SurfaceAtlasSizes,
3341    uniform_bind_group_layout: wgpu::BindGroupLayout,
3342    image_bind_group_layout: wgpu::BindGroupLayout,
3343    image_nearest_sampler: wgpu::Sampler,
3344    image_linear_sampler: wgpu::Sampler,
3345    text_fonts: SoftwareTextFontSet,
3346    viewport_uniforms: ViewportUniforms,
3347    run_store: RunStore,
3348    image_texture_cache: BoundedLruCache<u64, CachedImageTexture>,
3349    image_texture_cache_bytes: usize,
3350    external_texture_bindings: BoundedLruCache<u64, ImageBindGroups>,
3351    text_image_cache: BoundedLruCache<TextImageCacheKey, CachedTextImage>,
3352    text_glyph_atlas: TextGlyphAtlas,
3353    text_glyph_run_cache: BoundedLruCache<TextGlyphRunCacheKey, CachedTextGlyphRun>,
3354    text_glyph_gpu_run_cache: BoundedLruCache<TextGlyphRunCacheKey, Rc<CachedGpuTextGlyphRun>>,
3355    text_glyph_run_arena: GlyphRunArena,
3356    /// How run tables and retained glyph runs reach the GPU, and whether
3357    /// kept layer surfaces stay in their atlas: see [`UploadMode::copy_free`].
3358    pub(crate) copy_free: UploadMode,
3359    text_glyph_run_frame: u64,
3360    /// Text runs the frame has drawn so far, cached or not.
3361    text_glyph_runs_drawn: usize,
3362    text_glyph_mask_cache: SoftwareGlyphRasterCache,
3363    text_line_index_cache: TextLineIndexCache,
3364    pub(crate) scratch_image_vertices: Vec<Vertex>,
3365    pub(crate) scratch_image_indices: Vec<u32>,
3366    pub(crate) scratch_glyph_instances: GlyphInstances,
3367    pub(crate) scratch_image_cmds: Vec<ImageDrawCmd>,
3368    pub(crate) scratch_image_clips: Vec<DeviceRoundedClip>,
3369    pub(crate) scratch_glyph_cmds: Vec<GlyphDrawCmd>,
3370    pub(crate) scratch_glyph_moved: Vec<GlyphDrawCmd>,
3371    pub(crate) scratch_shadow_instances: Vec<ShadowInstance>,
3372    pub(crate) scratch_arena_draws: Vec<RunDrawCall>,
3373    pub(crate) scratch_pipelines: PipelineDemand,
3374    pub(crate) scratch_held: crate::draw_pass::HeldDraws,
3375    scratch_text_glyph_run: Vec<SoftwareGlyphAtlasRunGlyph>,
3376    scratch_text_glyph_entries: Vec<GlyphAtlasEntry>,
3377    run_glyph_scratch: RunGlyphScratch,
3378    frame_graph_executor: WgpuFrameGraphExecutor,
3379    pub(crate) stage_side_scratch: StageSideScratch,
3380    deferred_offscreen_releases: Vec<OffscreenTarget>,
3381    pub(crate) effect_renderer: EffectRenderer,
3382    pub(crate) layer_cache: LayerCache,
3383    pub(crate) ablation: Ablation,
3384    pub(crate) ablation_frames: u32,
3385    pub(crate) nesting_overflow_reported: bool,
3386    pub(crate) backdrop_gates: HashMap<NodeId, AdmissionGate>,
3387    pub(crate) fill_gates: HashMap<DrawCommandId, AdmissionGate>,
3388    pub(crate) effect_gates: HashMap<NodeId, AdmissionGate>,
3389    pub(crate) source_gates: HashMap<NodeId, AdmissionGate>,
3390    transparent_sources: HashMap<(u32, u32), Rc<OffscreenTarget>>,
3391    shadow_surface_cache: BoundedLruCache<ShadowSurfaceCacheKey, CachedShadowSurface>,
3392    shadow_surface_cache_bytes: u64,
3393    pub(crate) frame_stats: gpu_stats::FrameStats,
3394    last_frame_stats: Option<gpu_stats::FrameStatsSnapshot>,
3395    pending_frame_warmup_frames: u8,
3396    frame_count: u64,
3397    /// How many requested shader warm-ups this renderer has queued.
3398    shader_warm_ups_queued: usize,
3399}
3400
3401/// What a frame clears to before it draws: nothing for a transparent
3402/// window, the framework's background for every other surface.
3403pub fn frame_clear_color(transparent: bool) -> wgpu::Color {
3404    if transparent {
3405        wgpu::Color::TRANSPARENT
3406    } else {
3407        CLEAR_COLOR
3408    }
3409}
3410
3411fn image_sampler_descriptor(sampling: ImageSampling) -> wgpu::SamplerDescriptor<'static> {
3412    let filter = match sampling {
3413        ImageSampling::Nearest => wgpu::FilterMode::Nearest,
3414        ImageSampling::Linear => wgpu::FilterMode::Linear,
3415    };
3416    wgpu::SamplerDescriptor {
3417        label: Some(match sampling {
3418            ImageSampling::Nearest => "Nearest Image Sampler",
3419            ImageSampling::Linear => "Linear Image Sampler",
3420        }),
3421        address_mode_u: wgpu::AddressMode::ClampToEdge,
3422        address_mode_v: wgpu::AddressMode::ClampToEdge,
3423        address_mode_w: wgpu::AddressMode::ClampToEdge,
3424        mag_filter: filter,
3425        min_filter: filter,
3426        mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3427        ..Default::default()
3428    }
3429}
3430
3431/// What a [`GpuRenderer`] is built from. It crosses to the present thread
3432/// whole, so it holds only owned, `Send` parts.
3433pub(crate) struct GpuRendererInit {
3434    pub(crate) device: Arc<wgpu::Device>,
3435    pub(crate) queue: Arc<wgpu::Queue>,
3436    pub(crate) surface_format: wgpu::TextureFormat,
3437    pub(crate) adapter_backend: wgpu::Backend,
3438    pub(crate) adapter_downlevel: wgpu::DownlevelFlags,
3439    pub(crate) text_fonts: SoftwareTextFontSet,
3440    pub(crate) renderer_epoch: u64,
3441    pub(crate) pipeline_compilation: PipelineCompilation,
3442}
3443
3444impl GpuRenderer {
3445    pub fn new(init: GpuRendererInit) -> Self {
3446        let GpuRendererInit {
3447            device,
3448            queue,
3449            surface_format,
3450            adapter_backend,
3451            adapter_downlevel,
3452            text_fonts,
3453            renderer_epoch,
3454            pipeline_compilation,
3455        } = init;
3456        let display_format = surface_format;
3457        let construction_started = Instant::now();
3458        let device_errors = Arc::new(DeviceErrorSentry::default());
3459        if survive_gpu_errors_enabled() {
3460            let sentry = Arc::clone(&device_errors);
3461            device.on_uncaptured_error(Arc::new(move |error| sentry.record(&error)));
3462        }
3463        let composition_format = crate::offscreen::composition_format(display_format);
3464        device.set_device_lost_callback(|reason, message| {
3465            log::error!("[gpu-device] device lost ({reason:?}): {message}");
3466        });
3467        let copy_free = UploadMode::copy_free(&device, adapter_backend);
3468        let mut run_store = RunStore::new(
3469            &device,
3470            RunBufferMode::for_device(&device, adapter_downlevel),
3471            copy_free,
3472        );
3473        let uniform_bind_group_layout =
3474            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3475                label: Some("Viewport Uniform Bind Group Layout"),
3476                entries: &[wgpu::BindGroupLayoutEntry {
3477                    binding: 0,
3478                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3479                    ty: wgpu::BindingType::Buffer {
3480                        ty: wgpu::BufferBindingType::Uniform,
3481                        has_dynamic_offset: true,
3482                        min_binding_size: wgpu::BufferSize::new(
3483                            std::mem::size_of::<Uniforms>() as u64
3484                        ),
3485                    },
3486                    count: None,
3487                }],
3488            });
3489        let image_bind_group_layout =
3490            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3491                label: Some("Image Texture Bind Group Layout"),
3492                entries: &[
3493                    wgpu::BindGroupLayoutEntry {
3494                        binding: 0,
3495                        visibility: wgpu::ShaderStages::FRAGMENT,
3496                        ty: wgpu::BindingType::Texture {
3497                            multisampled: false,
3498                            view_dimension: wgpu::TextureViewDimension::D2,
3499                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
3500                        },
3501                        count: None,
3502                    },
3503                    wgpu::BindGroupLayoutEntry {
3504                        binding: 1,
3505                        visibility: wgpu::ShaderStages::FRAGMENT,
3506                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3507                        count: None,
3508                    },
3509                ],
3510            });
3511        let image_nearest_sampler =
3512            device.create_sampler(&image_sampler_descriptor(ImageSampling::Nearest));
3513        let image_linear_sampler =
3514            device.create_sampler(&image_sampler_descriptor(ImageSampling::Linear));
3515        let text_glyph_atlas = TextGlyphAtlas::new(
3516            &device,
3517            &image_bind_group_layout,
3518            GlyphSamplers {
3519                nearest: &image_nearest_sampler,
3520                linear: &image_linear_sampler,
3521            },
3522            TEXT_GLYPH_ATLAS_MIN_SIZE,
3523        );
3524        let viewport_uniforms = ViewportUniforms::default();
3525
3526        static GLASS_MATERIAL_FOLDS: DebugToggle =
3527            DebugToggle::new("CRANPOSE_GLASS_MATERIAL_FOLDS");
3528        if GLASS_MATERIAL_FOLDS.equals("1") {
3529            cranpose_ui_graphics::set_glass_material_folds(true);
3530        } else if GLASS_MATERIAL_FOLDS.equals("0") {
3531            cranpose_ui_graphics::set_glass_material_folds(false);
3532        }
3533        log::info!(
3534            "[gpu-init] liquid glass material folds {}",
3535            if cranpose_ui_graphics::glass_material_folds_enabled() {
3536                "on: a pipeline per material's feature set"
3537            } else {
3538                "off: one pipeline per blend mode"
3539            }
3540        );
3541
3542        #[cfg(not(target_arch = "wasm32"))]
3543        let crate::pipeline_disk_cache::Loaded {
3544            cache: pipeline_cache,
3545            records,
3546            updated,
3547            holds_recorded,
3548        } = crate::pipeline_disk_cache::load(&device);
3549        #[cfg(not(target_arch = "wasm32"))]
3550        let first_screen: Vec<u64> = records
3551            .shapes
3552            .iter()
3553            .filter(|shape| shape.first_screen)
3554            .map(|shape| shape.entry)
3555            .collect();
3556        #[cfg(target_arch = "wasm32")]
3557        let (pipeline_cache, first_screen): (Option<wgpu::PipelineCache>, Vec<u64>) =
3558            (None, Vec::new());
3559        let recorder = crate::pipeline_recorder::PipelineRecorder::default();
3560        #[cfg(not(target_arch = "wasm32"))]
3561        let pipeline_cache_watcher = crate::pipeline_disk_cache::spawn_persist_watcher(
3562            pipeline_cache.clone(),
3563            Arc::clone(&records),
3564            recorder.clone(),
3565        );
3566
3567        let effects_started = Instant::now();
3568        let pipeline_compiler = PipelineCompiler::for_compilation(pipeline_compilation);
3569        let depth_gate = crate::depth_gate::DepthGate::new(
3570            crate::draw_pass::lays_interiors_first(adapter_backend),
3571            pipeline_compiler.is_active(),
3572        );
3573        let effect_renderer = EffectRenderer::new(
3574            &device,
3575            pipeline_compiler.clone(),
3576            pipeline_cache.clone(),
3577            composition_format,
3578            adapter_backend,
3579            recorder.clone(),
3580        );
3581        let output_converter = OutputConverter::new(&device, adapter_backend, display_format);
3582        let screenshot_converter =
3583            OutputConverter::new(&device, adapter_backend, wgpu::TextureFormat::Rgba8Unorm);
3584        let effects_ms = instant_ms(effects_started, Instant::now());
3585        let mut frame_graph_executor = WgpuFrameGraphExecutor::new();
3586        frame_graph_executor.init_pass_timing(&device, &queue);
3587        #[cfg(target_arch = "wasm32")]
3588        frame_graph_executor.batch_queue_writes(adapter_backend == wgpu::Backend::BrowserWebGpu);
3589        let shape_shader = SharedShader::new(
3590            &device,
3591            adapter_backend,
3592            "Shape Shader",
3593            shape_shader_code(run_store.mode()),
3594            &[Some(&uniform_bind_group_layout), Some(run_store.layout())],
3595        );
3596        if run_store.mode().trig_fill {
3597            let fill = ArcTrigFill::new(
3598                &device,
3599                adapter_backend,
3600                pipeline_cache.clone(),
3601                shape_shader.clone(),
3602                recorder.clone(),
3603            );
3604            if first_screen.contains(&crate::arc_trig_fill::FIRST_SCREEN_KEY) {
3605                fill.warm(&pipeline_compiler);
3606            }
3607            run_store.attach_trig_fill(fill);
3608        }
3609        let shape_pipelines = ShapePipelines::new(
3610            ShapePipelineFactory {
3611                device: Arc::clone(&device),
3612                cache: pipeline_cache.clone(),
3613                format: composition_format,
3614                shader: shape_shader,
3615                mode: run_store.mode(),
3616            },
3617            adapter_backend,
3618            &pipeline_compiler,
3619            first_screen
3620                .into_iter()
3621                .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3622                .filter_map(ShapePipelineKey::from_bits),
3623            recorder.clone(),
3624        );
3625        let image_layouts = [
3626            Some(&uniform_bind_group_layout),
3627            Some(&image_bind_group_layout),
3628        ];
3629        let image_shader = SharedShader::new(
3630            &device,
3631            adapter_backend,
3632            "Image Shader",
3633            shaders::IMAGE,
3634            &image_layouts,
3635        );
3636        let glyph_atlas_shader = SharedShader::new(
3637            &device,
3638            adapter_backend,
3639            "Glyph Atlas Shader",
3640            shaders::GLYPH_ATLAS,
3641            &image_layouts,
3642        );
3643        let rrect_shadow_shader = SharedShader::new(
3644            &device,
3645            adapter_backend,
3646            "Round Rect Shadow Shader",
3647            shaders::RRECT_SHADOW,
3648            &[Some(&uniform_bind_group_layout)],
3649        );
3650
3651        let mut renderer = Self {
3652            device,
3653            queue,
3654            device_errors,
3655            renderer_epoch,
3656            composition_format,
3657            #[cfg(not(target_arch = "wasm32"))]
3658            display_format,
3659            composition_target: None,
3660            output_converter,
3661            screenshot_converter,
3662            adapter_backend,
3663            pipeline_cache,
3664            #[cfg(not(target_arch = "wasm32"))]
3665            _pipeline_cache_watcher: pipeline_cache_watcher,
3666            #[cfg(not(target_arch = "wasm32"))]
3667            recent_after_update: updated.then(|| Arc::clone(&records)),
3668            recorder,
3669            #[cfg(not(target_arch = "wasm32"))]
3670            landing: pipeline_compiler.landing(),
3671            pipeline_compiler,
3672            #[cfg(not(target_arch = "wasm32"))]
3673            built_at_frame_start: 0,
3674            drew_placeholder: false,
3675            shape_pipelines,
3676            image_pipeline: [
3677                FixedPipeline::new("image/src-over"),
3678                FixedPipeline::new("image/src-over/depth"),
3679                FixedPipeline::new("image/src-over/alpha-mask"),
3680                FixedPipeline::new("image/src-over/alpha-mask/depth"),
3681                FixedPipeline::new("image/src-over/rounded"),
3682                FixedPipeline::new("image/src-over/rounded/depth"),
3683                FixedPipeline::new("image/src-over/alpha-mask/rounded"),
3684                FixedPipeline::new("image/src-over/alpha-mask/rounded/depth"),
3685            ],
3686            image_pipeline_dst_out: [
3687                FixedPipeline::new("image/dst-out"),
3688                FixedPipeline::new("image/dst-out/depth"),
3689                FixedPipeline::new("image/dst-out/alpha-mask"),
3690                FixedPipeline::new("image/dst-out/alpha-mask/depth"),
3691                FixedPipeline::new("image/dst-out/rounded"),
3692                FixedPipeline::new("image/dst-out/rounded/depth"),
3693                FixedPipeline::new("image/dst-out/alpha-mask/rounded"),
3694                FixedPipeline::new("image/dst-out/alpha-mask/rounded/depth"),
3695            ],
3696            glyph_atlas_pipeline: [
3697                FixedPipeline::new("glyph/atlas"),
3698                FixedPipeline::new("glyph/atlas/depth"),
3699                FixedPipeline::new("glyph/atlas/aligned"),
3700                FixedPipeline::new("glyph/atlas/aligned/depth"),
3701                FixedPipeline::new("glyph/atlas/turned"),
3702                FixedPipeline::new("glyph/atlas/turned/depth"),
3703            ],
3704            rrect_shadow_pipeline: [
3705                FixedPipeline::new("shadow/rrect"),
3706                FixedPipeline::new("shadow/rrect/depth"),
3707            ],
3708            image_shader,
3709            glyph_atlas_shader,
3710            rrect_shadow_shader,
3711            depth_targets: crate::idle_pool::IdlePool::default(),
3712            depth_gate,
3713            surface_atlas_sizes: crate::frame::SurfaceAtlasSizes::for_backend(adapter_backend),
3714            uniform_bind_group_layout,
3715            image_bind_group_layout,
3716            image_nearest_sampler,
3717            image_linear_sampler,
3718            text_fonts,
3719            viewport_uniforms,
3720            run_store,
3721            image_texture_cache: BoundedLruCache::with_capacity_at_least_one(
3722                MAX_TEXTURE_CACHE_ITEMS,
3723            ),
3724            image_texture_cache_bytes: 0,
3725            external_texture_bindings: BoundedLruCache::with_capacity_at_least_one(
3726                MAX_EXTERNAL_TEXTURE_BINDINGS,
3727            ),
3728            text_image_cache: BoundedLruCache::with_capacity_at_least_one(
3729                MAX_TEXT_IMAGE_CACHE_ITEMS,
3730            ),
3731            text_glyph_atlas,
3732            text_glyph_run_cache: BoundedLruCache::with_capacity_at_least_one(
3733                MIN_TEXT_GLYPH_RUN_CACHE_ITEMS,
3734            ),
3735            text_glyph_runs_drawn: 0,
3736            text_glyph_gpu_run_cache: BoundedLruCache::with_capacity_at_least_one(
3737                MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS,
3738            ),
3739            text_glyph_run_arena: GlyphRunArena::new(copy_free),
3740            copy_free,
3741            text_glyph_run_frame: 0,
3742            text_glyph_mask_cache: SoftwareGlyphRasterCache::with_capacity_at_least_one(
3743                MAX_TEXT_GLYPH_MASK_CACHE_ITEMS,
3744            ),
3745            text_line_index_cache: TextLineIndexCache::new(MAX_TEXT_LINE_INDEX_CACHE_ITEMS),
3746            scratch_image_vertices: Vec::new(),
3747            scratch_image_indices: Vec::new(),
3748            scratch_glyph_instances: GlyphInstances::default(),
3749            scratch_image_cmds: Vec::new(),
3750            scratch_image_clips: Vec::new(),
3751            scratch_glyph_cmds: Vec::new(),
3752            scratch_glyph_moved: Vec::new(),
3753            scratch_shadow_instances: Vec::new(),
3754            scratch_arena_draws: Vec::new(),
3755            scratch_pipelines: PipelineDemand::default(),
3756            scratch_held: crate::draw_pass::HeldDraws::default(),
3757            scratch_text_glyph_run: Vec::new(),
3758            scratch_text_glyph_entries: Vec::new(),
3759            run_glyph_scratch: RunGlyphScratch::default(),
3760            frame_graph_executor,
3761            stage_side_scratch: StageSideScratch::default(),
3762            deferred_offscreen_releases: Vec::new(),
3763            effect_renderer,
3764            layer_cache: LayerCache::new(),
3765            ablation: Ablation::default(),
3766            ablation_frames: 0,
3767            nesting_overflow_reported: false,
3768            backdrop_gates: HashMap::default(),
3769            fill_gates: HashMap::default(),
3770            effect_gates: HashMap::default(),
3771            source_gates: HashMap::default(),
3772            transparent_sources: HashMap::default(),
3773            shadow_surface_cache: BoundedLruCache::with_capacity_at_least_one(
3774                MAX_SHADOW_SURFACE_CACHE_ITEMS,
3775            ),
3776            shadow_surface_cache_bytes: 0,
3777            frame_stats: gpu_stats::FrameStats::default(),
3778            last_frame_stats: None,
3779            pending_frame_warmup_frames: 0,
3780            frame_count: 0,
3781            shader_warm_ups_queued: 0,
3782        };
3783        #[cfg(not(target_arch = "wasm32"))]
3784        renderer.warm_first_screen(&records, holds_recorded);
3785        renderer.warm_requested_shaders();
3786        log::info!(
3787            "[gpu-init] {:?} renderer ready in {:.1} ms (effects {:.1} ms)",
3788            adapter_backend,
3789            instant_ms(construction_started, Instant::now()),
3790            effects_ms,
3791        );
3792        renderer
3793    }
3794
3795    /// Prepares the first screen the last launches recorded. The first frame
3796    /// waits for its shapes and fixed pipelines, but draws placeholders for
3797    /// runtime shaders that have not compiled: those queue behind, since a
3798    /// Mali driver compiles largely one pipeline at a time. A driver cache
3799    /// that `holds_recorded` pipelines builds them as cache hits, so those
3800    /// draw from it, and need no stand-in.
3801    #[cfg(not(target_arch = "wasm32"))]
3802    fn warm_first_screen(
3803        &mut self,
3804        records: &crate::pipeline_records::PipelineRecords,
3805        holds_recorded: bool,
3806    ) {
3807        self.warm_fixed_pipelines(&|label| {
3808            records
3809                .fixed
3810                .iter()
3811                .any(|fixed| fixed.first_screen && fixed.entry == label)
3812        });
3813        if holds_recorded {
3814            self.effect_renderer.trust_cached(records);
3815        }
3816        self.effect_renderer.warm_first_screen_shaders(
3817            records
3818                .shaders
3819                .iter()
3820                .filter(|shader| shader.first_screen)
3821                .map(|shader| &shader.entry),
3822        );
3823        if !records.shapes.iter().any(|shape| shape.first_screen) {
3824            self.warm_every_screen();
3825        }
3826    }
3827
3828    /// Queues the pipelines every screen draws with, for a launch with no
3829    /// record of its first screen: flat solid rects and text on whole
3830    /// pixels. They build while the first screen composes, when the
3831    /// compiler's threads have nothing else; on a Mate 20 X the gauntlet's
3832    /// first content showed 333-366 ms after the first frame with them
3833    /// against 383-399 ms without.
3834    #[cfg(not(target_arch = "wasm32"))]
3835    fn warm_every_screen(&mut self) {
3836        self.shape_pipelines.warm(ShapePipelineKey::SOLID_RECT);
3837        self.glyph_atlas_pipeline_resource(false, GlyphQuads::Aligned)
3838            .prefetch(
3839                CompileLane::WarmUp,
3840                &self.pipeline_compiler,
3841                self.adapter_backend,
3842                || self.glyph_atlas_pipeline_job(false, GlyphQuads::Aligned),
3843            );
3844    }
3845
3846    fn ensure_shape_pipeline(&mut self, key: ShapePipelineKey, vertices: u64) {
3847        self.shape_pipelines.ensure(key, vertices);
3848    }
3849
3850    /// Queues the shader warm-ups requested since the last call, each at the
3851    /// target it draws to (`cranpose_ui_graphics::request_shader_warm_ups`).
3852    fn warm_requested_shaders(&mut self) {
3853        let requested = cranpose_ui_graphics::shader_warm_ups_after(self.shader_warm_ups_queued);
3854        if requested.is_empty() {
3855            return;
3856        }
3857        self.shader_warm_ups_queued += requested.len();
3858        self.effect_renderer.warm_shaders(&requested);
3859    }
3860
3861    /// Queues every pipeline recent launches of another build drew with:
3862    /// after an update their compiled pipelines are gone, and each would
3863    /// otherwise compile inside the first frame that draws with it.
3864    #[cfg(not(target_arch = "wasm32"))]
3865    fn warm_recent(&mut self, records: &crate::pipeline_records::PipelineRecords) {
3866        self.warm_fixed_pipelines(&|label| records.fixed.iter().any(|fixed| fixed.entry == label));
3867        let shapes = records
3868            .shapes
3869            .iter()
3870            .map(|shape| shape.entry)
3871            .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3872            .filter_map(ShapePipelineKey::from_bits);
3873        for key in shapes {
3874            self.shape_pipelines.warm(key);
3875        }
3876        self.effect_renderer
3877            .warm_recorded_shaders(records.shaders.iter().map(|shader| &shader.entry));
3878    }
3879
3880    /// Queues the fixed pipelines whose labels `wanted` accepts.
3881    #[cfg(not(target_arch = "wasm32"))]
3882    fn warm_fixed_pipelines(&self, wanted: &dyn Fn(&str) -> bool) {
3883        let compiler = self.effect_renderer.compiler();
3884        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3885            if wanted(pipeline.label()) {
3886                pipeline.queue(
3887                    compiler,
3888                    crate::pipeline_compiler::CompileLane::WarmUp,
3889                    self.adapter_backend,
3890                    job(),
3891                );
3892            }
3893        });
3894    }
3895
3896    /// Builds here, ahead of the first frame, the pipelines named by the
3897    /// first screens in `records` that this renderer's backend drew (see
3898    /// [`crate::WgpuRenderer::build_first_screen_pipelines`]).
3899    pub(crate) fn build_first_screen(&mut self, records: &[u8]) {
3900        let records = crate::pipeline_records::decode_first_screens(records, self.adapter_backend);
3901        for shape in &records.shapes {
3902            if let Some(key) = ShapePipelineKey::from_bits(shape.entry) {
3903                self.shape_pipelines.build_ahead(key);
3904            }
3905        }
3906        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3907            if records
3908                .fixed
3909                .iter()
3910                .any(|fixed| fixed.entry == pipeline.label())
3911            {
3912                pipeline.build_ahead(&self.recorder, self.adapter_backend, job());
3913            }
3914        });
3915    }
3916
3917    /// See [`crate::WgpuRenderer::first_screen_pipelines`].
3918    #[cold]
3919    #[inline(never)]
3920    pub(crate) fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
3921        self.recorder.first_screen_records(self.adapter_backend)
3922    }
3923
3924    /// Hands `visit` every fixed pipeline, the effect renderer's too, with
3925    /// the job that builds it.
3926    fn for_each_fixed_pipeline(
3927        &self,
3928        visit: &mut dyn FnMut(&FixedPipeline, &dyn Fn() -> FixedPipelineJob),
3929    ) {
3930        self.effect_renderer.for_each_fixed(&self.device, visit);
3931        for depth in [false, true] {
3932            for (alpha_mask, rounded) in
3933                [(false, false), (true, false), (false, true), (true, true)]
3934            {
3935                let variant = ImageVariant {
3936                    depth,
3937                    alpha_mask,
3938                    rounded,
3939                };
3940                for blend_mode in [BlendMode::SrcOver, BlendMode::DstOut] {
3941                    visit(self.image_pipeline_resource(blend_mode, variant), &|| {
3942                        Box::new(self.image_pipeline_job(blend_mode, variant))
3943                    });
3944                }
3945            }
3946            for quads in [GlyphQuads::Plain, GlyphQuads::Aligned, GlyphQuads::Turned] {
3947                visit(self.glyph_atlas_pipeline_resource(depth, quads), &|| {
3948                    Box::new(self.glyph_atlas_pipeline_job(depth, quads))
3949                });
3950            }
3951            visit(&self.rrect_shadow_pipeline[usize::from(depth)], &|| {
3952                Box::new(self.rrect_shadow_pipeline_job(depth))
3953            });
3954        }
3955    }
3956
3957    fn image_pipeline_resource(
3958        &self,
3959        blend_mode: BlendMode,
3960        variant: ImageVariant,
3961    ) -> &FixedPipeline {
3962        let pipelines = match blend_mode {
3963            BlendMode::DstOut => &self.image_pipeline_dst_out,
3964            _ => &self.image_pipeline,
3965        };
3966        &pipelines[usize::from(variant.depth)
3967            + 2 * usize::from(variant.alpha_mask)
3968            + 4 * usize::from(variant.rounded)]
3969    }
3970
3971    fn image_pipeline_job(
3972        &self,
3973        blend_mode: BlendMode,
3974        variant: ImageVariant,
3975    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3976        let device = Arc::clone(&self.device);
3977        let cache = self.pipeline_cache.clone();
3978        let format = self.composition_format;
3979        let shader = self.image_shader.clone();
3980        move || {
3981            create_image_pipeline(
3982                &device,
3983                cache.as_ref(),
3984                format,
3985                &shader,
3986                blend_mode,
3987                variant,
3988            )
3989        }
3990    }
3991
3992    /// Queues the builds of the image pipelines `cmds` draw with that are
3993    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
3994    /// `awaited` each still to land.
3995    pub(crate) fn prefetch_image_pipelines(
3996        &self,
3997        cmds: &[ImageDrawCmd],
3998        blend_mode: BlendMode,
3999        (depth, lane): (bool, CompileLane),
4000        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4001    ) {
4002        let mut last = None;
4003        for cmd in cmds {
4004            let variant = ImageVariant::of(cmd, depth);
4005            if last.replace(variant) == Some(variant) {
4006                continue;
4007            }
4008            if let Some(pending) = self.image_pipeline_resource(blend_mode, variant).prefetch(
4009                lane,
4010                &self.pipeline_compiler,
4011                self.adapter_backend,
4012                || self.image_pipeline_job(blend_mode, variant),
4013            ) {
4014                awaited(pending);
4015            }
4016        }
4017    }
4018
4019    /// Queues the builds of the glyph pipelines `cmds` draw with that are
4020    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4021    /// `awaited` each still to land.
4022    pub(crate) fn prefetch_glyph_pipelines(
4023        &self,
4024        cmds: &[GlyphDrawCmd],
4025        (depth, lane): (bool, CompileLane),
4026        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4027    ) {
4028        let mut last = None;
4029        for cmd in cmds {
4030            let quads = cmd.quads();
4031            if last.replace(quads) == Some(quads) {
4032                continue;
4033            }
4034            if let Some(pending) = self.glyph_atlas_pipeline_resource(depth, quads).prefetch(
4035                lane,
4036                &self.pipeline_compiler,
4037                self.adapter_backend,
4038                || self.glyph_atlas_pipeline_job(depth, quads),
4039            ) {
4040                awaited(pending);
4041            }
4042        }
4043    }
4044
4045    /// Queues the build of the shadow pipeline on `lane` when it is missing
4046    /// (see [`FixedPipeline::prefetch`]), handing `awaited` the pipeline
4047    /// while it is still to land.
4048    pub(crate) fn prefetch_shadow_pipeline(
4049        &self,
4050        (depth, lane): (bool, CompileLane),
4051        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4052    ) {
4053        if let Some(pending) = self.rrect_shadow_pipeline[usize::from(depth)].prefetch(
4054            lane,
4055            &self.pipeline_compiler,
4056            self.adapter_backend,
4057            || self.rrect_shadow_pipeline_job(depth),
4058        ) {
4059            awaited(pending);
4060        }
4061    }
4062
4063    pub(crate) fn image_pipeline(
4064        &self,
4065        blend_mode: BlendMode,
4066        variant: ImageVariant,
4067    ) -> &wgpu::RenderPipeline {
4068        self.image_pipeline_resource(blend_mode, variant).for_draw(
4069            &self.recorder,
4070            self.adapter_backend,
4071            || self.image_pipeline_job(blend_mode, variant)(),
4072        )
4073    }
4074
4075    fn glyph_atlas_pipeline_job(
4076        &self,
4077        depth: bool,
4078        quads: GlyphQuads,
4079    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4080        let device = Arc::clone(&self.device);
4081        let cache = self.pipeline_cache.clone();
4082        let format = self.composition_format;
4083        let shader = self.glyph_atlas_shader.clone();
4084        move || {
4085            create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
4086        }
4087    }
4088
4089    /// The glyph pipeline for a pass with a depth buffer or not, drawing
4090    /// `quads`.
4091    fn glyph_atlas_pipeline(&self, depth: bool, quads: GlyphQuads) -> &wgpu::RenderPipeline {
4092        self.glyph_atlas_pipeline_resource(depth, quads).for_draw(
4093            &self.recorder,
4094            self.adapter_backend,
4095            || self.glyph_atlas_pipeline_job(depth, quads)(),
4096        )
4097    }
4098
4099    fn rrect_shadow_pipeline_job(
4100        &self,
4101        depth: bool,
4102    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4103        let device = Arc::clone(&self.device);
4104        let cache = self.pipeline_cache.clone();
4105        let format = self.composition_format;
4106        let shader = self.rrect_shadow_shader.clone();
4107        move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
4108    }
4109
4110    /// Draws `instances` of the pass's uploaded shadow instances, bound with
4111    /// `uniform_slot` under `scissor`.
4112    pub(crate) fn draw_shadow_instances(
4113        &self,
4114        pass: &mut TrackedPass<'_, '_>,
4115        buffer: &BufferUpload,
4116        uniform_slot: usize,
4117        instances: std::ops::Range<u32>,
4118        scissor: Option<(u32, u32, u32, u32)>,
4119        frame: PassFrame,
4120    ) -> Result<(), String> {
4121        let depth = frame.depth;
4122        let pipeline = self.rrect_shadow_pipeline[usize::from(depth)].for_draw(
4123            &self.recorder,
4124            self.adapter_backend,
4125            || self.rrect_shadow_pipeline_job(depth)(),
4126        );
4127        let (x, y, width, height) = frame.scissor(scissor);
4128        pass.set_scissor_rect(x, y, width, height);
4129        pass.set_pipeline(pipeline);
4130        self.viewport_uniforms.bind(pass, uniform_slot)?;
4131        pass.set_vertex_buffer(0, buffer.slice());
4132        pass.draw(0..SHADOW_QUAD_CORNERS, instances);
4133        self.frame_stats.add_draw_calls(1);
4134        Ok(())
4135    }
4136
4137    pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
4138        &self,
4139        recorder: &mut C,
4140        instances: &[ShadowInstance],
4141    ) -> BufferUpload {
4142        recorder.upload_buffer(
4143            UploadAllocatorSpec::vertex(
4144                "Shadow Instance Buffer",
4145                std::mem::size_of::<ShadowInstance>() as u64,
4146            ),
4147            &self.device,
4148            bytemuck::cast_slice(instances),
4149        )
4150    }
4151
4152    fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
4153        let kind = match quads {
4154            GlyphQuads::Plain => 0,
4155            GlyphQuads::Aligned => 1,
4156            GlyphQuads::Turned => 2,
4157        };
4158        &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
4159    }
4160
4161    /// The transient depth buffer for a target of `size`, created on first
4162    /// use; the few sizes recent frames used are kept.
4163    pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
4164        const KEPT_DEPTH_TARGETS: usize = 4;
4165        let view = match self.depth_targets.take(|(kept, _)| *kept == size) {
4166            Some((_, view)) => view,
4167            None => self.create_depth_target(size),
4168        };
4169        self.depth_targets
4170            .put((size, view.clone()), KEPT_DEPTH_TARGETS, u64::MAX, |_| 0);
4171        view
4172    }
4173
4174    fn create_depth_target(&self, size: (u32, u32)) -> wgpu::TextureView {
4175        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4176            label: Some("Opaque interior depth"),
4177            size: wgpu::Extent3d {
4178                width: size.0,
4179                height: size.1,
4180                depth_or_array_layers: 1,
4181            },
4182            mip_level_count: 1,
4183            sample_count: 1,
4184            dimension: wgpu::TextureDimension::D2,
4185            format: DEPTH_FORMAT,
4186            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4187                | wgpu::TextureUsages::TRANSIENT_ATTACHMENT,
4188            view_formats: &[],
4189        });
4190        texture.create_view(&wgpu::TextureViewDescriptor::default())
4191    }
4192
4193    /// The binding a draw of `image` sampled by `sampling` takes, uploading
4194    /// the image the first time a draw needs it.
4195    fn image_binding(
4196        &mut self,
4197        image: &ImageBitmap,
4198        sampling: ImageSampling,
4199    ) -> Result<ImageBinding, String> {
4200        if image.format() == cranpose_ui_graphics::ImagePixelFormat::External {
4201            return self.external_texture_binding(image, sampling);
4202        }
4203        if let Some(cached) = self.image_texture_cache.get(&image.id()) {
4204            return Ok(cached.bind_groups.binding(sampling));
4205        }
4206
4207        let size = wgpu::Extent3d {
4208            width: image.width(),
4209            height: image.height(),
4210            depth_or_array_layers: 1,
4211        };
4212
4213        let alpha_mask = matches!(
4214            image.format(),
4215            cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
4216        );
4217        let (format, bytes_per_pixel) = if alpha_mask {
4218            (wgpu::TextureFormat::R8Unorm, 1)
4219        } else {
4220            (wgpu::TextureFormat::Rgba8Unorm, 4)
4221        };
4222
4223        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4224            label: Some("Image Texture"),
4225            size,
4226            mip_level_count: 1,
4227            sample_count: 1,
4228            dimension: wgpu::TextureDimension::D2,
4229            format,
4230            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4231            view_formats: &[],
4232        });
4233
4234        let upload_stats = self.frame_graph_executor.upload_texture(
4235            &self.queue,
4236            wgpu::TexelCopyTextureInfo {
4237                texture: &texture,
4238                mip_level: 0,
4239                origin: wgpu::Origin3d::ZERO,
4240                aspect: wgpu::TextureAspect::All,
4241            },
4242            image.pixels(),
4243            wgpu::TexelCopyBufferLayout {
4244                offset: 0,
4245                bytes_per_row: Some(bytes_per_pixel * image.width()),
4246                rows_per_image: Some(image.height()),
4247            },
4248            size,
4249        );
4250        self.frame_stats.record_command_stats(upload_stats);
4251
4252        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4253        let bytes = image.pixels().len();
4254        let cached = CachedImageTexture {
4255            bind_groups: self.image_bind_groups(&view, alpha_mask),
4256            _texture: texture,
4257            _view: view,
4258            bytes,
4259        };
4260        let binding = cached.bind_groups.binding(sampling);
4261        if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
4262            self.image_texture_cache_bytes = self
4263                .image_texture_cache_bytes
4264                .saturating_sub(replaced.bytes);
4265        }
4266        self.image_texture_cache_bytes += bytes;
4267        while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
4268            && self.image_texture_cache.len() > 1
4269        {
4270            let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
4271                break;
4272            };
4273            self.image_texture_cache_bytes =
4274                self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
4275        }
4276        Ok(binding)
4277    }
4278
4279    fn external_texture_binding(
4280        &mut self,
4281        image: &ImageBitmap,
4282        sampling: ImageSampling,
4283    ) -> Result<ImageBinding, String> {
4284        let key = image.storage_id();
4285        if let Some(bind_groups) = self.external_texture_bindings.get(&key) {
4286            return Ok(bind_groups.binding(sampling));
4287        }
4288        let view = image
4289            .external_handle::<wgpu::TextureView>()
4290            .ok_or("an external texture's handle is not a wgpu::TextureView")?;
4291        let bind_groups = self.image_bind_groups(view, false);
4292        let binding = bind_groups.binding(sampling);
4293        self.external_texture_bindings.put(key, bind_groups);
4294        Ok(binding)
4295    }
4296
4297    fn image_bind_groups(&self, view: &wgpu::TextureView, alpha_mask: bool) -> ImageBindGroups {
4298        ImageBindGroups {
4299            alpha_mask,
4300            nearest: self.image_bind_group(view, &self.image_nearest_sampler),
4301            linear: self.image_bind_group(view, &self.image_linear_sampler),
4302        }
4303    }
4304
4305    fn image_bind_group(
4306        &self,
4307        view: &wgpu::TextureView,
4308        sampler: &wgpu::Sampler,
4309    ) -> wgpu::BindGroup {
4310        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4311            label: Some("Image Texture Bind Group"),
4312            layout: &self.image_bind_group_layout,
4313            entries: &[
4314                wgpu::BindGroupEntry {
4315                    binding: 0,
4316                    resource: wgpu::BindingResource::TextureView(view),
4317                },
4318                wgpu::BindGroupEntry {
4319                    binding: 1,
4320                    resource: wgpu::BindingResource::Sampler(sampler),
4321                },
4322            ],
4323        })
4324    }
4325
4326    pub(crate) fn max_texture_dim(&self) -> u32 {
4327        self.effect_renderer.max_texture_dim()
4328    }
4329
4330    /// A pooled texture that outlives the frame: layer cache entries and
4331    /// cached shadow surfaces.
4332    pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
4333        self.effect_renderer
4334            .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
4335    }
4336
4337    fn frame_root(
4338        &mut self,
4339        output_mode: OutputMode,
4340        output_view: Option<&wgpu::TextureView>,
4341        output_texture: Option<&wgpu::Texture>,
4342        viewport: (u32, u32),
4343        reads_page: bool,
4344    ) -> FrameRoot {
4345        if let (OutputMode::Display, Some(view), Some(texture)) =
4346            (output_mode, output_view, output_texture)
4347            && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
4348        {
4349            return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
4350                texture.clone(),
4351                view.clone(),
4352            )));
4353        }
4354        FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
4355    }
4356
4357    fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
4358        if let Some(target) = self.composition_target.take()
4359            && target.target.width == width
4360            && target.target.height == height
4361        {
4362            return target;
4363        }
4364        let target = Rc::new(OffscreenTarget::new(
4365            &self.device,
4366            self.composition_format,
4367            width,
4368            height,
4369        ));
4370        let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
4371        CompositionTarget {
4372            target,
4373            output_bind_group,
4374        }
4375    }
4376
4377    fn transient_offscreen_descriptor(
4378        &self,
4379        label: &'static str,
4380        width: u32,
4381        height: u32,
4382    ) -> FrameTextureDescriptor {
4383        let max_texture_dim = self.max_texture_dim();
4384        FrameTextureDescriptor::render_attachment(
4385            label,
4386            width.min(max_texture_dim),
4387            height.min(max_texture_dim),
4388            self.composition_format,
4389        )
4390    }
4391
4392    /// A texture of the given size that stays transparent: the input of a
4393    /// runtime shader whose layer draws nothing itself, so the shader needs
4394    /// no surface pass and reads the same empty content every frame.
4395    #[inline(never)]
4396    pub(crate) fn transparent_source<C: FrameCommandRecorder>(
4397        &mut self,
4398        recorder: &mut C,
4399        width: u32,
4400        height: u32,
4401    ) -> Rc<OffscreenTarget> {
4402        if let Some(source) = self.transparent_sources.get(&(width, height)) {
4403            return Rc::clone(source);
4404        }
4405        if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
4406            for (_, source) in self.transparent_sources.drain() {
4407                if let Ok(target) = Rc::try_unwrap(source) {
4408                    self.deferred_offscreen_releases.push(target);
4409                }
4410            }
4411        }
4412        let source = Rc::new(self.acquire_retained_surface(width, height));
4413        self.clear_target(
4414            recorder,
4415            &source.view,
4416            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4417        );
4418        self.transparent_sources
4419            .insert((width, height), Rc::clone(&source));
4420        source
4421    }
4422
4423    fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
4424        self.deferred_offscreen_releases.push(target);
4425    }
4426
4427    fn flush_deferred_offscreen_releases(&mut self) {
4428        let layer_cache = &mut self.layer_cache;
4429        let mut retire = |gate: &mut AdmissionGate| {
4430            let seen = gate.end_frame();
4431            if !seen && let Some(dead) = gate.dead_entry() {
4432                layer_cache.remove(&dead);
4433            }
4434            seen
4435        };
4436        self.backdrop_gates.retain(|_, gate| retire(gate));
4437        self.fill_gates.retain(|_, gate| retire(gate));
4438        self.effect_gates.retain(|_, gate| retire(gate));
4439        self.source_gates.retain(|_, gate| retire(gate));
4440        for target in self.deferred_offscreen_releases.drain(..) {
4441            self.effect_renderer.release_offscreen(target);
4442        }
4443        self.layer_cache.end_frame();
4444        for (transient, target) in self.layer_cache.take_released() {
4445            match transient {
4446                Some(descriptor) => self
4447                    .frame_graph_executor
4448                    .return_cached_transient(descriptor, target),
4449                None => self.effect_renderer.release_offscreen(target),
4450            }
4451        }
4452        self.effect_renderer.end_offscreen_frame();
4453        self.frame_graph_executor.end_transient_frame();
4454        self.depth_targets.end_frame();
4455        self.surface_atlas_sizes.end_frame();
4456    }
4457
4458    fn insert_cached_shadow_surface(
4459        &mut self,
4460        key: ShadowSurfaceCacheKey,
4461        target: Rc<OffscreenTarget>,
4462    ) {
4463        let byte_size = offscreen_byte_size(target.width, target.height);
4464        while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
4465            let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
4466                break;
4467            };
4468            self.shadow_surface_cache_bytes = self
4469                .shadow_surface_cache_bytes
4470                .saturating_sub(evicted.byte_size);
4471        }
4472        let cached = CachedShadowSurface { target, byte_size };
4473        if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4474            self.shadow_surface_cache_bytes = self
4475                .shadow_surface_cache_bytes
4476                .saturating_sub(replaced.byte_size);
4477        }
4478        self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4479    }
4480}
4481fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4482    snapshot.layer_cache_misses > 0
4483        || snapshot.shadow_shape_cache_misses > 0
4484        || snapshot.text_image_cache_misses > 0
4485        || snapshot.text_glyph_atlas_misses > 0
4486}
4487
4488fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4489    if *pending_frames > 0 {
4490        *pending_frames = pending_frames.saturating_sub(1);
4491    } else if frame_stats_need_warmup_frame(snapshot) {
4492        *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4493    }
4494}
4495
4496impl GpuRenderer {
4497    #[expect(clippy::too_many_arguments)]
4498    pub fn render(
4499        &mut self,
4500        texture: &wgpu::Texture,
4501        view: &wgpu::TextureView,
4502        width: u32,
4503        height: u32,
4504        packet: FramePacket,
4505        surface_epoch: u64,
4506        returns: &mut RenderReturns,
4507    ) -> Result<(), String> {
4508        self.render_internal(
4509            width,
4510            height,
4511            packet,
4512            surface_epoch,
4513            returns,
4514            OutputMode::Display,
4515            Some(view),
4516            Some(texture),
4517        )
4518    }
4519
4520    #[expect(clippy::too_many_arguments)]
4521    fn render_internal(
4522        &mut self,
4523        width: u32,
4524        height: u32,
4525        packet: FramePacket,
4526        surface_epoch: u64,
4527        returns: &mut RenderReturns,
4528        output_mode: OutputMode,
4529        output_view: Option<&wgpu::TextureView>,
4530        output_texture: Option<&wgpu::Texture>,
4531    ) -> Result<(), String> {
4532        let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
4533            Some(CancelReason::RendererEpoch)
4534        } else if packet.surface_epoch != surface_epoch {
4535            Some(CancelReason::SurfaceEpoch)
4536        } else if packet.viewport != (width, height) {
4537            Some(CancelReason::Viewport)
4538        } else {
4539            None
4540        };
4541        if let Some(reason) = cancel_reason {
4542            return Self::cancel_packet(packet, reason, returns);
4543        }
4544        if self.device_errors.take_poison() {
4545            return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
4546        }
4547        returns.frame_id = packet.frame_id;
4548        let render_start = Instant::now();
4549        #[cfg(not(target_arch = "wasm32"))]
4550        let builds_before = thread_builds();
4551        self.warm_requested_shaders();
4552        self.shape_pipelines.begin_frame();
4553        self.recorder.begin_frame();
4554        self.begin_placeholder_frame();
4555        self.viewport_uniforms.begin_frame();
4556        self.run_store.begin_frame(gpu_stats_enabled());
4557        self.begin_text_glyph_run_frame();
4558
4559        let text_cache_len = packet.text_cache_len;
4560        let reads_page = packet.root.contains_backdrop()
4561            || packet
4562                .overlay
4563                .as_ref()
4564                .is_some_and(LayerScene::contains_backdrop);
4565        let frame_root = self.frame_root(
4566            output_mode,
4567            output_view,
4568            output_texture,
4569            (width, height),
4570            reads_page,
4571        );
4572        let root = frame_root.target();
4573        let screenshot_bind_group = output_view.and_then(|_| {
4574            matches!(output_mode, OutputMode::Screenshot).then(|| {
4575                self.screenshot_converter
4576                    .bind_group(&self.device, &root.view)
4577            })
4578        });
4579        let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
4580        let result = self.render_graph(root, packet, returns, output_mode, output);
4581        #[cfg(not(target_arch = "wasm32"))]
4582        self.effect_renderer
4583            .compiler()
4584            .spread_demand(thread_builds() == builds_before);
4585        if let FrameRoot::Composition(composition) = frame_root {
4586            self.composition_target = Some(composition);
4587        }
4588        let after_graph = Instant::now();
4589        self.flush_deferred_offscreen_releases();
4590        self.scratch_glyph_instances.end_frame();
4591
4592        self.frame_stats
4593            .layer_cache_size
4594            .set(self.layer_cache.len() as u32);
4595        self.frame_stats
4596            .layer_cache_bytes
4597            .set(self.layer_cache.bytes());
4598        self.frame_stats.offscreen_pool_size.set(
4599            self.effect_renderer
4600                .retained_offscreen_count()
4601                .saturating_add(self.frame_graph_executor.retained_texture_count())
4602                .saturating_add(usize::from(self.composition_target.is_some())) as u32,
4603        );
4604        self.frame_stats.offscreen_pool_bytes.set(
4605            (self.effect_renderer.retained_offscreen_bytes() as u64)
4606                .saturating_add(self.frame_graph_executor.retained_texture_bytes())
4607                .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
4608                    u64::from(target.target.width)
4609                        .saturating_mul(u64::from(target.target.height))
4610                        .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
4611                })),
4612        );
4613        self.frame_stats
4614            .text_pool_size
4615            .set(self.text_image_cache.len() as u32);
4616        self.frame_stats
4617            .image_cache_size
4618            .set(self.image_texture_cache.len() as u32);
4619        self.frame_stats.text_cache_size.set(text_cache_len as u32);
4620        self.effect_renderer
4621            .merge_and_reset_debug_counters(&self.frame_stats);
4622        self.frame_graph_executor.reset_upload_allocators();
4623        let snapshot = self.frame_stats.snapshot();
4624        if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
4625            log::warn!(
4626                "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
4627                 offscreen_acq={} offscreen_new={} isolated={} draws={}",
4628                snapshot.layer_cache_hits,
4629                snapshot.layer_cache_misses,
4630                snapshot.layer_cache_miss_pixels,
4631                snapshot.offscreen_acquires,
4632                snapshot.offscreen_news,
4633                snapshot.isolated_layer_renders,
4634                snapshot.draw_calls,
4635            );
4636        }
4637        self.last_frame_stats = Some(snapshot);
4638        PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4639        update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
4640        let gpu_stats_on = gpu_stats_enabled();
4641        self.frame_stats
4642            .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
4643        if gpu_stats_on && self.frame_count.is_multiple_of(60) {
4644            gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
4645        }
4646        self.frame_graph_executor
4647            .end_pass_timing_frame(&self.device, &self.queue);
4648        self.frame_stats.reset();
4649        let after_stats = Instant::now();
4650        if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
4651            log::warn!(
4652                "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
4653                instant_ms(render_start, after_graph),
4654                instant_ms(after_graph, after_stats),
4655            );
4656        }
4657        if result.is_ok() {
4658            returns.outcome = PresentOutcome::Presented;
4659        }
4660        result
4661    }
4662
4663    /// Returns a packet unrendered, handing its scene back for recycling.
4664    pub(crate) fn cancel_packet(
4665        packet: FramePacket,
4666        reason: CancelReason,
4667        returns: &mut RenderReturns,
4668    ) -> Result<(), String> {
4669        returns.scene = Some(FrameSceneStorage {
4670            root: packet.root,
4671            overlay: packet.overlay,
4672        });
4673        returns.frame_id = packet.frame_id;
4674        returns.outcome = PresentOutcome::Cancelled(reason);
4675        Ok(())
4676    }
4677
4678    pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
4679        self.last_frame_stats
4680    }
4681
4682    pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
4683        self.frame_graph_executor.pass_timing_report()
4684    }
4685
4686    pub fn needs_frame_warmup(&self) -> bool {
4687        self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
4688    }
4689
4690    #[cfg(target_arch = "wasm32")]
4691    pub(crate) fn pipeline_compiler(&self) -> &PipelineCompiler {
4692        &self.pipeline_compiler
4693    }
4694
4695    /// Whether a frame must follow to replace a placeholder: a pipeline it
4696    /// waited for landed, or, with nothing to wake the app when one does,
4697    /// this frame drew one.
4698    fn placeholder_awaits_frame(&self) -> bool {
4699        #[cfg(not(target_arch = "wasm32"))]
4700        if let Some(landing) = &self.landing {
4701            return landing.landed() || (self.drew_placeholder && !landing.has_wake());
4702        }
4703        self.drew_placeholder
4704    }
4705
4706    /// Starts a frame: once a pipeline a placeholder waited for has landed,
4707    /// the retained layers, which may hold that placeholder, are dropped.
4708    fn begin_placeholder_frame(&mut self) {
4709        self.drew_placeholder = false;
4710        #[cfg(not(target_arch = "wasm32"))]
4711        if let Some(landing) = &self.landing {
4712            self.built_at_frame_start = landing.built();
4713            if landing.take_landed() {
4714                self.layer_cache.clear();
4715            }
4716        }
4717    }
4718
4719    /// Notes an effect drawn as its placeholder, or left out, while its
4720    /// pipelines compile, and waits for the next one to land.
4721    pub(crate) fn note_placeholder(&mut self) {
4722        self.drew_placeholder = true;
4723        self.recorder.hold_first_screen();
4724        self.frame_stats
4725            .placeholder_draws
4726            .set(self.frame_stats.placeholder_draws.get() + 1);
4727        #[cfg(not(target_arch = "wasm32"))]
4728        if let Some(landing) = &self.landing {
4729            landing.await_since(self.built_at_frame_start);
4730        }
4731    }
4732
4733    /// Queues every pipeline the cache file records, as the first frame of
4734    /// an updated build does, and returns whether any is left to build: for
4735    /// a renderer that prepares an app's pipelines without drawing.
4736    #[cfg(not(target_arch = "wasm32"))]
4737    pub(crate) fn prepare_recorded(&mut self) -> bool {
4738        self.effect_renderer.warm_after_first_frame();
4739        if let Some(records) = self.recent_after_update.take() {
4740            self.warm_recent(&records);
4741        }
4742        self.compiling()
4743    }
4744
4745    /// Whether the background compiler has a queued pipeline left to build.
4746    #[cfg(not(target_arch = "wasm32"))]
4747    pub(crate) fn compiling(&self) -> bool {
4748        self.landing
4749            .as_ref()
4750            .is_some_and(|landing| landing.in_flight())
4751    }
4752
4753    /// Whether the last frame drew a placeholder and pipelines are still
4754    /// compiling, so its picture is not final yet.
4755    pub(crate) fn awaits_pipelines(&self) -> bool {
4756        #[cfg(not(target_arch = "wasm32"))]
4757        if let Some(landing) = &self.landing {
4758            return self.drew_placeholder && landing.in_flight();
4759        }
4760        self.drew_placeholder
4761    }
4762
4763    /// The compiler's account of the pipelines it builds, for a runtime that
4764    /// reads it off the present thread.
4765    #[cfg(not(target_arch = "wasm32"))]
4766    pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
4767        self.landing.clone()
4768    }
4769
4770    /// Calls `wake` from the compiling thread when a pipeline a placeholder
4771    /// waited for lands, so an app with nothing else to draw draws again.
4772    #[cfg(not(target_arch = "wasm32"))]
4773    pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
4774        if let Some(landing) = &self.landing {
4775            landing.wake_with(wake);
4776        }
4777    }
4778
4779    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
4780        DebugCpuAllocationStats {
4781            scene_graph_node_count: 0,
4782            scene_graph_heap_bytes: 0,
4783            scene_hits_len: 0,
4784            scene_hits_cap: 0,
4785            scene_node_index_len: 0,
4786            scene_node_index_cap: 0,
4787            text_renderer_pool_len: self.text_image_cache.len(),
4788            text_renderer_pool_cap: self.text_image_cache.cap().get(),
4789            image_texture_cache_len: self.image_texture_cache.len(),
4790            image_texture_cache_cap: self.image_texture_cache.cap().get(),
4791            run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
4792            run_store_bytes: self.run_store.stored_bytes(),
4793            run_store_runs: self.run_store.stored_count(),
4794            scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
4795            scratch_image_indices_cap: self.scratch_image_indices.capacity(),
4796            scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
4797            scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
4798                + self.scratch_glyph_instances.turned.capacity(),
4799            layer_cache_len: self.layer_cache.len(),
4800            layer_cache_bytes: self.layer_cache.bytes(),
4801        }
4802    }
4803    pub fn render_to_rgba_pixels(
4804        &mut self,
4805        width: u32,
4806        height: u32,
4807        packet: FramePacket,
4808        surface_epoch: u64,
4809        returns: &mut RenderReturns,
4810    ) -> Result<Vec<u8>, String> {
4811        if width == 0 || height == 0 {
4812            return Err("Screenshot size must be non-zero".to_string());
4813        }
4814        let errors_before = self.device_errors.error_count();
4815
4816        let output_texture = crate::offscreen::create_2d_texture(
4817            &self.device,
4818            wgpu::TextureFormat::Rgba8Unorm,
4819            width,
4820            height,
4821            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4822            Some("Screenshot Output Texture"),
4823        );
4824        let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
4825        self.render_internal(
4826            width,
4827            height,
4828            packet,
4829            surface_epoch,
4830            returns,
4831            OutputMode::Screenshot,
4832            Some(&output_view),
4833            None,
4834        )?;
4835        if returns.outcome != PresentOutcome::Presented {
4836            return Err(format!(
4837                "Screenshot rendering did not complete: {:?}",
4838                returns.outcome
4839            ));
4840        }
4841        self.read_screenshot_pixels(&output_texture, errors_before)
4842    }
4843
4844    fn read_screenshot_pixels(
4845        &mut self,
4846        output_texture: &wgpu::Texture,
4847        errors_before: u64,
4848    ) -> Result<Vec<u8>, String> {
4849        let width = output_texture.width();
4850        let height = output_texture.height();
4851        let bytes_per_pixel = 4u32;
4852        let unpadded_bytes_per_row = width
4853            .checked_mul(bytes_per_pixel)
4854            .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
4855        let padded_bytes_per_row =
4856            align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
4857        let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
4858
4859        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
4860            label: Some("Screenshot Readback Buffer"),
4861            size: output_buffer_size,
4862            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4863            mapped_at_creation: false,
4864        });
4865
4866        let device = self.device.clone();
4867        let queue = self.queue.clone();
4868        let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
4869        let source = graph.import_surface("screenshot-copy-source");
4870        graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
4871            context.encoder.copy_texture_to_buffer(
4872                wgpu::TexelCopyTextureInfo {
4873                    texture: output_texture,
4874                    mip_level: 0,
4875                    origin: wgpu::Origin3d::ZERO,
4876                    aspect: wgpu::TextureAspect::All,
4877                },
4878                wgpu::TexelCopyBufferInfo {
4879                    buffer: &output_buffer,
4880                    layout: wgpu::TexelCopyBufferLayout {
4881                        offset: 0,
4882                        bytes_per_row: Some(padded_bytes_per_row),
4883                        rows_per_image: Some(height),
4884                    },
4885                },
4886                wgpu::Extent3d {
4887                    width,
4888                    height,
4889                    depth_or_array_layers: 1,
4890                },
4891            );
4892            Ok(())
4893        });
4894        let mut executor = std::mem::take(&mut self.frame_graph_executor);
4895        let execution = executor.execute_recorded_graph(&device, &queue, graph);
4896        self.frame_graph_executor = executor;
4897        self.recall_frame_uploads();
4898        let execution = execution.map_err(|error| error.to_string())?;
4899        let submission_index = execution.submission;
4900        let copy_stats = execution.stats;
4901        self.last_frame_stats = self
4902            .last_frame_stats
4903            .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
4904
4905        let buffer_slice = output_buffer.slice(..);
4906        let (tx, rx) = mpsc::channel();
4907        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
4908            let _ = tx.send(result);
4909        });
4910        self.device
4911            .poll(wgpu::PollType::Wait {
4912                submission_index: Some(submission_index),
4913                timeout: None,
4914            })
4915            .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
4916
4917        match rx.recv_timeout(Duration::from_secs(3)) {
4918            Ok(Ok(())) => {}
4919            Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
4920            Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
4921        }
4922        if self.device_errors.error_count() != errors_before {
4923            output_buffer.unmap();
4924            return Err("GPU errors occurred while capturing the screenshot".to_string());
4925        }
4926
4927        let mapped = buffer_slice
4928            .get_mapped_range()
4929            .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
4930        let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
4931
4932        let src_row_len = padded_bytes_per_row as usize;
4933        let dst_row_len = unpadded_bytes_per_row as usize;
4934        for row in 0..height as usize {
4935            let src_offset = row * src_row_len;
4936            let dst_offset = row * dst_row_len;
4937            pixels[dst_offset..dst_offset + dst_row_len]
4938                .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
4939        }
4940        drop(mapped);
4941        output_buffer.unmap();
4942
4943        self.convert_surface_pixels_to_rgba(&pixels)
4944    }
4945
4946    /// Asks the buffers the submitted frame unmapped back for later frames.
4947    fn recall_frame_uploads(&mut self) {
4948        self.viewport_uniforms.uploads.recall();
4949        self.run_store.recall();
4950    }
4951
4952    fn render_graph(
4953        &mut self,
4954        root_target: &Rc<OffscreenTarget>,
4955        packet: FramePacket,
4956        returns: &mut RenderReturns,
4957        output_mode: OutputMode,
4958        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4959    ) -> Result<(), String> {
4960        let device = self.device.clone();
4961        let queue = self.queue.clone();
4962        let graph_start = Instant::now();
4963        let FramePacket {
4964            root,
4965            overlay,
4966            root_scale,
4967            clear,
4968            ..
4969        } = packet;
4970        let page = Rc::clone(root_target);
4971
4972        #[cfg(not(target_arch = "wasm32"))]
4973        let (result, submitted) = {
4974            let mut executor = std::mem::take(&mut self.frame_graph_executor);
4975            let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
4976            let surface = frame_graph.import_surface("renderer-surface");
4977            frame_graph.add_fallible_recorded_command_pass(
4978                Some("Renderer Frame Pass"),
4979                &[],
4980                &[surface],
4981                |frame_encoder| {
4982                    self.encode_frame(
4983                        frame_encoder,
4984                        &root,
4985                        overlay.as_ref(),
4986                        Rc::clone(&page),
4987                        root_scale,
4988                        clear,
4989                        output_mode,
4990                        output,
4991                    )
4992                },
4993            );
4994            let after_build = Instant::now();
4995            let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
4996            let after_execute = Instant::now();
4997            self.frame_graph_executor = executor;
4998            self.recall_frame_uploads();
4999            if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5000                log::warn!(
5001                    "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
5002                    instant_ms(graph_start, after_build),
5003                    instant_ms(after_build, after_execute),
5004                );
5005            }
5006            match execution {
5007                Ok(execution) => {
5008                    if execution.stats.pass_count > 0 {
5009                        self.frame_stats.record_command_stats(execution.stats);
5010                    }
5011                    (Ok(()), true)
5012                }
5013                Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
5014                Err(error) => (Err(error.to_string()), false),
5015            }
5016        };
5017
5018        #[cfg(target_arch = "wasm32")]
5019        let (result, submitted) = {
5020            let mut executor = std::mem::take(&mut self.frame_graph_executor);
5021            let (result, execution) = {
5022                let mut frame_encoder =
5023                    executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
5024                let initial_pass_count = frame_encoder.recorded_pass_count();
5025                let result = self.encode_frame(
5026                    &mut frame_encoder,
5027                    &root,
5028                    overlay.as_ref(),
5029                    Rc::clone(&page),
5030                    root_scale,
5031                    clear,
5032                    output_mode,
5033                    output,
5034                );
5035                let execution =
5036                    if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
5037                        Some(frame_encoder.finish())
5038                    } else {
5039                        None
5040                    };
5041                (result, execution)
5042            };
5043            let after_execute = Instant::now();
5044            self.frame_graph_executor = executor;
5045            if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5046                log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
5047            }
5048            let submitted = execution.is_some();
5049            if let Some(execution) = execution {
5050                self.frame_stats.record_command_stats(execution.stats);
5051            }
5052            (result, submitted)
5053        };
5054        #[cfg(not(target_arch = "wasm32"))]
5055        if submitted {
5056            self.recorder.note_frame_drawn();
5057            self.effect_renderer.warm_after_first_frame();
5058            if let Some(records) = self.recent_after_update.take() {
5059                self.warm_recent(&records);
5060            }
5061        }
5062        if !submitted {
5063            self.run_store.invalidate_uploads();
5064            self.text_glyph_gpu_run_cache.clear();
5065            self.text_glyph_run_arena = GlyphRunArena::new(self.copy_free);
5066        }
5067        returns.scene = Some(FrameSceneStorage { root, overlay });
5068        result
5069    }
5070
5071    /// Records the frame: the root and overlay layer scenes into the frame's
5072    /// target, the output conversion when the target is not the presented
5073    /// image, and the viewport uniforms the recorded passes claimed.
5074    #[expect(clippy::too_many_arguments)]
5075    fn encode_frame<C: FrameCommandRecorder>(
5076        &mut self,
5077        recorder: &mut C,
5078        root: &LayerScene,
5079        overlay: Option<&LayerScene>,
5080        page: Rc<OffscreenTarget>,
5081        root_scale: f32,
5082        clear: wgpu::Color,
5083        output_mode: OutputMode,
5084        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5085    ) -> Result<(), String> {
5086        FrameExecutor::new(self, recorder).render_frame(
5087            root,
5088            overlay,
5089            page,
5090            root_scale,
5091            wgpu::LoadOp::Clear(clear),
5092        )?;
5093        if let Some((output_view, bind_group)) = output {
5094            match output_mode {
5095                OutputMode::Display => &self.output_converter,
5096                OutputMode::Screenshot => &self.screenshot_converter,
5097            }
5098            .encode(
5099                &self.device,
5100                recorder,
5101                output_view,
5102                bind_group,
5103                self.adapter_backend,
5104                &self.recorder,
5105            );
5106            recorder.record_pass();
5107        }
5108        self.stage_frame_uploads(recorder);
5109        self.shape_pipelines.request_wanted();
5110        self.depth_gate.end_frame();
5111        self.pipeline_compiler.end_frame();
5112        self.viewport_uniforms.uploads.finish_frame();
5113        self.run_store.finish_frame();
5114        Ok(())
5115    }
5116
5117    pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
5118        let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
5119        upload += self.run_store.stage_pending(&self.device, recorder);
5120        upload += self
5121            .text_glyph_run_arena
5122            .stage_pending(&self.device, recorder);
5123        self.run_store.fill_arena_trig(&self.device, recorder);
5124        self.frame_stats.record_command_stats(upload);
5125    }
5126    /// Claims this frame's next viewport uniform slot for `params`.
5127    pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
5128        let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
5129        self.viewport_uniforms
5130            .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
5131    }
5132
5133    /// Resolves a blurred shadow at `z` into a texture and queues its
5134    /// composites. The shadow's shapes and texts render into a source the
5135    /// size of their blur footprint, blur in place and take the post-blur
5136    /// cutouts; the source is then blitted over the rect the shadow covers.
5137    /// Shape-only shadows live in the shadow cache, keyed by their content
5138    /// and device placement, so a scrolling card re-blits its cached blur.
5139    /// The blurred shadow texture and whether the cache held it: a
5140    /// shape-only shadow is cached by content and placement, a shadow with
5141    /// text renders every frame.
5142    fn blurred_shadow_source<C: FrameCommandRecorder>(
5143        &mut self,
5144        recorder: &mut C,
5145        shadow: &ShadowDraw,
5146        source_device: DevicePixelBounds,
5147        pixel_radius: f32,
5148        root_scale: f32,
5149        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5150    ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
5151        let shape_only = shadow.texts.is_empty();
5152        let key = if shape_only {
5153            shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
5154        } else {
5155            None
5156        };
5157        let content = key.map_or(SourceContent::Transient, |key| {
5158            SourceContent::retained(&key)
5159        });
5160        if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
5161            return Some((Rc::clone(&entry.target), true, content));
5162        }
5163        // A shadow whose blur compiles is left out until the blur lands.
5164        if !self.effect_renderer.blur_draws_now(
5165            &self.device,
5166            TileMode::Decal,
5167            (source_device.width, source_device.height),
5168            pixel_radius,
5169            pixel_radius,
5170        ) {
5171            self.note_placeholder();
5172            return None;
5173        }
5174        if !shape_only {
5175            self.frame_stats.record_shadow_text_blur_fallback();
5176        }
5177        let source = self.render_shadow_source(
5178            recorder,
5179            shadow,
5180            source_device,
5181            pixel_radius,
5182            root_scale,
5183            key.is_some(),
5184            transients,
5185        )?;
5186        if let Some(key) = key {
5187            self.frame_stats
5188                .record_shadow_shape_cache_miss(source_device.width, source_device.height);
5189            self.frame_stats.maybe_print_shadow_shape_cache_miss(
5190                source_device.width,
5191                source_device.height,
5192                key.content_hash,
5193                pixel_radius,
5194                [source_device.x, source_device.y],
5195                shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
5196                shadow.clip,
5197            );
5198            self.insert_cached_shadow_surface(key, Rc::clone(&source));
5199        }
5200        Some((source, false, content))
5201    }
5202
5203    #[expect(clippy::too_many_arguments)]
5204    pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
5205        &mut self,
5206        recorder: &mut C,
5207        shadow: &ShadowDraw,
5208        z: usize,
5209        root_scale: f32,
5210        target_rect: DeviceRect4,
5211        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5212        resolved: &mut Vec<ResolvedComposite>,
5213    ) {
5214        if !shadow.requires_surface()
5215            || skip_shadow_draws()
5216            || !root_scale.is_finite()
5217            || root_scale <= 0.0
5218        {
5219            return;
5220        }
5221        let Some(bounds) = shadow_draw_bounds(shadow) else {
5222            return;
5223        };
5224        let margin = blur_reach(shadow.blur_radius, root_scale);
5225        let source_bounds = expand_rect(bounds, margin, margin);
5226        let mut visible = source_bounds;
5227        if let Some(clip) = shadow.clip {
5228            let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
5229                return;
5230            };
5231            visible = clipped;
5232        }
5233        let target_logical = Rect {
5234            x: target_rect.0 / root_scale,
5235            y: target_rect.1 / root_scale,
5236            width: target_rect.2 / root_scale,
5237            height: target_rect.3 / root_scale,
5238        };
5239        let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
5240            return;
5241        };
5242        let max_texture_dim = self.max_texture_dim();
5243        let shape_only = shadow.texts.is_empty();
5244        let anchor = shadow
5245            .shapes
5246            .as_ref()
5247            .and_then(|run| run.placement.snap_anchor);
5248        let source_device = shape_only
5249            .then(|| {
5250                translation_stable_anchored_device_pixel_bounds(
5251                    source_bounds,
5252                    anchor,
5253                    root_scale,
5254                    max_texture_dim,
5255                )
5256            })
5257            .flatten()
5258            .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
5259        let Some(source_device) = source_device else {
5260            return;
5261        };
5262        let pixel_radius = shadow.blur_radius * root_scale;
5263        let Some((source, hit, content)) = self.blurred_shadow_source(
5264            recorder,
5265            shadow,
5266            source_device,
5267            pixel_radius,
5268            root_scale,
5269            transients,
5270        ) else {
5271            return;
5272        };
5273        let dest = (
5274            source_device.x,
5275            source_device.y,
5276            source_device.width as f32,
5277            source_device.height as f32,
5278        );
5279        let mut coverage = intersect_device_rects(dest, target_rect);
5280        if let Some(clip) = shadow.clip {
5281            coverage = coverage.and_then(|coverage| {
5282                intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
5283            });
5284        }
5285        let Some(coverage) = coverage else {
5286            return;
5287        };
5288        if hit {
5289            self.frame_stats.record_shadow_shape_cache_hit(
5290                (coverage.2 as u64).saturating_mul(coverage.3 as u64),
5291            );
5292        }
5293        let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
5294        let downscaled =
5295            (source.width, source.height) != (source_device.width, source_device.height);
5296        let (sample_mode, source_viewport) = if downscaled {
5297            (
5298                CompositeSampleMode::Linear,
5299                Some((0.0, 0.0, source.width as f32, source.height as f32)),
5300            )
5301        } else {
5302            (CompositeSampleMode::Nearest, None)
5303        };
5304        resolved.push(ResolvedComposite {
5305            z_index: z,
5306            source,
5307            content,
5308            dest,
5309            scissor: Some(coverage),
5310            kind: ResolvedCompositeKind::Blit {
5311                alpha: 1.0,
5312                blend_mode: BlendMode::SrcOver,
5313                rounded_mask,
5314                sample_mode,
5315                source_viewport,
5316            },
5317        });
5318    }
5319
5320    /// Draws a shadow's shapes and texts into a surface covering `bounds`
5321    /// and blurs it. A wide blur runs at its scratch size and its result
5322    /// stays there, read bilinearly by the composite; a post-blur cutout
5323    /// needs the surface's full size, so the blurred result is interpolated
5324    /// back into it first and the cutout drawn at that size. A retained
5325    /// result feeds the shadow cache; a transient one is registered with
5326    /// the frame's transients and released with them. `None` when the
5327    /// shadow draws nothing.
5328    #[expect(clippy::too_many_arguments)]
5329    fn render_shadow_source<C: FrameCommandRecorder>(
5330        &mut self,
5331        recorder: &mut C,
5332        shadow: &ShadowDraw,
5333        bounds: DevicePixelBounds,
5334        pixel_radius: f32,
5335        root_scale: f32,
5336        retained: bool,
5337        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5338    ) -> Option<Rc<OffscreenTarget>> {
5339        let (width, height) = (bounds.width, bounds.height);
5340        let device = self.device.clone();
5341        let (scratch_width, scratch_height) =
5342            crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
5343        let full_size_result = shadow.post_blur_cutouts.is_some()
5344            || (scratch_width, scratch_height) == (width, height);
5345        let (result_width, result_height) = if full_size_result {
5346            (width, height)
5347        } else {
5348            (scratch_width, scratch_height)
5349        };
5350        let result = if retained {
5351            Rc::new(self.acquire_retained_surface(result_width, result_height))
5352        } else {
5353            self.shadow_transient(
5354                recorder,
5355                transients,
5356                "Shadow Result",
5357                result_width,
5358                result_height,
5359            )
5360        };
5361        let source = if full_size_result {
5362            Rc::clone(&result)
5363        } else {
5364            self.shadow_transient(recorder, transients, "Shadow Source", width, height)
5365        };
5366        let offset = [bounds.x, bounds.y];
5367        let target = PassTarget {
5368            view: &source.view,
5369            width,
5370            height,
5371        };
5372        let scene = shadow_scene(
5373            shadow.shapes.as_ref(),
5374            &shadow.texts,
5375            blur_reach(shadow.blur_radius, root_scale),
5376        );
5377        let segment = PassSegment {
5378            scene: &scene,
5379            ops: &scene.draw_ops,
5380            composites: &[],
5381            offset,
5382            scissor: None,
5383            first_run_window: None,
5384            transform: SegmentTransform::IDENTITY,
5385            scale: root_scale,
5386        };
5387        let drew = self.encode_pass(
5388            recorder,
5389            target,
5390            std::slice::from_ref(&segment),
5391            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
5392            "Shadow Source Pass",
5393        );
5394        match drew {
5395            Ok(true) => {}
5396            Ok(false) => {
5397                drop(source);
5398                if retained && let Ok(target) = Rc::try_unwrap(result) {
5399                    self.defer_offscreen_release(target);
5400                }
5401                return None;
5402            }
5403            Err(error) => {
5404                log::error!("shadow source pass failed: {error}");
5405                return None;
5406            }
5407        }
5408        if pixel_radius > 0.0 {
5409            let scratch_descriptor = self.transient_offscreen_descriptor(
5410                "Shadow Blur Scratch",
5411                scratch_width,
5412                scratch_height,
5413            );
5414            let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
5415            let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
5416            {
5417                Some(self.shadow_transient(
5418                    recorder,
5419                    transients,
5420                    "Shadow Blur Result",
5421                    scratch_width,
5422                    scratch_height,
5423                ))
5424            } else {
5425                None
5426            };
5427            let blur_dest = match &blurred {
5428                Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
5429                None => (&result.view, (result_width, result_height)),
5430            };
5431            let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
5432                recorder,
5433                &device,
5434                &source,
5435                &scratch,
5436                blur_dest,
5437                pixel_radius,
5438                pixel_radius,
5439                TileMode::Decal,
5440                None,
5441            );
5442            recorder.record_passes(passes);
5443            self.effect_renderer.record_blur_pass();
5444            recorder.release_transient_offscreen(scratch_descriptor, scratch);
5445            if let Some(blurred) = &blurred {
5446                self.effect_renderer
5447                    .encode_upscale_pass(recorder, &device, blurred, &result.view);
5448                recorder.record_pass();
5449            }
5450        }
5451        if let Some(cutout_run) = &shadow.post_blur_cutouts {
5452            let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
5453            let segment = PassSegment {
5454                scene: &cutouts,
5455                ops: &cutouts.draw_ops,
5456                composites: &[],
5457                offset,
5458                scissor: None,
5459                first_run_window: None,
5460                transform: SegmentTransform::IDENTITY,
5461                scale: root_scale,
5462            };
5463            if let Err(error) = self.encode_pass(
5464                recorder,
5465                target,
5466                std::slice::from_ref(&segment),
5467                wgpu::LoadOp::Load,
5468                "Shadow Cutout Pass",
5469            ) {
5470                log::error!("shadow cutout pass failed: {error}");
5471            }
5472        }
5473        Some(result)
5474    }
5475
5476    /// A transient surface of a shadow's frame, released with the frame's
5477    /// transients.
5478    fn shadow_transient<C: FrameCommandRecorder>(
5479        &self,
5480        recorder: &mut C,
5481        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5482        label: &'static str,
5483        width: u32,
5484        height: u32,
5485    ) -> Rc<OffscreenTarget> {
5486        let descriptor = self.transient_offscreen_descriptor(label, width, height);
5487        let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
5488        transients.push((descriptor, Rc::clone(&target)));
5489        target
5490    }
5491
5492    /// Whether `run` draws from retained buffers keyed by its command.
5493    pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
5494        self.run_store.is_stored(run)
5495    }
5496
5497    /// The pipeline `segment` of a run at `placement` draws with. `clipped`
5498    /// says the variant tests the run's clip: a turned run's, since an
5499    /// unturned one's clip is its paint's scissor (see [`clip_scissor`]).
5500    fn run_pipeline_key(
5501        segment: &RecordSegment,
5502        placement: &crate::scene::Placement,
5503        tier: RunTier,
5504        ablation: ShapeAblation,
5505        turns: ShapeTurns,
5506        (depth, clip): (bool, SegmentClip),
5507        viewport: ViewportUniformParams,
5508    ) -> ShapePipelineKey {
5509        let blend_mode = supported_blend_mode(segment.blend);
5510        let laid = depth
5511            && blend_mode == BlendMode::SrcOver
5512            && !placement.paints()
5513            && clip != SegmentClip::Rounded
5514            && !ablation.material
5515            && !ablation.fill;
5516        ShapePipelineKey {
5517            blend_mode,
5518            tier,
5519            variant: ShapeVariant::of_segment(
5520                segment,
5521                clip,
5522                ablation,
5523                laid,
5524                (
5525                    turns == ShapeTurns::None,
5526                    turns == ShapeTurns::None
5527                        && placement.snap_anchor.is_some()
5528                        && viewport.offset.iter().all(|value| value.fract() == 0.0),
5529                ),
5530            ),
5531            turns,
5532            depth: if depth {
5533                ShapeDepth::Tested
5534            } else {
5535                ShapeDepth::Off
5536            },
5537        }
5538    }
5539
5540    /// Queues for a later frame the shape pipelines `keys` name and the
5541    /// interiors they lay down, handing `awaited` each still to land.
5542    pub(crate) fn warm_shapes_later(
5543        &mut self,
5544        keys: &PipelineDemand,
5545        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
5546    ) {
5547        for key in keys.keys() {
5548            self.shape_pipelines.warm_later(key, awaited);
5549        }
5550    }
5551
5552    /// Prepares the pipeline of each key `pipelines` holds and, in a pass
5553    /// with a depth buffer, the one laying down its opaque interiors: the
5554    /// compiler's threads build the missing ones after the first while this
5555    /// thread builds that one.
5556    pub(crate) fn ensure_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
5557        self.shape_pipelines.prefetch(pipelines);
5558        for (key, vertices) in pipelines.drain() {
5559            self.ensure_shape_pipeline(key, vertices);
5560            if let Some(interior) = key.interior() {
5561                self.ensure_shape_pipeline(interior, vertices);
5562            }
5563        }
5564    }
5565
5566    /// Brings a stored run's tables up to date and appends its draws, under
5567    /// a placement uniform of its own, to the pass's run draws `draws`, and
5568    /// the pipelines they draw with to `pipelines`.
5569    #[expect(clippy::too_many_arguments)]
5570    pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
5571        &mut self,
5572        recorder: &mut C,
5573        run: &RunDraw,
5574        viewport: ViewportUniformParams,
5575        root_scale: f32,
5576        window: &std::ops::Range<u32>,
5577        (depth, mut depth_keys): (bool, Option<&mut PipelineDemand>),
5578        (draws, pipelines): (&mut Vec<RunDrawCall>, &mut PipelineDemand),
5579    ) -> StoreRunBatch {
5580        let placement = &run.placement;
5581        let ablation = self.ablation.shape;
5582        let turns = ShapeTurns::of(viewport.transform, false);
5583        let scissor = clip_scissor(placement, root_scale, viewport);
5584        let clip = SegmentClip::of(placement, scissor.is_some());
5585        let start = draws.len();
5586        self.run_store.stored_run_draws(
5587            &self.device,
5588            run,
5589            &mut |segment| {
5590                let key = |depth| {
5591                    Self::run_pipeline_key(
5592                        segment,
5593                        placement,
5594                        RunTier::Store,
5595                        ablation,
5596                        turns,
5597                        (depth, clip),
5598                        viewport,
5599                    )
5600                };
5601                if let Some(keys) = depth_keys.as_deref_mut() {
5602                    keys.add(key(true), 0);
5603                }
5604                key(depth)
5605            },
5606            draws,
5607        );
5608        window_draws(draws, start, window);
5609        let run_draws = &draws[start..];
5610        let upload_start = Instant::now();
5611        let (upload, fill, tables) = self.run_store.upload_stored(
5612            &self.device,
5613            recorder,
5614            run,
5615            root_scale,
5616            window,
5617            run_draws,
5618        );
5619        if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
5620            log::warn!(
5621                "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
5622                upload.upload_bytes,
5623                run.tables().shapes.len()
5624            );
5625        }
5626        self.frame_stats.record_command_stats(upload);
5627        if let Some(fill) = fill {
5628            self.frame_stats.add_shape_fill(fill);
5629        }
5630        let uniforms = Uniforms::of(
5631            viewport,
5632            PlacementData::of(&run.placement, root_scale, viewport.transform),
5633            RunTier::Store,
5634        );
5635        let uniform_slot =
5636            self.viewport_uniforms
5637                .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
5638        for draw in run_draws {
5639            pipelines.add(
5640                draw.key,
5641                crate::run_store::draw_vertices(
5642                    draw.records.end - draw.records.start,
5643                    draw.band_class,
5644                ),
5645            );
5646        }
5647        StoreRunBatch {
5648            tables,
5649            uniform_slot,
5650            draws: start..draws.len(),
5651            clip: scissor,
5652        }
5653    }
5654
5655    pub(crate) fn open_arena(&mut self) -> usize {
5656        self.run_store.open_arena()
5657    }
5658
5659    /// The records the open arena chunk holds so far.
5660    pub(crate) fn open_arena_records(&self) -> u32 {
5661        self.run_store.open_arena_records()
5662    }
5663
5664    pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
5665        self.run_store.arena_accepts(chunk, run)
5666    }
5667
5668    /// Appends `window` of `run`'s records to the open arena chunk, their
5669    /// placement under `turn`, keyed for a pass whose flat and turned
5670    /// records alternate often when `mixed_turns`, and the pipelines they
5671    /// draw with to `pipelines`. `clip` says how its variant tests its clip:
5672    /// an unturned run leaves a rect clip to its paint's scissor, never a
5673    /// rounded one.
5674    #[expect(clippy::too_many_arguments)]
5675    pub(crate) fn append_arena_run(
5676        &mut self,
5677        chunk: usize,
5678        run: &RunDraw,
5679        window: std::ops::Range<u32>,
5680        root_scale: f32,
5681        viewport: ViewportUniformParams,
5682        mixed_turns: bool,
5683        (depth, clip): (bool, SegmentClip),
5684        (pipelines, mut depth_keys): (&mut PipelineDemand, Option<&mut PipelineDemand>),
5685    ) -> u32 {
5686        let placement = &run.placement;
5687        let ablation = self.ablation.shape;
5688        let turn = viewport.transform;
5689        let turns = ShapeTurns::of(turn, mixed_turns);
5690        self.run_store.append_arena(
5691            chunk,
5692            run,
5693            window,
5694            (root_scale, turn),
5695            &mut |segment| {
5696                let key = |depth| {
5697                    Self::run_pipeline_key(
5698                        segment,
5699                        placement,
5700                        RunTier::Arena,
5701                        ablation,
5702                        turns,
5703                        (depth, clip),
5704                        viewport,
5705                    )
5706                };
5707                if let Some(keys) = depth_keys.as_deref_mut() {
5708                    keys.add(key(true), 0);
5709                }
5710                key(depth)
5711            },
5712            pipelines,
5713        )
5714    }
5715
5716    /// Moves the open chunk's draws since its last cut onto `out`, keeping
5717    /// it open.
5718    pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5719        self.run_store.cut_arena(&self.device, chunk, out);
5720    }
5721
5722    /// Uploads the open chunk and moves its draws since its last cut onto
5723    /// `out`.
5724    pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5725        if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
5726            self.frame_stats.add_shape_fill(fill);
5727        }
5728    }
5729
5730    pub(crate) fn draw_run_calls(
5731        &self,
5732        pass: &mut TrackedPass<'_, '_>,
5733        tables: ArenaBinding<'_>,
5734        uniform_slot: usize,
5735        draws: &[RunDrawCall],
5736        scissor: (u32, u32, u32, u32),
5737        stage: RunStage,
5738    ) -> Result<(), String> {
5739        match stage {
5740            RunStage::Paint => {
5741                if draws.is_empty() {
5742                    return Ok(());
5743                }
5744                self.frame_stats.bump_shapes();
5745                self.record_run_draws(
5746                    pass,
5747                    tables,
5748                    uniform_slot,
5749                    scissor,
5750                    draws.iter().map(PlannedRunDraw::paint),
5751                )
5752            }
5753            RunStage::Interiors => {
5754                let planned = interior_run_draws(draws);
5755                if planned.is_empty() {
5756                    return Ok(());
5757                }
5758                self.frame_stats
5759                    .shape_interior_draws
5760                    .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
5761                self.record_run_draws(pass, tables, uniform_slot, scissor, planned.into_iter())
5762            }
5763        }
5764    }
5765
5766    /// Records `planned` against one batch's tables, uniform and scissor.
5767    fn record_run_draws(
5768        &self,
5769        pass: &mut TrackedPass<'_, '_>,
5770        tables: ArenaBinding<'_>,
5771        uniform_slot: usize,
5772        scissor: (u32, u32, u32, u32),
5773        planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
5774    ) -> Result<(), String> {
5775        self.frame_stats.add_draw_calls(planned.len() as u32);
5776        let (x, y, width, height) = scissor;
5777        pass.set_scissor_rect(x, y, width, height);
5778        self.viewport_uniforms.bind(pass, uniform_slot)?;
5779        pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
5780        for (slot, buffer) in tables.records.into_iter().enumerate() {
5781            pass.set_vertex_buffer(slot as u32, buffer.slice(u64::from(tables.offsets[slot])..));
5782        }
5783        let mut bound_class = None;
5784        for draw in planned {
5785            let key = draw.key;
5786            let (pipeline, fallback) = self
5787                .shape_pipelines
5788                .get(key)
5789                .ok_or_else(|| format!("shape pipeline {key:?} was not prepared"))?;
5790            if fallback {
5791                self.frame_stats
5792                    .shape_pipeline_fallback_draws
5793                    .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5794            } else if !key.is_general() {
5795                self.frame_stats
5796                    .shape_specialized_draws
5797                    .set(self.frame_stats.shape_specialized_draws.get() + 1);
5798            }
5799            if bound_class != Some(draw.band_class) {
5800                pass.set_index_buffer(self.run_store.strip_index_buffer(draw.band_class).slice(..));
5801                bound_class = Some(draw.band_class);
5802            }
5803            pass.set_pipeline(pipeline);
5804            pass.draw_indexed(draw.indices, 0, draw.records);
5805        }
5806        Ok(())
5807    }
5808
5809    /// Draws a stored-run batch, whose draws are its range of `draws`.
5810    pub(crate) fn draw_store_run(
5811        &self,
5812        pass: &mut TrackedPass<'_, '_>,
5813        batch: &StoreRunBatch,
5814        draws: &[RunDrawCall],
5815        scissor: (u32, u32, u32, u32),
5816        stage: RunStage,
5817    ) -> Result<(), String> {
5818        self.draw_run_calls(
5819            pass,
5820            batch.tables.binding(),
5821            batch.uniform_slot,
5822            &draws[batch.draws.clone()],
5823            scissor,
5824            stage,
5825        )
5826    }
5827
5828    pub(crate) fn draw_arena(
5829        &self,
5830        pass: &mut TrackedPass<'_, '_>,
5831        chunk: usize,
5832        uniform_slot: usize,
5833        draws: &[RunDrawCall],
5834        scissor: (u32, u32, u32, u32),
5835        stage: RunStage,
5836    ) -> Result<(), String> {
5837        self.draw_run_calls(
5838            pass,
5839            self.run_store.arena_binding(chunk),
5840            uniform_slot,
5841            draws,
5842            scissor,
5843            stage,
5844        )
5845    }
5846    #[cfg(not(target_arch = "wasm32"))]
5847    pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
5848        self.display_format
5849    }
5850
5851    pub fn device_error_count(&self) -> u64 {
5852        self.device_errors.error_count()
5853    }
5854
5855    /// A pass that only applies `load_op` to the target, for a scene with
5856    /// nothing to draw that still needs its clear.
5857    pub(crate) fn clear_target<C: FrameCommandRecorder>(
5858        &self,
5859        recorder: &mut C,
5860        view: &wgpu::TextureView,
5861        load_op: wgpu::LoadOp<wgpu::Color>,
5862    ) {
5863        self.empty_pass(recorder, "Clear Pass", view, load_op);
5864    }
5865
5866    pub(crate) fn empty_pass<C: FrameCommandRecorder>(
5867        &self,
5868        recorder: &mut C,
5869        label: &'static str,
5870        view: &wgpu::TextureView,
5871        load_op: wgpu::LoadOp<wgpu::Color>,
5872    ) {
5873        let pass = recorder.begin_color_pass(label, view, load_op);
5874        drop(pass);
5875        recorder.record_pass();
5876    }
5877    pub(crate) fn draw_image_cmds(
5878        &self,
5879        pass: &mut TrackedPass<'_, '_>,
5880        image_slot: &ImageSlot,
5881        uniform_slot: usize,
5882        cmds: &[ImageDrawCmd],
5883        (blend_mode, depth): (BlendMode, bool),
5884        bound: Option<(u32, u32, u32, u32)>,
5885    ) -> Result<(), String> {
5886        if cmds.is_empty() {
5887            return Ok(());
5888        }
5889        self.frame_stats.bump_images();
5890        self.frame_stats.add_draw_calls(cmds.len() as u32);
5891        let mut bound_pipeline = None;
5892        self.viewport_uniforms.bind(pass, uniform_slot)?;
5893        pass.set_index_buffer(image_slot.indices.slice());
5894        pass.set_vertex_buffer(0, image_slot.vertices.slice());
5895        let mut clips_bound = false;
5896        for cmd in cmds {
5897            let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
5898                continue;
5899            };
5900            pass.set_scissor_rect(x, y, width, height);
5901            let variant = ImageVariant::of(cmd, depth);
5902            if bound_pipeline != Some(variant) {
5903                pass.set_pipeline(self.image_pipeline(blend_mode, variant));
5904                bound_pipeline = Some(variant);
5905            }
5906            pass.set_bind_group(1, &cmd.image.bind_group, &[]);
5907            let instance = match cmd.clip {
5908                Some(clip) => {
5909                    if !clips_bound {
5910                        let clips = image_slot
5911                            .clips
5912                            .as_ref()
5913                            .ok_or_else(|| "rounded image without clip instances".to_string())?;
5914                        pass.set_vertex_buffer(1, clips.slice());
5915                        clips_bound = true;
5916                    }
5917                    clip
5918                }
5919                None => 0,
5920            };
5921            pass.draw_indexed(
5922                cmd.index_start..(cmd.index_start + 6),
5923                0,
5924                instance..instance + 1,
5925            );
5926        }
5927        Ok(())
5928    }
5929
5930    pub(crate) fn draw_glyph_cmds(
5931        &self,
5932        pass: &mut TrackedPass<'_, '_>,
5933        (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
5934        uniform_slot: usize,
5935        cmds: &[GlyphDrawCmd],
5936        bound: Option<(u32, u32, u32, u32)>,
5937        frame: PassFrame,
5938    ) -> Result<(), String> {
5939        if cmds.is_empty() {
5940            return Ok(());
5941        }
5942        let whole_target = frame.scissor(bound);
5943        self.frame_stats.bump_text();
5944        let mut bound_atlas = None;
5945        // Which shared instances are bound, turned or plain, and which
5946        // pipeline; retained runs draw with a plain one.
5947        let mut shared_bound: Option<bool> = None;
5948        let mut bound_pipeline: Option<GlyphQuads> = None;
5949        let mut bound_run_instances: Option<&wgpu::Buffer> = None;
5950        let mut draws = 0u32;
5951        for draw in GlyphDraws::new(cmds) {
5952            let scissor = match draw.scissor {
5953                Some(scissor) => bounded_scissor(scissor, bound),
5954                None => Some(whole_target),
5955            };
5956            let Some((x, y, width, height)) = scissor else {
5957                continue;
5958            };
5959            pass.set_scissor_rect(x, y, width, height);
5960            if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
5961                pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
5962                bound_atlas = Some(draw.atlas);
5963            }
5964            draws += 1;
5965            match draw.step {
5966                GlyphDrawStep::Shared(instances, quads) => {
5967                    if bound_pipeline != Some(quads) {
5968                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5969                        bound_pipeline = Some(quads);
5970                    }
5971                    let turned = quads.turned();
5972                    if shared_bound != Some(turned) {
5973                        let slot =
5974                            if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
5975                                "shared glyph draw without glyph instances".to_string()
5976                            })?;
5977                        self.viewport_uniforms.bind(pass, uniform_slot)?;
5978                        pass.set_vertex_buffer(0, slot.slice());
5979                        shared_bound = Some(turned);
5980                        bound_run_instances = None;
5981                    }
5982                    pass.draw(0..GLYPH_QUAD_CORNERS, instances);
5983                }
5984                GlyphDrawStep::Retained {
5985                    run,
5986                    uniform_slot: retained_slot,
5987                    aligned,
5988                } => {
5989                    let quads = GlyphQuads::plain(aligned);
5990                    if bound_pipeline != Some(quads) {
5991                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5992                        bound_pipeline = Some(quads);
5993                    }
5994                    shared_bound = None;
5995                    self.viewport_uniforms.bind(pass, retained_slot)?;
5996                    let instances = run.span.instance_buffer();
5997                    if bound_run_instances != Some(instances) {
5998                        pass.set_vertex_buffer(0, instances.slice(..));
5999                        bound_run_instances = Some(instances);
6000                    }
6001                    pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
6002                }
6003            }
6004        }
6005        self.frame_stats.add_draw_calls(draws);
6006        Ok(())
6007    }
6008    pub(crate) fn append_image_draw_cmd(
6009        &mut self,
6010        image_draw: &ImageDraw,
6011        viewport: ViewportUniformParams,
6012        root_scale: f32,
6013        (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6014        image_clips: &mut Vec<DeviceRoundedClip>,
6015        image_cmds: &mut Vec<ImageDrawCmd>,
6016    ) -> Result<(), String> {
6017        let snap_delta = image_draw
6018            .snap_anchor
6019            .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6020            .unwrap_or_default();
6021        let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
6022        if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
6023            return Ok(());
6024        }
6025
6026        let (mut tint, cpu_filter) = tint_for_image(image_draw.color_filter, image_draw.alpha);
6027        if tint[3] <= 0.0 {
6028            return Ok(());
6029        }
6030
6031        let filtered_image = cpu_filter
6032            .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
6033            .transpose()?;
6034        let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
6035        if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
6036            for (channel, value) in tint[..3].iter_mut().zip(color) {
6037                *channel *= value as f32 / 255.0;
6038            }
6039        }
6040
6041        let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
6042        let Some(scissor) =
6043            scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
6044        else {
6045            return Ok(());
6046        };
6047
6048        let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
6049            return Ok(());
6050        };
6051        let device_quad = geometry.device_quad(root_scale);
6052        let index_start =
6053            push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
6054        let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
6055            image_clips.push(clip);
6056            image_clips.len() as u32 - 1
6057        });
6058        image_cmds.push(ImageDrawCmd {
6059            index_start,
6060            scissor,
6061            image: self.image_binding(prepared_image, geometry.sampling)?,
6062            clip,
6063        });
6064        Ok(())
6065    }
6066
6067    /// Uploads a pass's image and glyph quads into the frame's buffers.
6068    pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
6069        &self,
6070        recorder: &mut C,
6071        vertices: &[Vertex],
6072        indices: &[u32],
6073        clips: &[DeviceRoundedClip],
6074    ) -> ImageSlot {
6075        ImageSlot {
6076            vertices: recorder.upload_buffer(
6077                image_vertex_spec(),
6078                &self.device,
6079                bytemuck::cast_slice(vertices),
6080            ),
6081            indices: recorder.upload_buffer(
6082                image_index_spec(),
6083                &self.device,
6084                bytemuck::cast_slice(indices),
6085            ),
6086            clips: (!clips.is_empty()).then(|| {
6087                recorder.upload_buffer(
6088                    UploadAllocatorSpec::vertex(
6089                        "Image Clip Buffer",
6090                        std::mem::size_of::<DeviceRoundedClip>() as u64,
6091                    ),
6092                    &self.device,
6093                    bytemuck::cast_slice(clips),
6094                )
6095            }),
6096        }
6097    }
6098
6099    pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
6100        &self,
6101        recorder: &mut C,
6102        instances: &[GlyphInstance],
6103    ) -> BufferUpload {
6104        recorder.upload_buffer(
6105            glyph_instance_spec(),
6106            &self.device,
6107            bytemuck::cast_slice(instances),
6108        )
6109    }
6110
6111    pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
6112        &self,
6113        recorder: &mut C,
6114        glyphs: &[TurnedGlyph],
6115    ) -> BufferUpload {
6116        recorder.upload_buffer(
6117            turned_glyph_spec(),
6118            &self.device,
6119            bytemuck::cast_slice(glyphs),
6120        )
6121    }
6122
6123    fn glyph_atlas_entry_for(
6124        &mut self,
6125        glyph: &SoftwareGlyphAtlasGlyph,
6126    ) -> Result<GlyphAtlasEntry, String> {
6127        if let Some(entry) = self
6128            .text_glyph_atlas
6129            .upload_glyph(glyph, &mut self.frame_stats)
6130        {
6131            return Ok(entry);
6132        }
6133
6134        self.text_glyph_atlas.reset(
6135            &self.device,
6136            &self.image_bind_group_layout,
6137            GlyphSamplers {
6138                nearest: &self.image_nearest_sampler,
6139                linear: &self.image_linear_sampler,
6140            },
6141        );
6142        Err("text glyph atlas filled and was reset".to_string())
6143    }
6144
6145    /// Writes the glyphs the pass placed in the atlas to its texture, ahead
6146    /// of the submit that draws them.
6147    pub(crate) fn flush_glyph_uploads(&mut self) {
6148        self.text_glyph_atlas.flush_uploads(
6149            &self.queue,
6150            &mut self.frame_graph_executor,
6151            &mut self.frame_stats,
6152        );
6153    }
6154
6155    fn glyph_atlas_entry_for_cached(
6156        &mut self,
6157        glyph: &SoftwareGlyphAtlasPlacement,
6158    ) -> Option<GlyphAtlasEntry> {
6159        let entry = self
6160            .text_glyph_atlas
6161            .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
6162        self.frame_stats.record_text_glyph_atlas_hits(1);
6163        Some(entry)
6164    }
6165
6166    fn glyph_atlas_entry_for_placement(
6167        &mut self,
6168        glyph: &SoftwareGlyphAtlasPlacement,
6169    ) -> Result<GlyphAtlasEntry, String> {
6170        if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
6171            return Ok(entry);
6172        }
6173
6174        let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
6175            return Err("text glyph placement has no retained raster mask".to_string());
6176        };
6177        self.glyph_atlas_entry_for(&upload_glyph)
6178    }
6179
6180    /// The atlas entries of a run's drawing glyphs: of `cached_glyph_run`,
6181    /// which holds only those, or of the drawing glyphs of `collected_run`,
6182    /// a run just collected, whose new glyphs are uploaded here.
6183    fn prepare_text_glyph_entries(
6184        &mut self,
6185        run_key: TextGlyphRunCacheKey,
6186        atlas_generation: u64,
6187        cached_glyph_run: Option<&RunGlyphs>,
6188        collected_run: &[SoftwareGlyphAtlasRunGlyph],
6189        entries: &mut Vec<GlyphAtlasEntry>,
6190    ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
6191        entries.clear();
6192        let mut seen = RunAtlasEntries::new();
6193        if let Some(glyph_run) = cached_glyph_run {
6194            for glyph in glyph_run.iter() {
6195                entries.push(seen.entry(self, &glyph, |renderer| {
6196                    renderer.glyph_atlas_entry_for_placement(&glyph)
6197                })?);
6198            }
6199        } else {
6200            for run_glyph in collected_run {
6201                entries.push(seen.entry(
6202                    self,
6203                    &run_glyph.placement(),
6204                    |renderer| match run_glyph {
6205                        SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
6206                            renderer.glyph_atlas_entry_for_placement(placement)
6207                        }
6208                        SoftwareGlyphAtlasRunGlyph::New(glyph) => {
6209                            renderer.glyph_atlas_entry_for(glyph)
6210                        }
6211                    },
6212                )?);
6213            }
6214        }
6215
6216        let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
6217        if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
6218            cached.atlas_entries = Some(Rc::clone(&entries));
6219            cached.atlas_generation = atlas_generation;
6220        }
6221        Ok(entries)
6222    }
6223
6224    #[expect(clippy::too_many_arguments)]
6225    fn append_text_glyph_quad_run(
6226        &mut self,
6227        source_raster_rect: Rect,
6228        quads: GlyphRunQuads<'_>,
6229        (clip, cut): (Option<Rect>, Option<[f32; 4]>),
6230        viewport: ViewportUniformParams,
6231        root_scale: f32,
6232        glyph_instances: &mut GlyphInstances,
6233        record_cached_hits: bool,
6234    ) -> (GlyphQuads, GlyphExtent) {
6235        let start = glyph_instances.lens();
6236        let mut extent = GlyphExtent::EMPTY;
6237        let origin = [source_raster_rect.x, source_raster_rect.y];
6238        let bounds = quads.bounds.at(origin);
6239        let kind = if viewport.transform.is_identity()
6240            && cut.is_none_or(|edges| {
6241                bounds[0] >= edges[0]
6242                    && bounds[1] >= edges[1]
6243                    && bounds[2] <= edges[2]
6244                    && bounds[3] <= edges[3]
6245            })
6246            && quads
6247                .bounds
6248                .within_viewport(source_raster_rect, clip, viewport, root_scale)
6249        {
6250            // Every quad shows whole and uncut: they sit at whole pixels from
6251            // the run's origin, which then decides their alignment, and
6252            // their extent is the run's bounds.
6253            glyph_instances.plain.extend(quads.instances_at(origin));
6254            extent.add(bounds);
6255            GlyphQuads::plain(glyph_rect_aligned(
6256                [origin[0], origin[1], origin[0], origin[1]],
6257                viewport.offset,
6258            ))
6259        } else if viewport.transform.is_identity() {
6260            let plain = &mut glyph_instances.plain;
6261            let mut aligned = true;
6262            for_each_visible_glyph(
6263                source_raster_rect,
6264                quads,
6265                (clip, cut),
6266                viewport,
6267                root_scale,
6268                |glyph| {
6269                    aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
6270                    extent.add(glyph.rect);
6271                    plain.push(glyph);
6272                },
6273            );
6274            GlyphQuads::plain(aligned)
6275        } else {
6276            let turn = viewport.transform;
6277            let turned = &mut glyph_instances.turned;
6278            for_each_visible_glyph(
6279                source_raster_rect,
6280                quads,
6281                (clip, cut),
6282                viewport,
6283                root_scale,
6284                |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
6285            );
6286            GlyphQuads::Turned
6287        };
6288        let end = glyph_instances.lens();
6289        let appended = (end.0 - start.0) + (end.1 - start.1);
6290        if record_cached_hits {
6291            self.frame_stats
6292                .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
6293        }
6294        (kind, extent)
6295    }
6296
6297    /// The viewport a retained glyph run draws under: its vertices sit at
6298    /// its raster rect's origin, so an untransformed target moves its offset
6299    /// back by that origin, and a transformed one adds the origin to each
6300    /// vertex before its transform, as the shared path's vertices hold it.
6301    fn retained_glyph_viewport(
6302        viewport: ViewportUniformParams,
6303        source_raster_rect: Rect,
6304    ) -> ViewportUniformParams {
6305        if !viewport.transform.is_identity() {
6306            return ViewportUniformParams {
6307                origin: [source_raster_rect.x, source_raster_rect.y],
6308                ..viewport
6309            };
6310        }
6311        ViewportUniformParams {
6312            offset: [
6313                viewport.offset[0] - source_raster_rect.x,
6314                viewport.offset[1] - source_raster_rect.y,
6315            ],
6316            ..viewport
6317        }
6318    }
6319
6320    fn retained_text_glyph_run(
6321        &mut self,
6322        cache_key: TextGlyphRunCacheKey,
6323    ) -> Option<Rc<CachedGpuTextGlyphRun>> {
6324        let atlas_generation = self.text_glyph_atlas.generation();
6325        let frame = self.text_glyph_run_frame;
6326        self.text_glyph_gpu_run_cache
6327            .get(&cache_key)
6328            .filter(|cached| cached.atlas_generation == atlas_generation)
6329            .inspect(|cached| cached.last_frame.set(frame))
6330            .cloned()
6331    }
6332
6333    /// Opens a frame for text runs: runs no frame drew for
6334    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] leave the GPU cache and those no
6335    /// frame drew for [`TEXT_GLYPH_RUN_IDLE_FRAMES`] the CPU cache, and the
6336    /// arena takes back the quads dropped retained runs held.
6337    fn begin_text_glyph_run_frame(&mut self) {
6338        #[cfg(feature = "installed-fonts")]
6339        if let Some(fonts) = self.text_fonts.with_installed_faces() {
6340            // Text drawn before the install may show a missing glyph where an
6341            // installed face now has one.
6342            self.text_fonts = fonts;
6343            self.text_image_cache.clear();
6344            self.text_glyph_run_cache.clear();
6345            self.text_glyph_gpu_run_cache.clear();
6346        }
6347        self.text_glyph_run_frame += 1;
6348        let frame = self.text_glyph_run_frame;
6349        let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
6350        self.text_glyph_run_cache.set_cap(
6351            std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
6352                .unwrap_or(std::num::NonZeroUsize::MIN),
6353        );
6354        evict_idle(
6355            &mut self.text_glyph_gpu_run_cache,
6356            frame,
6357            TEXT_GLYPH_GPU_RUN_IDLE_FRAMES,
6358            |run| run.last_frame.get(),
6359        );
6360        evict_idle(
6361            &mut self.text_glyph_run_cache,
6362            frame,
6363            TEXT_GLYPH_RUN_IDLE_FRAMES,
6364            |run| run.last_frame.get(),
6365        );
6366        self.text_glyph_run_arena.begin_frame();
6367        let evacuating = self.text_glyph_run_arena.evacuating();
6368        if !evacuating.is_empty() {
6369            let moving: Vec<TextGlyphRunCacheKey> = self
6370                .text_glyph_gpu_run_cache
6371                .iter()
6372                .filter(|(_, run)| evacuating.contains(&run.span.chunk()))
6373                .map(|(key, _)| *key)
6374                .collect();
6375            for key in &moving {
6376                self.text_glyph_gpu_run_cache.pop(key);
6377            }
6378        }
6379    }
6380
6381    fn emit_retained_text_glyph_run_if_ready(
6382        &mut self,
6383        cache_key: TextGlyphRunCacheKey,
6384        quads: GlyphRunQuads<'_>,
6385        viewport: ViewportUniformParams,
6386        source_raster_rect: Rect,
6387        scissor: (u32, u32, u32, u32),
6388        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6389    ) -> bool {
6390        let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
6391            if self.ensure_retained_text_glyph_run(cache_key, quads) {
6392                self.retained_text_glyph_run(cache_key)
6393            } else {
6394                None
6395            }
6396        }) else {
6397            return false;
6398        };
6399        let uniform_slot =
6400            self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
6401        self.frame_stats
6402            .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
6403        // The run's quads sit at whole texels from its raster origin.
6404        let aligned = viewport.transform.is_identity()
6405            && glyph_rect_aligned(
6406                [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
6407                [viewport.offset[0], viewport.offset[1]],
6408            );
6409        glyph_cmds.push(GlyphDrawCmd::retained(
6410            (run, uniform_slot, aligned),
6411            scissor,
6412            self.text_glyph_atlas.bind_group(viewport.transform),
6413        ));
6414        true
6415    }
6416
6417    fn ensure_retained_text_glyph_run(
6418        &mut self,
6419        cache_key: TextGlyphRunCacheKey,
6420        quads: GlyphRunQuads<'_>,
6421    ) -> bool {
6422        let atlas_generation = self.text_glyph_atlas.generation();
6423        if self
6424            .text_glyph_gpu_run_cache
6425            .peek(&cache_key)
6426            .is_some_and(|cached| cached.atlas_generation == atlas_generation)
6427        {
6428            return true;
6429        }
6430
6431        let Some(span) = self
6432            .text_glyph_run_arena
6433            .insert(&self.device, quads.instances_at([0.0, 0.0]))
6434        else {
6435            return false;
6436        };
6437        self.text_glyph_gpu_run_cache.put(
6438            cache_key,
6439            Rc::new(CachedGpuTextGlyphRun {
6440                span,
6441                atlas_generation,
6442                last_frame: Cell::new(self.text_glyph_run_frame),
6443            }),
6444        );
6445        true
6446    }
6447    /// Appends the glyph atlas draws of `text_draw`, whose logical geometry
6448    /// `logical` the caller found drawing into a rect `viewport` shows.
6449    /// `false` when the text cannot draw from the atlas (animated motion, or
6450    /// a run the atlas cannot hold): nothing was appended, and the caller
6451    /// draws the text as a rasterized image instead.
6452    pub(crate) fn append_text_glyph_draws(
6453        &mut self,
6454        (text_draw, logical): (&TextDraw, (Rect, f32)),
6455        viewport: ViewportUniformParams,
6456        root_scale: f32,
6457        glyph_instances: &mut GlyphInstances,
6458        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6459    ) -> bool {
6460        let (_, raster_rect, _, text_scale, static_text_motion) =
6461            text_raster_geometry_at(text_draw, logical, root_scale);
6462        if !static_text_motion {
6463            return false;
6464        }
6465        let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
6466        let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
6467        let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
6468        let initial_instance_len = glyph_instances.lens();
6469        let initial_cmd_len = glyph_cmds.len();
6470        let drew = self
6471            .text_glyph_run(
6472                text_draw,
6473                raster_rect,
6474                text_scale,
6475                run_key,
6476                &mut collected_run,
6477            )
6478            .is_some_and(|run| {
6479                self.append_text_glyph_run(
6480                    TextGlyphRunDraw {
6481                        text_draw,
6482                        raster_rect,
6483                        run_key,
6484                        run,
6485                    },
6486                    (viewport, root_scale),
6487                    (&collected_run, &mut generated_entries),
6488                    glyph_instances,
6489                    glyph_cmds,
6490                )
6491            });
6492        self.scratch_text_glyph_run = collected_run;
6493        self.scratch_text_glyph_entries = generated_entries;
6494        if !drew {
6495            glyph_instances.truncate(initial_instance_len);
6496            glyph_cmds.truncate(initial_cmd_len);
6497        }
6498        drew
6499    }
6500
6501    /// The run of `text_draw` from the cache, or collected into
6502    /// `collected_run` and cached; `None` when the text cannot draw from the
6503    /// atlas.
6504    fn text_glyph_run(
6505        &mut self,
6506        text_draw: &TextDraw,
6507        raster_rect: Rect,
6508        text_scale: f32,
6509        run_key: TextGlyphRunCacheKey,
6510        collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
6511    ) -> Option<TextGlyphRunLookup> {
6512        let atlas_generation = self.text_glyph_atlas.generation();
6513        let frame = self.text_glyph_run_frame;
6514        self.text_glyph_runs_drawn += 1;
6515        if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
6516            cached.last_frame.set(frame);
6517            return Some(TextGlyphRunLookup {
6518                glyphs: cached.glyphs.clone(),
6519                bounds: cached.bounds,
6520                cached: true,
6521                entries: (cached.atlas_generation == atlas_generation)
6522                    .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
6523                    .flatten(),
6524            });
6525        }
6526        collected_run.clear();
6527        if collect_solid_text_atlas_run(
6528            text_draw.text.string().as_ref(),
6529            raster_rect,
6530            &text_draw.text_style,
6531            text_draw.color,
6532            text_draw.font_size,
6533            text_scale,
6534            &self.text_fonts,
6535            &mut self.text_glyph_mask_cache,
6536            collected_run,
6537        )
6538        .is_none()
6539        {
6540            log_text_atlas_fallback(text_draw);
6541            return None;
6542        }
6543        let Some(glyphs) = RunGlyphs::of(
6544            collected_run
6545                .iter()
6546                .map(SoftwareGlyphAtlasRunGlyph::placement),
6547            &mut self.run_glyph_scratch,
6548        ) else {
6549            log_text_atlas_fallback(text_draw);
6550            return None;
6551        };
6552        let bounds = GlyphRunBounds::of(glyphs.iter());
6553        self.frame_stats.record_text_glyph_run_collected();
6554        // A run this frame drew stays: the cache grows rather than evict it.
6555        let cache = &mut self.text_glyph_run_cache;
6556        if cache.len() == cache.cap().get()
6557            && cache
6558                .peek_lru()
6559                .is_some_and(|(_, run)| run.last_frame.get() == frame)
6560        {
6561            cache.set_cap(cache.cap().saturating_add(cache.len()));
6562        }
6563        self.text_glyph_run_cache.put(
6564            run_key,
6565            CachedTextGlyphRun {
6566                glyphs: glyphs.clone(),
6567                bounds,
6568                atlas_entries: None,
6569                atlas_generation: 0,
6570                last_frame: Cell::new(frame),
6571            },
6572        );
6573        Some(TextGlyphRunLookup {
6574            glyphs,
6575            bounds,
6576            cached: false,
6577            entries: None,
6578        })
6579    }
6580
6581    /// Appends the draws of a text's run: its retained quads when it has
6582    /// them, else its visible quads into the frame's shared glyphs. `false`
6583    /// when the atlas cannot hold its glyphs.
6584    fn append_text_glyph_run(
6585        &mut self,
6586        draw: TextGlyphRunDraw<'_>,
6587        (viewport, root_scale): (ViewportUniformParams, f32),
6588        (collected_run, generated_entries): (
6589            &[SoftwareGlyphAtlasRunGlyph],
6590            &mut Vec<GlyphAtlasEntry>,
6591        ),
6592        glyph_instances: &mut GlyphInstances,
6593        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6594    ) -> bool {
6595        let TextGlyphRunDraw {
6596            text_draw,
6597            raster_rect,
6598            run_key,
6599            run,
6600        } = draw;
6601        let draw_rect = Rect {
6602            x: raster_rect.x / root_scale,
6603            y: raster_rect.y / root_scale,
6604            width: raster_rect.width / root_scale,
6605            height: raster_rect.height / root_scale,
6606        };
6607        let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
6608        else {
6609            return true;
6610        };
6611        let texel = self.text_glyph_atlas.texel();
6612
6613        // A retained run's quads are uploaded whole: under a turn only the
6614        // shared path cuts them to a clip.
6615        let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
6616        if let Some(entries) = run.entries.as_ref()
6617            && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
6618            && !clip_needs_cut
6619            && self.emit_retained_text_glyph_run_if_ready(
6620                run_key,
6621                GlyphRunQuads {
6622                    glyphs: &run.glyphs,
6623                    entries,
6624                    texel,
6625                    bounds: run.bounds,
6626                },
6627                viewport,
6628                raster_rect,
6629                scissor,
6630                glyph_cmds,
6631            )
6632        {
6633            return true;
6634        }
6635
6636        let turned = !viewport.transform.is_identity();
6637        let instance_start = glyph_instances.len_of(turned);
6638        let (entries, entries_cached) = match run.entries {
6639            Some(entries) => (entries, true),
6640            None => {
6641                let Ok(entries) = self.prepare_text_glyph_entries(
6642                    run_key,
6643                    self.text_glyph_atlas.generation(),
6644                    run.cached.then_some(&run.glyphs),
6645                    collected_run,
6646                    generated_entries,
6647                ) else {
6648                    return false;
6649                };
6650                (entries, false)
6651            }
6652        };
6653        let quads = GlyphRunQuads {
6654            glyphs: &run.glyphs,
6655            entries: &entries,
6656            texel: self.text_glyph_atlas.texel(),
6657            bounds: run.bounds,
6658        };
6659        let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
6660        let (kind, extent) = self.append_text_glyph_quad_run(
6661            raster_rect,
6662            quads,
6663            (text_draw.clip, cut),
6664            viewport,
6665            root_scale,
6666            glyph_instances,
6667            entries_cached,
6668        );
6669        let instance_end = glyph_instances.len_of(turned);
6670        if instance_end > instance_start {
6671            let (clip, bounds) = if turned {
6672                (None, scissor)
6673            } else {
6674                shared_glyph_clip(extent, scissor, viewport)
6675            };
6676            glyph_cmds.push(GlyphDrawCmd::shared(
6677                (instance_start..instance_end, kind),
6678                clip,
6679                bounds,
6680                self.text_glyph_atlas.bind_group(viewport.transform),
6681            ));
6682        }
6683        true
6684    }
6685
6686    #[expect(clippy::too_many_arguments)]
6687    fn append_image_bitmap_draw_cmd(
6688        &mut self,
6689        image: &ImageBitmap,
6690        rect: Rect,
6691        clip: Option<Rect>,
6692        sampling: ImageSampling,
6693        viewport: ViewportUniformParams,
6694        root_scale: f32,
6695        image_vertices: &mut Vec<Vertex>,
6696        image_indices: &mut Vec<u32>,
6697        image_cmds: &mut Vec<ImageDrawCmd>,
6698    ) -> Result<(), String> {
6699        if rect.width <= 0.0 || rect.height <= 0.0 {
6700            return Ok(());
6701        }
6702
6703        let (device_quad, scissor_rect) =
6704            if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
6705                let left_px = (rect.x * root_scale).round();
6706                let top_px = (rect.y * root_scale).round();
6707                let width_px = (rect.width * root_scale).round().max(1.0);
6708                let height_px = (rect.height * root_scale).round().max(1.0);
6709                let snapped_rect = Rect {
6710                    x: left_px / root_scale,
6711                    y: top_px / root_scale,
6712                    width: width_px / root_scale,
6713                    height: height_px / root_scale,
6714                };
6715                let right_px = left_px + width_px;
6716                let bottom_px = top_px + height_px;
6717                (
6718                    [
6719                        [left_px, top_px],
6720                        [right_px, top_px],
6721                        [left_px, bottom_px],
6722                        [right_px, bottom_px],
6723                    ],
6724                    snapped_rect,
6725                )
6726            } else {
6727                (
6728                    rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
6729                    rect,
6730                )
6731            };
6732
6733        let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
6734            return Ok(());
6735        };
6736        let Some(uv_rect) = image_uv_rect(image, None) else {
6737            return Ok(());
6738        };
6739
6740        let index_start = push_image_quad(
6741            (image_vertices, image_indices),
6742            device_quad,
6743            [1.0, 1.0, 1.0, 1.0],
6744            &uv_rect,
6745        );
6746        image_cmds.push(ImageDrawCmd {
6747            index_start,
6748            scissor,
6749            image: self.image_binding(image, sampling)?,
6750            clip: None,
6751        });
6752        Ok(())
6753    }
6754
6755    /// Appends `text_draw` as a rasterized image if `viewport` shows it.
6756    pub(crate) fn append_text_image_draw_cmds(
6757        &mut self,
6758        text_draw: &TextDraw,
6759        viewport: ViewportUniformParams,
6760        root_scale: f32,
6761        image_vertices: &mut Vec<Vertex>,
6762        image_indices: &mut Vec<u32>,
6763        image_cmds: &mut Vec<ImageDrawCmd>,
6764    ) -> Result<(), String> {
6765        let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
6766            self.text_raster_geometry(text_draw, root_scale)
6767        else {
6768            return Ok(());
6769        };
6770        if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
6771            return Ok(());
6772        }
6773
6774        let raster_source = self.text_image_raster_source(
6775            text_draw,
6776            logical_rect,
6777            raster_rect,
6778            clip,
6779            root_scale,
6780            static_text_motion,
6781        );
6782        let source_draw = raster_source.draw.as_ref();
6783        let source_raster_rect = raster_source.raster_rect;
6784        let source_origin = if source_draw.text.string().span_styles().is_empty() {
6785            Point::new(source_raster_rect.x, source_raster_rect.y)
6786        } else {
6787            Point::new(raster_rect.x, raster_rect.y)
6788        };
6789
6790        let mut cache_key = Self::text_image_cache_key(
6791            source_draw,
6792            source_raster_rect,
6793            text_scale,
6794            static_text_motion,
6795        );
6796        if !source_draw.text.string().span_styles().is_empty() {
6797            let mut state = default_hash::new();
6798            cache_key.0.hash(&mut state);
6799            (source_origin.x - source_raster_rect.x)
6800                .to_bits()
6801                .hash(&mut state);
6802            (source_origin.y - source_raster_rect.y)
6803                .to_bits()
6804                .hash(&mut state);
6805            cache_key = TextImageCacheKey(state.finish());
6806        }
6807        let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
6808            self.frame_stats
6809                .record_text_image_cache_hit(cached.image.width(), cached.image.height());
6810            cached.image.clone()
6811        } else {
6812            let Some(image) = self.rasterize_text_draw_to_image(
6813                source_draw,
6814                source_raster_rect,
6815                source_origin,
6816                text_scale,
6817            ) else {
6818                return Ok(());
6819            };
6820            self.frame_stats
6821                .record_text_image_cache_miss(image.width(), image.height());
6822            self.text_image_cache.put(
6823                cache_key,
6824                CachedTextImage {
6825                    image: image.clone(),
6826                },
6827            );
6828            image
6829        };
6830
6831        let draw_origin = if static_text_motion {
6832            Point::new(
6833                source_raster_rect.x / root_scale,
6834                source_raster_rect.y / root_scale,
6835            )
6836        } else {
6837            Point::new(logical_rect.x, logical_rect.y)
6838        };
6839        let draw_rect = Rect {
6840            x: draw_origin.x,
6841            y: draw_origin.y,
6842            width: image.width() as f32 / root_scale,
6843            height: image.height() as f32 / root_scale,
6844        };
6845        self.append_image_bitmap_draw_cmd(
6846            &image,
6847            draw_rect,
6848            clip,
6849            sampling_under(ImageSampling::Nearest, viewport.transform),
6850            viewport,
6851            root_scale,
6852            image_vertices,
6853            image_indices,
6854            image_cmds,
6855        )
6856    }
6857
6858    fn text_image_raster_source<'a>(
6859        &mut self,
6860        text_draw: &'a TextDraw,
6861        logical_rect: Rect,
6862        raster_rect: Rect,
6863        clip: Option<Rect>,
6864        root_scale: f32,
6865        static_text_motion: bool,
6866    ) -> TextRasterSource<'a> {
6867        let Some(clip) = clip else {
6868            return TextRasterSource {
6869                draw: Cow::Borrowed(text_draw),
6870                raster_rect,
6871            };
6872        };
6873        if !static_text_motion || text_draw.text.string().text().find('\n').is_none() {
6874            return TextRasterSource {
6875                draw: Cow::Borrowed(text_draw),
6876                raster_rect,
6877            };
6878        }
6879
6880        if !text_draw.text.string().span_styles().is_empty() {
6881            let device_clip = Rect {
6882                x: (clip.x * root_scale).floor(),
6883                y: (clip.y * root_scale).floor(),
6884                width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
6885                height: ((clip.y + clip.height) * root_scale).ceil()
6886                    - (clip.y * root_scale).floor(),
6887            };
6888            return TextRasterSource {
6889                draw: Cow::Borrowed(text_draw),
6890                raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
6891            };
6892        }
6893
6894        let line_starts = self
6895            .text_line_index_cache
6896            .line_starts(text_draw.text.string());
6897        clipped_text_raster_source_with_line_starts(
6898            text_draw,
6899            logical_rect,
6900            raster_rect,
6901            clip,
6902            root_scale,
6903            line_starts.as_ref(),
6904        )
6905    }
6906
6907    fn text_raster_geometry(
6908        &self,
6909        text_draw: &TextDraw,
6910        root_scale: f32,
6911    ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
6912        text_raster_geometry_for_draw(text_draw, root_scale)
6913    }
6914
6915    fn text_image_cache_key(
6916        text_draw: &TextDraw,
6917        raster_rect: Rect,
6918        text_scale: f32,
6919        static_text_motion: bool,
6920    ) -> TextImageCacheKey {
6921        let mut state = default_hash::new();
6922        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6923        hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
6924        TextImageCacheKey(state.finish())
6925    }
6926
6927    /// The key of a static text's glyph run. A run places its glyphs from
6928    /// the text's origin and aligns its lines within the text block, so the
6929    /// size of the rect it draws in does not change it: only an empty rect,
6930    /// which draws nothing, does.
6931    fn text_glyph_run_cache_key(
6932        text_draw: &TextDraw,
6933        raster_rect: Rect,
6934        text_scale: f32,
6935    ) -> TextGlyphRunCacheKey {
6936        let mut state = default_hash::new();
6937        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6938        (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
6939        TextGlyphRunCacheKey(state.finish())
6940    }
6941
6942    fn rasterize_text_draw_to_image(
6943        &mut self,
6944        text_draw: &TextDraw,
6945        raster_rect: Rect,
6946        source_origin: Point,
6947        text_scale: f32,
6948    ) -> Option<ImageBitmap> {
6949        rasterize_annotated_text_region(
6950            text_draw.text.string().as_ref(),
6951            raster_rect,
6952            if text_draw.text.string().span_styles().is_empty() {
6953                Point::new(raster_rect.x, raster_rect.y)
6954            } else {
6955                source_origin
6956            },
6957            &text_draw.text_style,
6958            text_draw.color,
6959            text_draw.font_size,
6960            text_scale,
6961            &self.text_fonts,
6962            Some(&mut self.text_glyph_mask_cache),
6963        )
6964    }
6965}
6966
6967struct TextRasterSource<'a> {
6968    draw: Cow<'a, TextDraw>,
6969    raster_rect: Rect,
6970}
6971
6972fn clipped_text_raster_source_with_line_starts<'a>(
6973    text_draw: &'a TextDraw,
6974    logical_rect: Rect,
6975    raster_rect: Rect,
6976    clip: Rect,
6977    root_scale: f32,
6978    line_starts: &[usize],
6979) -> TextRasterSource<'a> {
6980    if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
6981        return TextRasterSource {
6982            draw: Cow::Borrowed(text_draw),
6983            raster_rect,
6984        };
6985    }
6986
6987    let Some(visible_rect) = logical_rect.intersect(clip) else {
6988        return TextRasterSource {
6989            draw: Cow::Borrowed(text_draw),
6990            raster_rect,
6991        };
6992    };
6993
6994    let line_count = line_starts.len().max(1);
6995    let line_height = logical_rect.height / line_count as f32;
6996    if !line_height.is_finite() || line_height <= 0.0 {
6997        return TextRasterSource {
6998            draw: Cow::Borrowed(text_draw),
6999            raster_rect,
7000        };
7001    }
7002
7003    let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
7004    let visible_bottom =
7005        ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
7006    let start_line = visible_top.saturating_sub(1).max(0) as usize;
7007    let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
7008    let end_line = end_line.min(line_count);
7009    if start_line == 0 && end_line >= line_count {
7010        return TextRasterSource {
7011            draw: Cow::Borrowed(text_draw),
7012            raster_rect,
7013        };
7014    }
7015
7016    let byte_start = line_starts[start_line];
7017    let byte_end = line_end_offset(text_draw.text.string().text(), line_starts, end_line - 1);
7018    if byte_start >= byte_end {
7019        return TextRasterSource {
7020            draw: Cow::Borrowed(text_draw),
7021            raster_rect,
7022        };
7023    }
7024
7025    let slice_y = logical_rect.y + start_line as f32 * line_height;
7026    let slice_height = (end_line - start_line) as f32 * line_height;
7027    let mut slice_raster_rect = Rect {
7028        x: logical_rect.x * root_scale,
7029        y: slice_y * root_scale,
7030        width: logical_rect.width * root_scale,
7031        height: slice_height * root_scale,
7032    };
7033    slice_raster_rect.x = slice_raster_rect.x.round();
7034    slice_raster_rect.y = slice_raster_rect.y.round();
7035    slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
7036    slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
7037
7038    let mut sliced_draw = text_draw.clone();
7039    sliced_draw.rect = Rect {
7040        x: logical_rect.x,
7041        y: slice_y,
7042        width: logical_rect.width,
7043        height: slice_height,
7044    };
7045    sliced_draw.text = DrawnText::of(
7046        Arc::new(text_draw.text.string().subsequence(byte_start..byte_end)),
7047        &text_draw.text_style,
7048    );
7049
7050    TextRasterSource {
7051        draw: Cow::Owned(sliced_draw),
7052        raster_rect: slice_raster_rect,
7053    }
7054}
7055
7056fn line_start_offsets(text: &str) -> Vec<usize> {
7057    let mut starts =
7058        Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
7059    starts.push(0);
7060    starts.extend(
7061        text.char_indices()
7062            .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
7063    );
7064    starts
7065}
7066
7067fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
7068    line_starts.get(line + 1).copied().unwrap_or(text.len())
7069}
7070
7071fn align_to(value: u32, alignment: u32) -> u32 {
7072    debug_assert!(alignment > 0);
7073    value.div_ceil(alignment) * alignment
7074}
7075
7076impl GpuRenderer {
7077    fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
7078        if !pixels.len().is_multiple_of(4) {
7079            return Err("Screenshot readback has an incomplete pixel".to_string());
7080        }
7081        Ok(pixels.to_vec())
7082    }
7083}
7084
7085/// The scissor of a logical rect in a target whose origin sits at
7086/// `viewport.offset` of the scene's device space, clamped to the target.
7087/// `None` when nothing of the rect lands in the target.
7088pub(crate) fn scissor_rect_for_rect(
7089    rect: Rect,
7090    root_scale: f32,
7091    viewport: ViewportUniformParams,
7092) -> Option<(u32, u32, u32, u32)> {
7093    let width = viewport.width as f32;
7094    let height = viewport.height as f32;
7095    let mut left = canonicalize_device_coordinate(rect.x * root_scale);
7096    let mut top = canonicalize_device_coordinate(rect.y * root_scale);
7097    let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
7098    let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
7099    if !viewport.transform.is_identity() {
7100        let bounds = viewport.transform.target_bounds(Rect {
7101            x: left,
7102            y: top,
7103            width: right - left,
7104            height: bottom - top,
7105        });
7106        (left, top) = (bounds.x, bounds.y);
7107        (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
7108    }
7109    let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
7110    let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
7111    let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
7112    let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
7113    if right <= left || bottom <= top {
7114        return None;
7115    }
7116    Some((
7117        left as u32,
7118        top as u32,
7119        (right - left) as u32,
7120        (bottom - top) as u32,
7121    ))
7122}
7123
7124fn scissor_rect_for_layer(
7125    rect: Rect,
7126    clip: Option<Rect>,
7127    root_scale: f32,
7128    viewport: ViewportUniformParams,
7129) -> Option<(u32, u32, u32, u32)> {
7130    let clipped_rect = match clip {
7131        Some(clip_rect) => rect.intersect(clip_rect)?,
7132        None => rect,
7133    };
7134    scissor_rect_for_rect(clipped_rect, root_scale, viewport)
7135}
7136fn tint_for_image(
7137    color_filter: Option<ColorFilter>,
7138    alpha: f32,
7139) -> ([f32; 4], Option<ColorFilter>) {
7140    let alpha = alpha.clamp(0.0, 1.0);
7141    match color_filter {
7142        Some(filter) if filter.supports_gpu_vertex_modulation() => {
7143            let Some(tint) = filter.gpu_vertex_tint() else {
7144                return ([1.0, 1.0, 1.0, alpha], Some(filter));
7145            };
7146            (
7147                [
7148                    tint[0].clamp(0.0, 1.0),
7149                    tint[1].clamp(0.0, 1.0),
7150                    tint[2].clamp(0.0, 1.0),
7151                    (tint[3] * alpha).clamp(0.0, 1.0),
7152                ],
7153                None,
7154            )
7155        }
7156        Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
7157        None => ([1.0, 1.0, 1.0, alpha], None),
7158    }
7159}
7160
7161/// The rounded clip an image takes in place, in device pixels: one instance
7162/// its draw reads, beside the quad's vertices.
7163#[repr(C)]
7164#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7165pub(crate) struct DeviceRoundedClip {
7166    rect: [f32; 4],
7167    radius: f32,
7168}
7169
7170impl DeviceRoundedClip {
7171    const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
7172        4 => Float32x4,
7173        5 => Float32,
7174    ];
7175
7176    fn desc() -> wgpu::VertexBufferLayout<'static> {
7177        wgpu::VertexBufferLayout {
7178            array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
7179            step_mode: wgpu::VertexStepMode::Instance,
7180            attributes: &Self::ATTRIBS,
7181        }
7182    }
7183
7184    /// The rounded clip `image` takes at `root_scale`, scaled as a run's
7185    /// placement scales its clip.
7186    fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
7187        let rounding = image.rounding.filter(|_| image.clip.is_some())?;
7188        let device =
7189            crate::geometry::device_rect(rounding.rect, root_scale, image.snap_anchor.is_some());
7190        Some(Self {
7191            rect: [device.x, device.y, device.width, device.height],
7192            radius: rounding.radius * root_scale,
7193        })
7194    }
7195}
7196
7197/// Appends an image quad over `device_quad` and its two triangles, and
7198/// returns the index its triangles start at.
7199fn push_image_quad(
7200    (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
7201    device_quad: [[f32; 2]; 4],
7202    color: [f32; 4],
7203    uv_rect: &ImageUvRect,
7204) -> u32 {
7205    let base_vertex = vertices.len() as u32;
7206    let index_start = indices.len() as u32;
7207    indices.extend_from_slice(&[
7208        base_vertex,
7209        base_vertex + 1,
7210        base_vertex + 2,
7211        base_vertex + 2,
7212        base_vertex + 1,
7213        base_vertex + 3,
7214    ]);
7215    let corners = [
7216        [uv_rect.min[0], uv_rect.min[1]],
7217        [uv_rect.max[0], uv_rect.min[1]],
7218        [uv_rect.min[0], uv_rect.max[1]],
7219        [uv_rect.max[0], uv_rect.max[1]],
7220    ];
7221    vertices.extend(
7222        device_quad
7223            .into_iter()
7224            .zip(corners)
7225            .map(|(position, uv)| Vertex {
7226                position,
7227                color,
7228                uv,
7229                uv_bounds: uv_rect.sample_bounds,
7230            }),
7231    );
7232    index_start
7233}
7234
7235fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
7236    let Some(src) = src_rect else {
7237        return Some(ImageUvRect {
7238            min: [0.0, 0.0],
7239            max: [1.0, 1.0],
7240            sample_bounds: [0.0, 0.0, 1.0, 1.0],
7241        });
7242    };
7243
7244    let (u_min, u_max, u_bound_min, u_bound_max) =
7245        source_axis_uv(src.x, src.width, image.width() as f32)?;
7246    let (v_min, v_max, v_bound_min, v_bound_max) =
7247        source_axis_uv(src.y, src.height, image.height() as f32)?;
7248
7249    Some(ImageUvRect {
7250        min: [u_min, v_min],
7251        max: [u_max, v_max],
7252        sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
7253    })
7254}
7255
7256/// `entry`'s rect in an atlas whose texel is `texel` of its side, an
7257/// exact power of two: the products are the quotients by the side.
7258fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, texel: f32) -> ImageUvRect {
7259    let min = [entry.x as f32 * texel, entry.y as f32 * texel];
7260    let max = [
7261        (entry.x + entry.width) as f32 * texel,
7262        (entry.y + entry.height) as f32 * texel,
7263    ];
7264    let center_min = [
7265        (entry.x as f32 + 0.5) * texel,
7266        (entry.y as f32 + 0.5) * texel,
7267    ];
7268    let center_max = [
7269        (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) * texel,
7270        (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) * texel,
7271    ];
7272    ImageUvRect {
7273        min,
7274        max,
7275        sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
7276    }
7277}
7278
7279#[derive(Clone, Copy)]
7280pub(crate) struct ResolvedImageGeometry {
7281    pub(crate) rect: Rect,
7282    pub(crate) clip: Option<Rect>,
7283    pub(crate) sampling: ImageSampling,
7284    quad: [[f32; 2]; 4],
7285    snap_anchored: bool,
7286}
7287
7288pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
7289    let snap_delta = image
7290        .snap_anchor
7291        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
7292        .unwrap_or_default();
7293    resolve_image_geometry_with_delta(image, root_scale, snap_delta)
7294}
7295
7296fn resolve_image_geometry_with_delta(
7297    image: &ImageDraw,
7298    root_scale: f32,
7299    snap_delta: Point,
7300) -> ResolvedImageGeometry {
7301    let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
7302    let mut quad = translate_quad(image.quad, snap_delta);
7303    snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
7304    ResolvedImageGeometry {
7305        rect,
7306        clip: image.clip,
7307        sampling: image.sampling,
7308        quad,
7309        snap_anchored: image.snap_anchor.is_some(),
7310    }
7311}
7312
7313impl ResolvedImageGeometry {
7314    pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
7315        nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
7316            if self.snap_anchored {
7317                canonicalized_scaled_quad(self.quad, root_scale)
7318            } else {
7319                scaled_quad(self.quad, root_scale)
7320            }
7321        })
7322    }
7323}
7324
7325fn snap_nearest_image_to_device_pixels(
7326    sampling: ImageSampling,
7327    rect: &mut Rect,
7328    quad: &mut [[f32; 2]; 4],
7329    root_scale: f32,
7330) {
7331    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7332        return;
7333    }
7334
7335    let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
7336        return;
7337    };
7338
7339    let left_px = (quad_rect.x * root_scale).round();
7340    let top_px = (quad_rect.y * root_scale).round();
7341    let width_px = (quad_rect.width * root_scale).round().max(1.0);
7342    let height_px = (quad_rect.height * root_scale).round().max(1.0);
7343    let snapped = Rect {
7344        x: left_px / root_scale,
7345        y: top_px / root_scale,
7346        width: width_px / root_scale,
7347        height: height_px / root_scale,
7348    };
7349
7350    *rect = snapped;
7351    *quad = crate::rect_to_quad(snapped);
7352}
7353
7354fn nearest_image_device_quad(
7355    sampling: ImageSampling,
7356    quad: [[f32; 2]; 4],
7357    root_scale: f32,
7358) -> Option<[[f32; 2]; 4]> {
7359    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7360        return None;
7361    }
7362
7363    let rect = axis_aligned_quad_rect(quad)?;
7364    let left_px = (rect.x * root_scale).round();
7365    let top_px = (rect.y * root_scale).round();
7366    let width_px = (rect.width * root_scale).round().max(1.0);
7367    let height_px = (rect.height * root_scale).round().max(1.0);
7368    let right_px = left_px + width_px;
7369    let bottom_px = top_px + height_px;
7370    Some([
7371        [left_px, top_px],
7372        [right_px, top_px],
7373        [left_px, bottom_px],
7374        [right_px, bottom_px],
7375    ])
7376}
7377
7378fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
7379    if !start.is_finite()
7380        || !extent.is_finite()
7381        || !image_extent.is_finite()
7382        || extent == 0.0
7383        || image_extent <= 0.0
7384    {
7385        return None;
7386    }
7387
7388    let end = start + extent;
7389    let edge_min = start.min(end).clamp(0.0, image_extent);
7390    let edge_max = start.max(end).clamp(0.0, image_extent);
7391    if edge_max <= edge_min {
7392        return None;
7393    }
7394
7395    let center_min = edge_min + 0.5;
7396    let center_max = edge_max - 0.5;
7397    let (bound_min, bound_max) = if center_min <= center_max {
7398        (center_min, center_max)
7399    } else {
7400        let center = (edge_min + edge_max) * 0.5;
7401        (center, center)
7402    };
7403
7404    Some((
7405        edge_min / image_extent,
7406        edge_max / image_extent,
7407        bound_min / image_extent,
7408        bound_max / image_extent,
7409    ))
7410}
7411
7412fn apply_filter_to_bitmap(image: &ImageBitmap, filter: ColorFilter) -> Result<ImageBitmap, String> {
7413    let pixel_count = image.width() as usize * image.height() as usize;
7414    let mut filtered = Vec::with_capacity(pixel_count * 4);
7415    for index in 0..pixel_count {
7416        let pixel = image.rgba8_pixel(index);
7417        let rgba = [
7418            pixel[0] as f32 / 255.0,
7419            pixel[1] as f32 / 255.0,
7420            pixel[2] as f32 / 255.0,
7421            pixel[3] as f32 / 255.0,
7422        ];
7423        let out = filter.apply_rgba(rgba);
7424        filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
7425        filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
7426        filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
7427        filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
7428    }
7429    ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
7430        .map_err(|error| format!("failed to build filtered bitmap: {error}"))
7431}
7432
7433/// How a text raster samples its texels under a segment transform: as it
7434/// asks on the pixel grid, and filtered once a transform turns it off the
7435/// grid, where no texel lands on a pixel for nearest sampling to keep.
7436fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
7437    if transform.is_identity() {
7438        sampling
7439    } else {
7440        ImageSampling::Linear
7441    }
7442}
7443
7444/// The rounded mask a shadow's composite applies, in the scene's device
7445/// pixels: an inner shadow masks itself to its fill shape, and a shadow
7446/// lowered out of a clipped layer masks itself to that layer's rounded clip.
7447pub(crate) fn shadow_composite_mask(
7448    shadow: &ShadowDraw,
7449    snap_anchor: Option<SnapAnchor>,
7450    root_scale: f32,
7451) -> Option<RoundedCompositeMask> {
7452    inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
7453        shadow.rounded_clip.map(|clip| RoundedCompositeMask {
7454            rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
7455            radii: clip.radii.map(|radius| radius * root_scale),
7456        })
7457    })
7458}
7459
7460/// A scene holding just a shadow's own draws, in the order they arrive, so
7461/// the shadow source renders through the same pass encoder as everything
7462/// else.
7463fn shadow_scene(
7464    shapes: Option<&RunDraw>,
7465    texts: &[TextDraw],
7466    input_margin: f32,
7467) -> CompositorScene {
7468    let mut scene = CompositorScene::new();
7469    if let Some(run) = shapes {
7470        scene.push_run(run.clone());
7471    }
7472    for text in texts {
7473        let z_index = scene.next_z();
7474        scene.draw_ops.push(DrawOp {
7475            z_index,
7476            kind: DrawOpKind::Text(scene.texts.len()),
7477        });
7478        let mut source_text = text.clone();
7479        source_text.clip = source_text
7480            .clip
7481            .map(|clip| expand_rect(clip, input_margin, input_margin));
7482        scene.texts.push(source_text);
7483        scene.next_z += 1;
7484    }
7485    scene
7486}
7487
7488/// The whole device pixels a logical rect covers, or `None` when it covers
7489/// none or more than a texture can hold.
7490fn device_pixel_bounds(
7491    rect: Rect,
7492    root_scale: f32,
7493    max_texture_dim: u32,
7494) -> Option<DevicePixelBounds> {
7495    let x = (rect.x * root_scale).floor();
7496    let y = (rect.y * root_scale).floor();
7497    let right = ((rect.x + rect.width) * root_scale).ceil();
7498    let bottom = ((rect.y + rect.height) * root_scale).ceil();
7499    let width = (right - x).max(0.0) as u32;
7500    let height = (bottom - y).max(0.0) as u32;
7501    if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
7502        return None;
7503    }
7504    Some(DevicePixelBounds {
7505        x,
7506        y,
7507        width,
7508        height,
7509    })
7510}
7511fn inner_shadow_composite_mask(
7512    shadow: &ShadowDraw,
7513    root_scale: f32,
7514) -> Option<RoundedCompositeMask> {
7515    let run = shadow.shapes.as_ref()?;
7516    if !run
7517        .tables()
7518        .shapes
7519        .iter()
7520        .any(|record| record.blend_mode() == BlendMode::DstOut)
7521    {
7522        return None;
7523    }
7524    let fill = run.tables().shapes.get(0)?;
7525    let rect = run.placement.translated_bounds(fill.stored_rect());
7526    if rect.width <= 0.0 || rect.height <= 0.0 {
7527        return None;
7528    }
7529    let resolved =
7530        cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
7531            top_left: fill.radii[0],
7532            top_right: fill.radii[1],
7533            bottom_right: fill.radii[2],
7534            bottom_left: fill.radii[3],
7535        })
7536        .resolve(rect.width, rect.height);
7537    let radii = [
7538        resolved.top_left * root_scale,
7539        resolved.top_right * root_scale,
7540        resolved.bottom_left * root_scale,
7541        resolved.bottom_right * root_scale,
7542    ];
7543
7544    Some(RoundedCompositeMask {
7545        rect: mask_rect(anchored_device_rect(
7546            rect,
7547            run.placement.snap_anchor,
7548            root_scale,
7549        )),
7550        radii,
7551    })
7552}
7553
7554/// One draw call of a run batch's stage: its pipeline, the strip index
7555/// buffer it binds and the indices and records it instances.
7556#[derive(Clone, Debug, PartialEq, Eq)]
7557pub(crate) struct PlannedRunDraw {
7558    pub(crate) key: ShapePipelineKey,
7559    pub(crate) band_class: u8,
7560    pub(crate) indices: std::ops::Range<u32>,
7561    pub(crate) records: std::ops::Range<u32>,
7562}
7563
7564impl PlannedRunDraw {
7565    /// A draw of the paint, as it was recorded.
7566    fn paint(draw: &RunDrawCall) -> Self {
7567        Self {
7568            key: draw.key,
7569            band_class: draw.band_class,
7570            indices: draw.indices(),
7571            records: draw.records.clone(),
7572        }
7573    }
7574}
7575
7576/// The draw calls laying a batch's opaque interiors down: last first, so
7577/// they go down front to back, one call over each stretch of neighbouring
7578/// draws that share the interior pipeline, cut to the span from the stretch's
7579/// first draw holding an occluder to its last. The draws between ride along:
7580/// the pipeline lays any record's exact interior down and skips the rest, so
7581/// taking them costs a few vertices rather than a call, and it shades only a
7582/// record's quad, the first two triangles of every band class's pattern.
7583pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
7584    struct Stretch {
7585        key: ShapePipelineKey,
7586        start: u32,
7587        span: Option<PlannedRunDraw>,
7588    }
7589    let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
7590    let mut stretch: Option<Stretch> = None;
7591    for draw in draws.iter().rev() {
7592        let Some(key) = draw.key.interior() else {
7593            planned.extend(stretch.take().and_then(|open| open.span));
7594            continue;
7595        };
7596        if stretch
7597            .as_ref()
7598            .is_some_and(|open| open.key != key || open.start != draw.records.end)
7599        {
7600            planned.extend(stretch.take().and_then(|open| open.span));
7601        }
7602        let open = stretch.get_or_insert(Stretch {
7603            key,
7604            start: draw.records.end,
7605            span: None,
7606        });
7607        open.start = draw.records.start;
7608        if !draw.occluders {
7609            continue;
7610        }
7611        match &mut open.span {
7612            Some(span) => span.records.start = draw.records.start,
7613            None => {
7614                open.span = Some(PlannedRunDraw {
7615                    key,
7616                    band_class: draw.band_class,
7617                    indices: 0..cranpose_ui_graphics::strip_indices(1),
7618                    records: draw.records.clone(),
7619                });
7620            }
7621        }
7622    }
7623    planned.extend(stretch.and_then(|open| open.span));
7624    planned
7625}
7626
7627/// Drops the entries of `cache` no frame drew for more than `idle_frames`
7628/// before `frame`: the least recently used first, which is the order they
7629/// were last drawn in.
7630fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
7631    cache: &mut BoundedLruCache<K, V>,
7632    frame: u64,
7633    idle_frames: u64,
7634    last_frame: impl Fn(&V) -> u64,
7635) {
7636    while cache
7637        .peek_lru()
7638        .is_some_and(|(_, value)| frame.saturating_sub(last_frame(value)) > idle_frames)
7639    {
7640        cache.pop_lru();
7641    }
7642}
7643
7644/// Cuts the run draws from `start` on to `window` of their records, counted
7645/// across them in order, and drops the draws left with none.
7646fn window_draws(draws: &mut Vec<RunDrawCall>, start: usize, window: &std::ops::Range<u32>) {
7647    let mut relative = 0u32;
7648    let mut kept = start;
7649    for index in start..draws.len() {
7650        let draw = &mut draws[index];
7651        let count = draw.records.end - draw.records.start;
7652        let first = relative;
7653        relative += count;
7654        let keep_start = window.start.max(first).min(first + count);
7655        let keep_end = window.end.min(first + count).max(keep_start);
7656        draw.records =
7657            draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
7658        if draw.records.start < draw.records.end {
7659            draws.swap(kept, index);
7660            kept += 1;
7661        }
7662    }
7663    draws.truncate(kept);
7664}
7665
7666#[cfg(test)]
7667#[path = "tests/render_text_bounds_tests.rs"]
7668mod text_bounds_tests;
7669
7670#[cfg(test)]
7671#[path = "tests/render_retained_glyph_tests.rs"]
7672mod retained_glyph_tests;
7673
7674#[cfg(test)]
7675#[path = "tests/frame_clear_tests.rs"]
7676mod frame_clear_tests;
7677
7678#[cfg(test)]
7679#[path = "tests/render_clip_scissor_tests.rs"]
7680mod clip_scissor_tests;
7681
7682#[cfg(test)]
7683#[path = "tests/glyph_kind_tests.rs"]
7684mod glyph_kind_tests;
7685
7686#[cfg(test)]
7687#[path = "tests/glyph_run_bounds_tests.rs"]
7688mod glyph_run_bounds_tests;
7689
7690#[cfg(test)]
7691#[path = "tests/shape_variant_tests.rs"]
7692mod shape_variant_tests;