text_typeset/atlas/cache.rs
1use std::collections::HashMap;
2
3use etagere::AllocId;
4
5use crate::types::FontFaceId;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
8#[non_exhaustive]
9pub struct GlyphCacheKey {
10 pub font_face_id: FontFaceId,
11 pub glyph_id: u16,
12 pub size_bits: u32,
13 /// Font weight (variation axis) so that e.g. Inter Regular and Inter
14 /// Bold produce separate cache entries even though they share the
15 /// same `font_face_id` and `glyph_id` in a variable font.
16 pub weight: u32,
17 /// Whether the bitmap was rasterized with hinting. Rasters produced
18 /// under a raster scale (zoomed content) are unhinted, and the same
19 /// *physical* size can be reached both ways — 7px at raster_scale 2
20 /// and 14px at raster_scale 1 share `size_bits` but must not share
21 /// a bitmap.
22 pub hinted: bool,
23 /// Whether the text asks for italic: an upright face is rasterized
24 /// slanted for it (see `crate::font::synthesis`), and the slanted bitmap
25 /// must not stand in for the upright one.
26 pub italic: bool,
27 /// Which of the [`SUBPIXEL_BINS`](crate::atlas::rasterizer::SUBPIXEL_BINS)
28 /// horizontal offsets the bitmap was rasterized at: the glyph's pen
29 /// position fell that many quarters of a pixel past a pixel edge (see
30 /// [`split_subpixel_x`](crate::atlas::rasterizer::split_subpixel_x)).
31 /// `0` for a glyph drawn at a whole pixel, which is every glyph of a
32 /// scaled (unhinted) raster.
33 pub subpixel_x: u8,
34}
35
36impl GlyphCacheKey {
37 pub fn new(font_face_id: FontFaceId, glyph_id: u16, size_px: f32) -> Self {
38 Self {
39 font_face_id,
40 glyph_id,
41 size_bits: size_px.to_bits(),
42 weight: 400,
43 hinted: true,
44 italic: false,
45 subpixel_x: 0,
46 }
47 }
48
49 pub fn with_weight(
50 font_face_id: FontFaceId,
51 glyph_id: u16,
52 size_px: f32,
53 weight: u32,
54 hinted: bool,
55 ) -> Self {
56 Self {
57 font_face_id,
58 glyph_id,
59 size_bits: size_px.to_bits(),
60 weight,
61 hinted,
62 italic: false,
63 subpixel_x: 0,
64 }
65 }
66
67 /// [`with_weight`](Self::with_weight) for text that asks for italic when
68 /// `italic`.
69 pub fn with_style(
70 font_face_id: FontFaceId,
71 glyph_id: u16,
72 size_px: f32,
73 weight: u32,
74 hinted: bool,
75 italic: bool,
76 ) -> Self {
77 Self {
78 italic,
79 ..Self::with_weight(font_face_id, glyph_id, size_px, weight, hinted)
80 }
81 }
82
83 /// This key for the bitmap rasterized `bin` quarters of a pixel to the
84 /// right (see [`split_subpixel_x`](crate::atlas::rasterizer::split_subpixel_x)).
85 pub fn at_subpixel_x(self, bin: u8) -> Self {
86 Self {
87 subpixel_x: bin,
88 ..self
89 }
90 }
91}
92
93pub struct CachedGlyph {
94 pub alloc_id: AllocId,
95 pub atlas_x: u32,
96 pub atlas_y: u32,
97 pub width: u32,
98 pub height: u32,
99 pub placement_left: i32,
100 pub placement_top: i32,
101 pub is_color: bool,
102 /// Frame generation when this glyph was last used.
103 pub last_used: u64,
104}
105
106/// A glyph removed by [`GlyphCache::evict_unused`]: the allocator id to
107/// deallocate plus the atlas rectangle the glyph occupied. Consumers that
108/// retain glyph quads across frames (paint caches) key their invalidation
109/// off the eviction; the rect lets debug builds poison-fill freed pixels
110/// so stale-UV sampling is visually unmistakable.
111#[derive(Clone, Copy, Debug)]
112#[non_exhaustive]
113pub struct EvictedGlyph {
114 pub alloc_id: AllocId,
115 pub atlas_x: u32,
116 pub atlas_y: u32,
117 pub width: u32,
118 pub height: u32,
119}
120
121/// Glyph cache with LRU eviction.
122///
123/// Tracks a frame generation counter. Each `get` marks the glyph as used
124/// in the current generation. `evict_unused` removes glyphs not used
125/// for `max_idle_frames` generations and deallocates their atlas space.
126pub struct GlyphCache {
127 pub(crate) entries: HashMap<GlyphCacheKey, CachedGlyph>,
128 generation: u64,
129 last_eviction_generation: u64,
130}
131
132/// Number of frames a glyph can go unused before being evicted.
133const MAX_IDLE_FRAMES: u64 = 120; // ~2 seconds at 60fps
134
135impl Default for GlyphCache {
136 fn default() -> Self {
137 Self::new()
138 }
139}
140
141impl GlyphCache {
142 pub fn new() -> Self {
143 Self {
144 entries: HashMap::new(),
145 generation: 0,
146 last_eviction_generation: 0,
147 }
148 }
149
150 /// Advance the frame generation counter. Call once per render frame.
151 pub fn advance_generation(&mut self) {
152 self.generation += 1;
153 }
154
155 pub fn generation(&self) -> u64 {
156 self.generation
157 }
158
159 /// Look up a cached glyph, marking it as used in the current generation.
160 pub fn get(&mut self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
161 if let Some(entry) = self.entries.get_mut(key) {
162 entry.last_used = self.generation;
163 Some(entry)
164 } else {
165 None
166 }
167 }
168
169 /// Look up without marking as used (for read-only queries).
170 pub fn peek(&self, key: &GlyphCacheKey) -> Option<&CachedGlyph> {
171 self.entries.get(key)
172 }
173
174 pub fn insert(&mut self, key: GlyphCacheKey, mut glyph: CachedGlyph) {
175 glyph.last_used = self.generation;
176 self.entries.insert(key, glyph);
177 }
178
179 /// Evict glyphs unused for MAX_IDLE_FRAMES generations.
180 /// Returns the evicted entries — each carries the `AllocId` to
181 /// deallocate from the atlas plus the atlas rectangle it occupied
182 /// (the bucketed allocator cannot resolve a rectangle from an
183 /// `AllocId` after the fact, so the rect is captured here, before
184 /// the entry is dropped; debug builds use it to poison-fill the
185 /// freed pixels).
186 /// Only runs the actual eviction scan every 60 calls (~1 second at 60fps)
187 /// to avoid iterating the entire cache on every render.
188 pub fn evict_unused(&mut self) -> Vec<EvictedGlyph> {
189 // Only scan every 60 generations (~1 second at 60fps)
190 if self.generation - self.last_eviction_generation < 60 {
191 return Vec::new();
192 }
193 self.last_eviction_generation = self.generation;
194
195 let threshold = self.generation.saturating_sub(MAX_IDLE_FRAMES);
196 let mut evicted = Vec::new();
197
198 self.entries.retain(|_key, glyph| {
199 if glyph.last_used < threshold {
200 evicted.push(EvictedGlyph {
201 alloc_id: glyph.alloc_id,
202 atlas_x: glyph.atlas_x,
203 atlas_y: glyph.atlas_y,
204 width: glyph.width,
205 height: glyph.height,
206 });
207 false
208 } else {
209 true
210 }
211 });
212
213 evicted
214 }
215
216 /// Emergency eviction when the atlas is full: drop every glyph not
217 /// used in the *current* generation, regardless of the idle window.
218 ///
219 /// Unlike [`evict_unused`](Self::evict_unused) this runs
220 /// unconditionally (no every-60-generations gate) — it is only
221 /// called when an allocation has already failed at the atlas size
222 /// cap, where the alternative is silently dropping the new glyph.
223 /// Glyphs touched this generation are still referenced by quads in
224 /// the frame being built and must survive.
225 pub fn evict_for_pressure(&mut self) -> Vec<EvictedGlyph> {
226 let current = self.generation;
227 let mut evicted = Vec::new();
228
229 self.entries.retain(|_key, glyph| {
230 if glyph.last_used < current {
231 evicted.push(EvictedGlyph {
232 alloc_id: glyph.alloc_id,
233 atlas_x: glyph.atlas_x,
234 atlas_y: glyph.atlas_y,
235 width: glyph.width,
236 height: glyph.height,
237 });
238 false
239 } else {
240 true
241 }
242 });
243
244 evicted
245 }
246
247 pub fn len(&self) -> usize {
248 self.entries.len()
249 }
250
251 pub fn is_empty(&self) -> bool {
252 self.entries.is_empty()
253 }
254
255 /// Mark multiple glyphs as used in the current generation without
256 /// returning their data. Used by callers that cache glyph output
257 /// externally (e.g. per-widget paint caches) and need to keep the
258 /// glyphs alive in the atlas even though they don't re-measure them
259 /// every frame.
260 pub fn touch(&mut self, keys: &[GlyphCacheKey]) {
261 let current = self.generation;
262 for key in keys {
263 if let Some(entry) = self.entries.get_mut(key) {
264 entry.last_used = current;
265 }
266 }
267 }
268}