Skip to main content

sui_render_wgpu/
text.rs

1use crate::geometry::hash_normalized_analytic_path;
2use crate::geometry::hash_path;
3use crate::text_policy::StemDarkening;
4use crate::text_policy::TextHinting;
5use crate::text_policy::TextRenderMode;
6use std::hash::Hash;
7use sui_core::Path as ScenePath;
8use sui_core::Size;
9use sui_core::Transform;
10use sui_core::Vector;
11use sui_scene::StrokeStyle;
12pub use sui_scene::TextSubpixelOrder;
13use sui_text::ResolvedTextFace;
14use sui_text::TextLayoutCacheSnapshot;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct GlyphCacheSnapshot {
18    pub entries: usize,
19    pub hits: usize,
20    pub misses: usize,
21}
22
23impl GlyphCacheSnapshot {
24    pub const fn requests(self) -> usize {
25        self.hits + self.misses
26    }
27
28    pub fn hit_rate(self) -> f64 {
29        let requests = self.requests();
30        if requests == 0 {
31            0.0
32        } else {
33            self.hits as f64 / requests as f64
34        }
35    }
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub struct RendererTextCacheSnapshot {
40    pub layout: TextLayoutCacheSnapshot,
41    pub glyph: GlyphCacheSnapshot,
42    pub path: GlyphCacheSnapshot,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub(crate) struct TextFrameStats {
47    pub(crate) glyph_instances: usize,
48    pub(crate) glyph_upload_bytes: u64,
49    pub(crate) atlas_miss_count: usize,
50    pub(crate) atlas_miss_time_us: u64,
51}
52
53pub(crate) const TEXT_ATLAS_WIDTH: usize = 2048;
54pub(crate) const TEXT_ATLAS_HEIGHT: usize = 2048;
55pub(crate) const TEXT_ATLAS_PADDING: usize = 2;
56/// Maximum number of atlas pages (texture-array layers) before whole-page LRU eviction kicks in.
57/// Each page is TEXT_ATLAS_WIDTH x TEXT_ATLAS_HEIGHT x 4 bytes (~16 MB); 4 pages -> ~64 MB.
58pub(crate) const TEXT_ATLAS_MAX_PAGES: usize = 4;
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub(crate) struct GlyphFaceCacheKey {
62    pub(crate) data_ptr: usize,
63    pub(crate) data_len: usize,
64    pub(crate) face_index: u32,
65}
66
67impl GlyphFaceCacheKey {
68    pub(crate) fn new(face: &ResolvedTextFace) -> Self {
69        Self {
70            data_ptr: face.data_ptr(),
71            data_len: face.data_len(),
72            face_index: face.face_index(),
73        }
74    }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78pub(crate) enum TextAtlasColorMode {
79    Grayscale,
80    LcdSubpixel,
81}
82
83impl From<TextRenderMode> for TextAtlasColorMode {
84    fn from(value: TextRenderMode) -> Self {
85        match value {
86            TextRenderMode::Grayscale => Self::Grayscale,
87            TextRenderMode::LcdSubpixel => Self::LcdSubpixel,
88        }
89    }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Hash)]
93pub(crate) struct GlyphCacheKey {
94    pub(crate) face: GlyphFaceCacheKey,
95    pub(crate) glyph_id: u16,
96    pub(crate) scale_bucket: u32,
97    pub(crate) subpixel_offset: GlyphSubpixelOffsetKey,
98    pub(crate) atlas_color_mode: TextAtlasColorMode,
99    pub(crate) subpixel_order: TextSubpixelOrderCacheKey,
100    pub(crate) text_hinting: TextHintingCacheKey,
101    pub(crate) hinting_target: GlyphHintingTarget,
102    pub(crate) stem_darkening: StemDarkeningCacheKey,
103    /// Requested `wght` axis value — different weights of a variable font rasterize to distinct
104    /// outlines and must cache separately. (Static fonts ignore the axis, so this is constant.)
105    pub(crate) weight: u16,
106}
107
108impl GlyphCacheKey {
109    #[allow(clippy::too_many_arguments)]
110    pub(crate) fn new(
111        face: GlyphFaceCacheKey,
112        glyph_id: u16,
113        scale_bucket: u32,
114        subpixel_offset: GlyphSubpixelOffsetKey,
115        text_render_mode: TextRenderMode,
116        text_subpixel_order: TextSubpixelOrder,
117        text_hinting: TextHinting,
118        stem_darkening: StemDarkening,
119        weight: u16,
120    ) -> Self {
121        Self {
122            face,
123            glyph_id,
124            scale_bucket,
125            subpixel_offset,
126            atlas_color_mode: TextAtlasColorMode::from(text_render_mode),
127            subpixel_order: TextSubpixelOrderCacheKey::from(text_subpixel_order),
128            text_hinting: TextHintingCacheKey::from(text_hinting),
129            hinting_target: match text_hinting.normalized() {
130                TextHinting::None => GlyphHintingTarget::None,
131                TextHinting::Slight { .. } => GlyphHintingTarget::Symmetric,
132            },
133            stem_darkening: StemDarkeningCacheKey::from(stem_darkening),
134            weight,
135        }
136    }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140pub(crate) enum TextSubpixelOrderCacheKey {
141    None,
142    Rgb,
143    Bgr,
144}
145
146impl From<TextSubpixelOrder> for TextSubpixelOrderCacheKey {
147    fn from(value: TextSubpixelOrder) -> Self {
148        match value {
149            TextSubpixelOrder::None => Self::None,
150            TextSubpixelOrder::Rgb => Self::Rgb,
151            TextSubpixelOrder::Bgr => Self::Bgr,
152        }
153    }
154}
155
156pub(crate) const GLYPH_SUBPIXEL_VARIANTS_X: u8 = 4;
157pub(crate) const GLYPH_SUBPIXEL_VARIANTS_Y: u8 = 1;
158
159/// Zeno translates outlines, whereas physical subpixel positions translate
160/// sample locations. A BGRA mask therefore needs the opposite offsets: blue
161/// samples to the right, red to the left. Do not infer this from format names.
162pub(crate) const LCD_SUBPIXEL_OFFSET: f32 = 1.0 / 3.0;
163
164pub(crate) fn lcd_bgra_format() -> swash::zeno::Format {
165    swash::zeno::Format::CustomSubpixel([-LCD_SUBPIXEL_OFFSET, 0.0, LCD_SUBPIXEL_OFFSET])
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169pub(crate) enum GlyphHintingTarget {
170    None,
171    Symmetric,
172    Asymmetric,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
176pub(crate) struct GlyphSubpixelOffsetKey {
177    pub(crate) x: u8,
178    pub(crate) y: u8,
179}
180
181impl GlyphSubpixelOffsetKey {
182    pub(crate) fn new(x: u8, _y: u8) -> Self {
183        Self {
184            x: x % GLYPH_SUBPIXEL_VARIANTS_X,
185            y: 0,
186        }
187    }
188
189    pub(crate) fn as_swash_offset(self) -> swash::zeno::Vector {
190        swash::zeno::Vector::new(
191            f32::from(self.x) / f32::from(GLYPH_SUBPIXEL_VARIANTS_X),
192            f32::from(self.y) / f32::from(GLYPH_SUBPIXEL_VARIANTS_Y),
193        )
194    }
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
198pub(crate) enum TextHintingCacheKey {
199    None,
200    Slight { max_ppem_bits: u32 },
201}
202
203impl From<TextHinting> for TextHintingCacheKey {
204    fn from(value: TextHinting) -> Self {
205        match value.normalized() {
206            TextHinting::None => Self::None,
207            TextHinting::Slight { max_ppem } => Self::Slight {
208                max_ppem_bits: max_ppem.to_bits(),
209            },
210        }
211    }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub(crate) enum StemDarkeningCacheKey {
216    None,
217    Enabled {
218        max_ppem_bits: u32,
219        amount_bits: u32,
220    },
221}
222
223impl From<StemDarkening> for StemDarkeningCacheKey {
224    fn from(value: StemDarkening) -> Self {
225        match value.normalized() {
226            StemDarkening::None => Self::None,
227            StemDarkening::Enabled { max_ppem, amount } => Self::Enabled {
228                max_ppem_bits: max_ppem.to_bits(),
229                amount_bits: amount.to_bits(),
230            },
231        }
232    }
233}
234
235pub(crate) const GLYPH_SCALE_BUCKETS_PER_UNIT: f32 = 16_384.0;
236
237pub(crate) fn glyph_scale_bucket(scale: f32) -> u32 {
238    ((scale.max(f32::EPSILON) * GLYPH_SCALE_BUCKETS_PER_UNIT)
239        .round()
240        .max(1.0)) as u32
241}
242
243pub(crate) fn glyph_scale_from_bucket(bucket: u32) -> f32 {
244    (bucket.max(1) as f32) / GLYPH_SCALE_BUCKETS_PER_UNIT
245}
246
247#[derive(Debug, Clone, Copy)]
248pub(crate) struct CachedGlyphAtlas {
249    pub(crate) scale: f32,
250    pub(crate) offset: Vector,
251    pub(crate) size: Size,
252    pub(crate) uv_min: [f32; 2],
253    pub(crate) uv_max: [f32; 2],
254    pub(crate) color_mode: TextAtlasColorMode,
255    pub(crate) is_color: bool,
256    /// Which atlas page (texture-array layer) this glyph was rasterized into.
257    pub(crate) page_index: usize,
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub(crate) struct AtlasRectU {
262    pub(crate) min_x: usize,
263    pub(crate) min_y: usize,
264    pub(crate) max_x: usize,
265    pub(crate) max_y: usize,
266}
267
268impl AtlasRectU {
269    const NOTHING: Self = Self {
270        min_x: usize::MAX,
271        min_y: usize::MAX,
272        max_x: 0,
273        max_y: 0,
274    };
275
276    pub(crate) fn include_rect(&mut self, x: usize, y: usize, width: usize, height: usize) {
277        self.min_x = self.min_x.min(x);
278        self.min_y = self.min_y.min(y);
279        self.max_x = self.max_x.max(x + width);
280        self.max_y = self.max_y.max(y + height);
281    }
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub(crate) struct TextAtlasPlacement {
286    pub(crate) x: usize,
287    pub(crate) y: usize,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub(crate) enum TextAtlasInsertError {
292    Full,
293    TooLarge,
294}
295
296/// A pending CPU->GPU copy for one atlas page: the dirty rectangle (`offset`/`extent`) and its
297/// pixels. The destination page (texture-array layer) is supplied alongside by `take_uploads`.
298#[derive(Debug, Clone)]
299pub(crate) struct TextAtlasUpload {
300    pub(crate) offset: (u32, u32),
301    pub(crate) extent: (u32, u32),
302    pub(crate) pixels: Vec<u8>,
303    pub(crate) clear_texture: bool,
304}
305
306/// A single atlas page: a CPU-side pixel buffer with a shelf-packing cursor and a dirty
307/// rectangle for incremental GPU uploads. The multi-page atlas ([`TextAtlasPages`]) holds a
308/// collection of these.
309#[derive(Debug, Clone)]
310pub(crate) struct TextAtlas {
311    pub(crate) width: usize,
312    pub(crate) height: usize,
313    pub(crate) pixels: Vec<u8>,
314    pub(crate) dirty: AtlasRectU,
315    pub(crate) clear_texture: bool,
316    pub(crate) generation: u64,
317    pub(crate) cursor: (usize, usize),
318    pub(crate) row_height: usize,
319    /// Frame index of the most recent insert/touch, used for whole-page LRU eviction.
320    pub(crate) last_used_frame: u64,
321}
322
323impl Default for TextAtlas {
324    fn default() -> Self {
325        Self::new(TEXT_ATLAS_WIDTH, TEXT_ATLAS_HEIGHT)
326    }
327}
328
329impl TextAtlas {
330    pub(crate) fn new(width: usize, height: usize) -> Self {
331        Self {
332            width,
333            height,
334            pixels: vec![0; width * height * 4],
335            dirty: AtlasRectU::NOTHING,
336            clear_texture: false,
337            generation: 1,
338            cursor: (TEXT_ATLAS_PADDING, TEXT_ATLAS_PADDING),
339            row_height: 0,
340            last_used_frame: 0,
341        }
342    }
343
344    /// Reset this page so its space can be recycled (used when a page is evicted). Zeroes the
345    /// CPU pixels and GPU page are cleared separately; only new glyphs need uploading.
346    pub(crate) fn clear_for_reuse(&mut self) {
347        self.pixels.iter_mut().for_each(|byte| *byte = 0);
348        self.cursor = (TEXT_ATLAS_PADDING, TEXT_ATLAS_PADDING);
349        self.row_height = 0;
350        self.dirty = AtlasRectU::NOTHING;
351        self.clear_texture = true;
352        self.generation = self.generation.wrapping_add(1);
353        self.last_used_frame = 0;
354    }
355
356    pub(crate) fn allocate(
357        &mut self,
358        width: usize,
359        height: usize,
360    ) -> std::result::Result<TextAtlasPlacement, TextAtlasInsertError> {
361        if width == 0 || height == 0 || width > self.width || height > self.height {
362            return Err(TextAtlasInsertError::TooLarge);
363        }
364
365        if self.cursor.0 + width + TEXT_ATLAS_PADDING > self.width {
366            self.cursor.0 = TEXT_ATLAS_PADDING;
367            self.cursor.1 += self.row_height + TEXT_ATLAS_PADDING;
368            self.row_height = 0;
369        }
370
371        if self.cursor.1 + height + TEXT_ATLAS_PADDING > self.height {
372            return Err(TextAtlasInsertError::Full);
373        }
374
375        let placement = TextAtlasPlacement {
376            x: self.cursor.0,
377            y: self.cursor.1,
378        };
379        self.cursor.0 += width + TEXT_ATLAS_PADDING;
380        self.row_height = self.row_height.max(height);
381        Ok(placement)
382    }
383
384    pub(crate) fn write_rgba(
385        &mut self,
386        placement: TextAtlasPlacement,
387        width: usize,
388        height: usize,
389        pixels: &[u8],
390    ) {
391        for row in 0..height {
392            let src_start = row * width * 4;
393            let src_end = src_start + (width * 4);
394            let dst_start = ((placement.y + row) * self.width + placement.x) * 4;
395            let dst_end = dst_start + (width * 4);
396            self.pixels[dst_start..dst_end].copy_from_slice(&pixels[src_start..src_end]);
397        }
398        self.dirty
399            .include_rect(placement.x, placement.y, width, height);
400    }
401
402    pub(crate) fn insert_rgba(
403        &mut self,
404        width: usize,
405        height: usize,
406        pixels: &[u8],
407    ) -> std::result::Result<TextAtlasPlacement, TextAtlasInsertError> {
408        let placement = self.allocate(width, height)?;
409        self.write_rgba(placement, width, height, pixels);
410        Ok(placement)
411    }
412
413    pub(crate) fn take_upload(&mut self) -> Option<TextAtlasUpload> {
414        let dirty = std::mem::replace(&mut self.dirty, AtlasRectU::NOTHING);
415        let clear_texture = std::mem::take(&mut self.clear_texture);
416        if dirty == AtlasRectU::NOTHING {
417            return clear_texture.then(|| TextAtlasUpload {
418                offset: (0, 0),
419                extent: (0, 0),
420                pixels: Vec::new(),
421                clear_texture,
422            });
423        }
424
425        let width = dirty.max_x - dirty.min_x;
426        let height = dirty.max_y - dirty.min_y;
427        let mut pixels = vec![0; width * height * 4];
428        for row in 0..height {
429            let src_start = ((dirty.min_y + row) * self.width + dirty.min_x) * 4;
430            let src_end = src_start + (width * 4);
431            let dst_start = row * width * 4;
432            let dst_end = dst_start + (width * 4);
433            pixels[dst_start..dst_end].copy_from_slice(&self.pixels[src_start..src_end]);
434        }
435
436        Some(TextAtlasUpload {
437            offset: (dirty.min_x as u32, dirty.min_y as u32),
438            extent: (width as u32, height as u32),
439            pixels,
440            clear_texture,
441        })
442    }
443}
444
445/// Result of inserting a glyph into the multi-page atlas: where it landed, plus the page that was
446/// cleared to make room (if any) so the caller can drop the glyph-cache entries that pointed into
447/// the now-recycled page.
448#[derive(Debug, Clone, Copy, PartialEq, Eq)]
449pub(crate) struct TextAtlasInsertion {
450    pub(crate) page_index: usize,
451    pub(crate) placement: TextAtlasPlacement,
452    pub(crate) evicted_page: Option<usize>,
453}
454
455impl TextAtlasInsertion {
456    pub(crate) fn placed(page_index: usize, placement: TextAtlasPlacement) -> Self {
457        Self {
458            page_index,
459            placement,
460            evicted_page: None,
461        }
462    }
463
464    pub(crate) fn evicted(page_index: usize, placement: TextAtlasPlacement) -> Self {
465        Self {
466            page_index,
467            placement,
468            evicted_page: Some(page_index),
469        }
470    }
471}
472
473/// A multi-page glyph atlas: a collection of uniformly sized [`TextAtlas`] pages that grows on
474/// demand up to `max_pages`, then recycles the least-recently-used page. Each page maps to one
475/// layer of the GPU texture array.
476#[derive(Debug, Clone)]
477pub(crate) struct TextAtlasPages {
478    pub(crate) pages: Vec<TextAtlas>,
479    pub(crate) page_width: usize,
480    pub(crate) page_height: usize,
481    pub(crate) max_pages: usize,
482}
483
484impl TextAtlasPages {
485    pub(crate) fn new(page_width: usize, page_height: usize, max_pages: usize) -> Self {
486        Self {
487            pages: vec![TextAtlas::new(page_width, page_height)],
488            page_width,
489            page_height,
490            max_pages: max_pages.max(1),
491        }
492    }
493
494    /// Number of allocated atlas pages (drives how many texture-array layers are allocated).
495    pub(crate) fn page_count(&self) -> usize {
496        self.pages.len()
497    }
498
499    /// Uniform dimensions of every page, in pixels.
500    pub(crate) fn page_size(&self) -> (u32, u32) {
501        (self.page_width as u32, self.page_height as u32)
502    }
503
504    /// Mark a page as used in `frame` so LRU eviction won't reclaim it prematurely. Called on a
505    /// glyph-cache hit (the insert path stamps the page itself).
506    pub(crate) fn touch_page(&mut self, index: usize, frame: u64) {
507        if let Some(page) = self.pages.get_mut(index) {
508            page.last_used_frame = frame;
509        }
510    }
511
512    /// Insert a rasterized glyph, returning the page it landed on plus its placement within that
513    /// page. Tries existing pages in order, then grows a new page if under budget. At budget this
514    /// returns `Full` for now; whole-page LRU eviction is added in a later phase. `frame` stamps
515    /// the chosen page for that future eviction policy.
516    pub(crate) fn insert_rgba(
517        &mut self,
518        width: usize,
519        height: usize,
520        pixels: &[u8],
521        frame: u64,
522    ) -> std::result::Result<TextAtlasInsertion, TextAtlasInsertError> {
523        // A glyph larger than a page can never fit on any page.
524        if width == 0 || height == 0 || width > self.page_width || height > self.page_height {
525            return Err(TextAtlasInsertError::TooLarge);
526        }
527
528        for index in 0..self.pages.len() {
529            match self.pages[index].insert_rgba(width, height, pixels) {
530                Ok(placement) => {
531                    self.pages[index].last_used_frame = frame;
532                    return Ok(TextAtlasInsertion::placed(index, placement));
533                }
534                Err(TextAtlasInsertError::TooLarge) => return Err(TextAtlasInsertError::TooLarge),
535                Err(TextAtlasInsertError::Full) => {}
536            }
537        }
538
539        if self.pages.len() < self.max_pages {
540            let mut page = TextAtlas::new(self.page_width, self.page_height);
541            let placement = page.insert_rgba(width, height, pixels)?;
542            page.last_used_frame = frame;
543            let index = self.pages.len();
544            self.pages.push(page);
545            return Ok(TextAtlasInsertion::placed(index, placement));
546        }
547
548        // At the page budget: evict the least-recently-used page that was NOT touched this frame.
549        // Pages used earlier this frame are off-limits -- glyphs already emitted this frame point
550        // into them, so clearing one would make those draws sample garbage. This guard is the
551        // load-bearing invariant of the eviction scheme.
552        let evict_index = self
553            .pages
554            .iter()
555            .enumerate()
556            .filter(|(_, page)| page.last_used_frame != frame)
557            .min_by_key(|(_, page)| page.last_used_frame)
558            .map(|(index, _)| index);
559        let Some(evict_index) = evict_index else {
560            // Every page is hot this frame; signal Full so the caller drops this glyph for now.
561            return Err(TextAtlasInsertError::Full);
562        };
563
564        self.pages[evict_index].clear_for_reuse();
565        let placement = self.pages[evict_index].insert_rgba(width, height, pixels)?;
566        self.pages[evict_index].last_used_frame = frame;
567        Ok(TextAtlasInsertion::evicted(evict_index, placement))
568    }
569
570    /// Drain the pending dirty-rect upload from each page that has one, tagged with its page index
571    /// (the destination texture-array layer).
572    pub(crate) fn take_uploads(&mut self) -> Vec<(usize, TextAtlasUpload)> {
573        let mut uploads = Vec::new();
574        for (index, page) in self.pages.iter_mut().enumerate() {
575            if let Some(upload) = page.take_upload() {
576                uploads.push((index, upload));
577            }
578        }
579        uploads
580    }
581}
582
583#[cfg(test)]
584pub(crate) mod page_tests {
585    use super::*;
586
587    #[test]
588    fn optimization_regression_fresh_atlas_uploads_only_populated_pixels() {
589        let mut atlas = TextAtlas::new(2048, 2048);
590        atlas.insert_rgba(12, 18, &vec![255; 12 * 18 * 4]).unwrap();
591        let upload = atlas.take_upload().unwrap();
592        assert!(
593            upload.pixels.len() < 4096,
594            "a tiny glyph uploaded a whole page"
595        );
596        assert!(atlas.take_upload().is_none());
597    }
598
599    #[test]
600    fn recycled_page_upload_clears_old_glyphs_without_copying_a_full_page() {
601        let mut atlas = TextAtlas::new(64, 64);
602        atlas.insert_rgba(60, 60, &vec![255; 60 * 60 * 4]).unwrap();
603        atlas.take_upload().unwrap();
604        let generation = atlas.generation;
605        atlas.clear_for_reuse();
606        atlas.insert_rgba(4, 4, &[255; 4 * 4 * 4]).unwrap();
607        let upload = atlas.take_upload().unwrap();
608        assert!(upload.clear_texture);
609        assert_ne!(atlas.generation, generation);
610        assert_eq!(upload.pixels.len(), 4 * 4 * 4);
611        assert_eq!(atlas.pixels[(32 * 64 + 32) * 4], 0);
612        atlas.clear_for_reuse();
613        let clear_only = atlas.take_upload().unwrap();
614        assert!(clear_only.clear_texture);
615        assert!(clear_only.pixels.is_empty());
616        assert!(atlas.take_upload().is_none());
617    }
618
619    fn opaque(width: usize, height: usize) -> Vec<u8> {
620        vec![255u8; width * height * 4]
621    }
622
623    #[test]
624    fn overflow_allocates_second_page() {
625        let mut pages = TextAtlasPages::new(64, 64, 2);
626        let glyph = opaque(60, 60);
627
628        // First 60x60 fits on page 0; a second can't share the 64-tall page, so it grows.
629        assert_eq!(pages.insert_rgba(60, 60, &glyph, 1).unwrap().page_index, 0);
630        assert_eq!(pages.insert_rgba(60, 60, &glyph, 1).unwrap().page_index, 1);
631        assert_eq!(pages.page_count(), 2);
632
633        // Both pages are full, we are at the 2-page budget, and every page was touched this same
634        // frame -> nothing is eligible for eviction -> Full.
635        assert_eq!(
636            pages.insert_rgba(60, 60, &glyph, 1),
637            Err(TextAtlasInsertError::Full)
638        );
639    }
640
641    #[test]
642    fn eviction_reuses_lru_page() {
643        let mut pages = TextAtlasPages::new(64, 64, 2);
644        let glyph = opaque(60, 60);
645
646        // Page 0 last used at frame 1, page 1 at frame 2.
647        assert_eq!(pages.insert_rgba(60, 60, &glyph, 1).unwrap().page_index, 0);
648        assert_eq!(pages.insert_rgba(60, 60, &glyph, 2).unwrap().page_index, 1);
649
650        // At budget; inserting at frame 3 evicts the LRU page (page 0) and reuses it.
651        let insertion = pages.insert_rgba(60, 60, &glyph, 3).unwrap();
652        assert_eq!(insertion.page_index, 0);
653        assert_eq!(insertion.evicted_page, Some(0));
654        assert_eq!(pages.page_count(), 2);
655    }
656
657    #[test]
658    fn current_frame_page_not_evicted() {
659        let mut pages = TextAtlasPages::new(64, 64, 2);
660        let glyph = opaque(60, 60);
661
662        // Both pages are used in frame 5.
663        pages.insert_rgba(60, 60, &glyph, 5).unwrap();
664        pages.insert_rgba(60, 60, &glyph, 5).unwrap();
665
666        // A third glyph in frame 5 must NOT evict a page referenced earlier this frame.
667        assert_eq!(
668            pages.insert_rgba(60, 60, &glyph, 5),
669            Err(TextAtlasInsertError::Full)
670        );
671    }
672
673    #[test]
674    fn too_large_glyph_is_rejected() {
675        let mut pages = TextAtlasPages::new(64, 64, 4);
676        assert_eq!(
677            pages.insert_rgba(70, 70, &opaque(70, 70), 1),
678            Err(TextAtlasInsertError::TooLarge)
679        );
680        assert_eq!(pages.page_count(), 1);
681    }
682
683    #[test]
684    fn take_uploads_returns_per_page() {
685        let mut pages = TextAtlasPages::new(64, 64, 2);
686        let glyph = opaque(60, 60);
687        pages.insert_rgba(60, 60, &glyph, 1).unwrap();
688        pages.insert_rgba(60, 60, &glyph, 1).unwrap();
689
690        let uploads = pages.take_uploads();
691        let indices: Vec<usize> = uploads.iter().map(|(index, _)| *index).collect();
692        assert_eq!(uploads.len(), 2);
693        assert!(indices.contains(&0) && indices.contains(&1));
694
695        // Dirty state is consumed: a second drain yields nothing.
696        assert!(pages.take_uploads().is_empty());
697    }
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
701pub(crate) enum PathCacheKind {
702    Fill,
703    Stroke {
704        line_width_bits: u32,
705        cap: sui_scene::StrokeCap,
706        join: sui_scene::StrokeJoin,
707    },
708}
709
710#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
711pub(crate) struct PathCacheKey {
712    pub(crate) signature: u64,
713    pub(crate) kind: PathCacheKind,
714    pub(crate) feather_width_bits: u32,
715}
716
717#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
718pub(crate) struct AnalyticPathCacheKey {
719    pub(crate) signature: u64,
720    pub(crate) kind: PathCacheKind,
721    pub(crate) feather_width_bits: u32,
722}
723
724impl AnalyticPathCacheKey {
725    pub(crate) fn fill(path: &ScenePath, transform: Transform, feather_width: f32) -> Self {
726        Self {
727            signature: hash_normalized_analytic_path(path, transform),
728            kind: PathCacheKind::Fill,
729            feather_width_bits: feather_width.to_bits(),
730        }
731    }
732
733    pub(crate) fn stroke(
734        path: &ScenePath,
735        transform: Transform,
736        stroke: StrokeStyle,
737        feather_width: f32,
738    ) -> Self {
739        Self {
740            signature: hash_normalized_analytic_path(path, transform),
741            kind: PathCacheKind::Stroke {
742                line_width_bits: stroke.width.to_bits(),
743                cap: stroke.cap,
744                join: stroke.join,
745            },
746            feather_width_bits: feather_width.to_bits(),
747        }
748    }
749}
750
751impl PathCacheKey {
752    pub(crate) fn fill(path: &ScenePath, transform: Transform, feather_width: f32) -> Self {
753        Self {
754            signature: hash_path(path, transform),
755            kind: PathCacheKind::Fill,
756            feather_width_bits: feather_width.to_bits(),
757        }
758    }
759
760    pub(crate) fn stroke(
761        path: &ScenePath,
762        transform: Transform,
763        stroke: StrokeStyle,
764        feather_width: f32,
765    ) -> Self {
766        Self {
767            signature: hash_path(path, transform),
768            kind: PathCacheKind::Stroke {
769                line_width_bits: stroke.width.to_bits(),
770                cap: stroke.cap,
771                join: stroke.join,
772            },
773            feather_width_bits: feather_width.to_bits(),
774        }
775    }
776}