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