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