Skip to main content

euv_core/font/atlas/
impl.rs

1use super::*;
2
3/// Caching lookup, bounded LRU eviction, and telemetry operations for `GlyphAtlas`.
4impl GlyphAtlas {
5    /// Losslessly packs all fields of `GlyphKey` into the low 40 bits of a `u64`.
6    ///
7    /// # Arguments
8    ///
9    /// - `GlyphKey` - Quantized glyph lookup key.
10    ///
11    /// # Returns
12    ///
13    /// - `u64` - Bijective 40-bit key representation (`0..2^40`).
14    #[inline(always)]
15    #[must_use]
16    pub(crate) fn pack_glyph_key(key: GlyphKey) -> u64 {
17        key.pack_u64()
18    }
19
20    /// Computes a fast single-multiply avalanche hash for a packed 40-bit `GlyphKey`.
21    ///
22    /// # Arguments
23    ///
24    /// - `u64` - Lossless 40-bit packed glyph key.
25    ///
26    /// # Returns
27    ///
28    /// - `usize` - Mixed hash value suitable for power-of-two bitmasking.
29    #[inline(always)]
30    #[must_use]
31    fn hash_packed_key(packed: u64) -> usize {
32        let mixed: u64 = packed.wrapping_mul(GLYPH_INDEX_HASH_MULT);
33        (mixed ^ (mixed >> 32)) as usize
34    }
35
36    /// Estimates the resident memory footprint in bytes of one rasterized glyph entry.
37    ///
38    /// # Arguments
39    ///
40    /// - `&RasterizedGlyph` - Cached coverage bitmap entry.
41    ///
42    /// # Returns
43    ///
44    /// - `usize` - Tracked byte size including coverage bytes and metadata overhead.
45    #[inline(always)]
46    #[must_use]
47    fn entry_bytes(glyph: &RasterizedGlyph) -> usize {
48        glyph
49            .get_coverage()
50            .len()
51            .saturating_add(GLYPH_ENTRY_OVERHEAD_BYTES)
52    }
53
54    /// Resolves the active resident memory budget in bytes (`GLYPH_ATLAS_DEFAULT_BUDGET_BYTES` when unset).
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Glyph atlas reference.
59    ///
60    /// # Returns
61    ///
62    /// - `usize` - Effective byte budget threshold.
63    #[inline(always)]
64    #[must_use]
65    pub fn effective_budget_bytes(&self) -> usize {
66        let raw: usize = self.get_budget_bytes();
67        if raw == 0 {
68            GLYPH_ATLAS_DEFAULT_BUDGET_BYTES
69        } else {
70            raw
71        }
72    }
73
74    /// Configures a bounded resident memory budget in bytes and immediately evicts cold glyphs if currently over budget.
75    ///
76    /// # Arguments
77    ///
78    /// - `&Self` - Mutable glyph atlas reference.
79    /// - `usize` - Maximum resident byte budget (clamped to `>= 1024`).
80    pub fn set_memory_budget(&mut self, max_bytes: usize) {
81        let clamped: usize = max_bytes.max(GLYPH_ATLAS_MIN_BUDGET_BYTES);
82        self.set_budget_bytes(clamped);
83        self.evict_if_over_budget();
84    }
85
86    /// Returns the cumulative cache hit ratio in `[0.0, 1.0]` (`1.0` before any lookup).
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Glyph atlas reference.
91    ///
92    /// # Returns
93    ///
94    /// - `f32` - Cache hit rate fraction.
95    #[must_use]
96    pub fn hit_rate(&self) -> f32 {
97        let hits: u64 = self.get_cache_hits();
98        let total: u64 = hits.saturating_add(self.get_cache_misses());
99        if total == 0 {
100            1.0
101        } else {
102            (hits as f32) / (total as f32)
103        }
104    }
105
106    /// Evicts least-recently-used glyphs when `resident_bytes` exceeds the active budget and slots are unpinned.
107    ///
108    /// # Arguments
109    ///
110    /// - `&Self` - Mutable glyph atlas reference.
111    pub fn evict_if_over_budget(&mut self) {
112        let budget: usize = self.effective_budget_bytes();
113        let Self {
114            resident_bytes,
115            slots_pinned,
116            entries,
117            ..
118        } = self;
119        if *slots_pinned || *resident_bytes <= budget || entries.len() <= 1 {
120            return;
121        }
122        let target: usize = (budget.saturating_mul(3) / 4).max(GLYPH_ENTRY_OVERHEAD_BYTES);
123        self.evict_lru_to_target(target);
124    }
125
126    /// Tags subsequent glyph accesses and insertions with GPU submission `fence_id` for fence-deferred reclamation.
127    ///
128    /// # Arguments
129    ///
130    /// - `&Self` - Mutable glyph atlas reference.
131    /// - `u64` - Active frame GPU fence identifier.
132    pub fn begin_frame_fence(&mut self, fence_id: u64) {
133        let Self {
134            active_fence_id, ..
135        } = self;
136        *active_fence_id = (*active_fence_id).max(fence_id);
137    }
138
139    /// Marks GPU submission `fence_id` complete and reclaims all evicted glyph allocations whose fence completed.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Mutable glyph atlas reference.
144    /// - `u64` - Completed monotonic GPU fence identifier.
145    ///
146    /// # Returns
147    ///
148    /// - `usize` - Number of deferred glyph allocations reclaimed.
149    pub fn complete_fence(&mut self, fence_id: u64) -> usize {
150        let Self {
151            completed_fence_id,
152            pending_reclaim,
153            pending_reclaim_bytes,
154            reclaimed_entries,
155            ..
156        } = self;
157        if fence_id > *completed_fence_id {
158            *completed_fence_id = fence_id;
159        }
160        let completed: u64 = *completed_fence_id;
161        let before: usize = pending_reclaim.len();
162        let mut released_bytes: usize = 0;
163        pending_reclaim.retain(|&(retire_fence, bytes): &(u64, usize)| {
164            if retire_fence <= completed {
165                released_bytes = released_bytes.saturating_add(bytes);
166                false
167            } else {
168                true
169            }
170        });
171        let reclaimed: usize = before.saturating_sub(pending_reclaim.len());
172        *pending_reclaim_bytes = pending_reclaim_bytes.saturating_sub(released_bytes);
173        *reclaimed_entries = reclaimed_entries.saturating_add(reclaimed as u64);
174        reclaimed
175    }
176
177    /// Invalidates bitmap atlas entries independently of text shaping whenever DPI scale, AA mode, or font chain changes.
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Mutable glyph atlas reference.
182    /// - `f32` - Active display scale factor.
183    /// - `AntialiasingMode` - Active anti-aliasing policy.
184    /// - `u64` - Active font fallback chain revision.
185    ///
186    /// # Returns
187    ///
188    /// - `bool` - `true` when atlas bitmaps were invalidated and queued for fence-deferred release.
189    pub fn invalidate_for_render_params(
190        &mut self,
191        dpi_scale: f32,
192        aa: AntialiasingMode,
193        font_chain_revision: u64,
194    ) -> bool {
195        let next_dpi_bits: u32 = dpi_scale.max(0.5).to_bits();
196        let Self {
197            active_dpi_scale_bits,
198            active_aa_mode,
199            font_chain_revision: cur_font_rev,
200            ..
201        } = self;
202        if *active_dpi_scale_bits == 0 {
203            *active_dpi_scale_bits = next_dpi_bits;
204            *active_aa_mode = aa;
205            *cur_font_rev = font_chain_revision;
206            return false;
207        }
208        let unchanged: bool = *active_dpi_scale_bits == next_dpi_bits
209            && *active_aa_mode == aa
210            && *cur_font_rev == font_chain_revision;
211        if unchanged {
212            return false;
213        }
214        *active_dpi_scale_bits = next_dpi_bits;
215        *active_aa_mode = aa;
216        *cur_font_rev = font_chain_revision;
217        self.clear_with_fence_deferral();
218        true
219    }
220
221    /// Clears all resident bitmap entries, moving in-flight GPU-referenced entries to `pending_reclaim`.
222    ///
223    /// # Arguments
224    ///
225    /// - `&Self` - Mutable glyph atlas reference.
226    fn clear_with_fence_deferral(&mut self) {
227        let Self {
228            glyph_index,
229            entries,
230            entry_last_used,
231            entry_fence_ids,
232            ascii_tables,
233            last_ascii_style_sig,
234            last_ascii_table_idx,
235            revision,
236            resident_bytes,
237            completed_fence_id,
238            pending_reclaim,
239            pending_reclaim_bytes,
240            reclaimed_entries,
241            ..
242        } = self;
243        let completed: u64 = *completed_fence_id;
244        for (idx, (_, glyph)) in entries.iter().enumerate() {
245            let bytes: usize = Self::entry_bytes(glyph);
246            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
247            if fence > completed {
248                pending_reclaim.push((fence, bytes));
249                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
250            } else {
251                *reclaimed_entries = reclaimed_entries.saturating_add(1);
252            }
253        }
254        glyph_index.fill(GLYPH_INDEX_EMPTY);
255        entries.clear();
256        entry_last_used.clear();
257        entry_fence_ids.clear();
258        ascii_tables.clear();
259        *last_ascii_style_sig = 0;
260        *last_ascii_table_idx = 0;
261        *resident_bytes = 0;
262        *revision = revision.wrapping_add(1);
263    }
264
265    /// Compacts the glyph arena by evicting the coldest LRU entries until `resident_bytes <= target_bytes`, deferring reclamation of GPU in-flight bitmaps until fence completion.
266    ///
267    /// # Arguments
268    ///
269    /// - `&Self` - Mutable glyph atlas reference.
270    /// - `usize` - Target post-eviction resident byte ceiling.
271    fn evict_lru_to_target(&mut self, target_bytes: usize) {
272        let Self {
273            glyph_index,
274            entries,
275            entry_last_used,
276            entry_fence_ids,
277            ascii_tables,
278            revision,
279            resident_bytes,
280            evictions,
281            completed_fence_id,
282            pending_reclaim,
283            pending_reclaim_bytes,
284            reclaimed_entries,
285            ..
286        } = self;
287        let count: usize = entries.len();
288        if count == 0 || *resident_bytes <= target_bytes {
289            return;
290        }
291        let mut order: Vec<usize> = (0..count).collect();
292        order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
293        let mut keep: Vec<bool> = vec![true; count];
294        let mut remaining_bytes: usize = *resident_bytes;
295        let mut evicted_count: usize = 0;
296        let completed: u64 = *completed_fence_id;
297        for idx in order.into_iter() {
298            if remaining_bytes <= target_bytes {
299                break;
300            }
301            let bytes: usize = Self::entry_bytes(&entries[idx].1);
302            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
303            if fence > completed {
304                pending_reclaim.push((fence, bytes));
305                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
306            } else {
307                *reclaimed_entries = reclaimed_entries.saturating_add(1);
308            }
309            remaining_bytes = remaining_bytes.saturating_sub(bytes);
310            keep[idx] = false;
311            evicted_count += 1;
312        }
313        if evicted_count == 0 {
314            return;
315        }
316        let mut write_idx: usize = 0;
317        let mut next_resident: usize = 0;
318        for (read_idx, &kept) in keep.iter().enumerate() {
319            if kept {
320                if write_idx != read_idx {
321                    entries.swap(write_idx, read_idx);
322                    if read_idx < entry_last_used.len() && write_idx < entry_last_used.len() {
323                        entry_last_used.swap(write_idx, read_idx);
324                    }
325                    if read_idx < entry_fence_ids.len() && write_idx < entry_fence_ids.len() {
326                        entry_fence_ids.swap(write_idx, read_idx);
327                    }
328                }
329                next_resident =
330                    next_resident.saturating_add(Self::entry_bytes(&entries[write_idx].1));
331                write_idx += 1;
332            }
333        }
334        entries.truncate(write_idx);
335        entry_last_used.truncate(write_idx);
336        entry_fence_ids.truncate(write_idx);
337        *resident_bytes = next_resident;
338        *evictions = evictions.saturating_add(evicted_count as u64);
339        glyph_index.fill(GLYPH_INDEX_EMPTY);
340        for (slot_idx, (key, _)) in entries.iter().enumerate() {
341            let packed_key: u64 = Self::pack_glyph_key(*key);
342            Self::insert_index(glyph_index, slot_idx + 1, packed_key, slot_idx as u32);
343        }
344        for table in ascii_tables.iter_mut() {
345            table.slots.fill(u32::MAX);
346        }
347        *revision = revision.wrapping_add(1);
348    }
349
350    /// Probes the open-addressed `glyph_index` slice for `packed_key`.
351    ///
352    /// # Arguments
353    ///
354    /// - `&[u64]` - Power-of-two open-addressed index table.
355    /// - `u64` - Lossless 40-bit packed glyph key.
356    ///
357    /// # Returns
358    ///
359    /// - `Option<u32>` - Cached arena slot index when present.
360    #[inline(always)]
361    #[must_use]
362    fn lookup_index(glyph_index: &[u64], packed_key: u64) -> Option<u32> {
363        let cap: usize = glyph_index.len();
364        if cap == 0 {
365            return None;
366        }
367        let mask: usize = cap - 1;
368        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
369        loop {
370            let entry: u64 = glyph_index[idx];
371            if entry == GLYPH_INDEX_EMPTY {
372                return None;
373            }
374            if (entry & GLYPH_INDEX_KEY_MASK) == packed_key {
375                return Some((entry >> GLYPH_INDEX_SLOT_SHIFT) as u32);
376            }
377            idx = (idx + 1) & mask;
378        }
379    }
380
381    /// Inserts `(packed_key, slot)` into the open-addressed `glyph_index` table, doubling capacity at 75% load.
382    ///
383    /// # Arguments
384    ///
385    /// - `&mut Vec<u64>` - Open-addressed index table storage.
386    /// - `usize` - Current total entry count including the newly inserted glyph.
387    /// - `u64` - Lossless 40-bit packed glyph key.
388    /// - `u32` - Arena slot index into `entries`.
389    fn insert_index(glyph_index: &mut Vec<u64>, entry_count: usize, packed_key: u64, slot: u32) {
390        let cap: usize = glyph_index.len();
391        if cap == 0 {
392            glyph_index.resize(GLYPH_INDEX_INIT_CAP, GLYPH_INDEX_EMPTY);
393        } else if entry_count * 4 > cap * 3 {
394            let new_cap: usize = cap * 2;
395            let new_mask: usize = new_cap - 1;
396            let mut grown: Vec<u64> = vec![GLYPH_INDEX_EMPTY; new_cap];
397            for old_entry in glyph_index.iter().copied() {
398                if old_entry == GLYPH_INDEX_EMPTY {
399                    continue;
400                }
401                let old_key: u64 = old_entry & GLYPH_INDEX_KEY_MASK;
402                let mut idx: usize = Self::hash_packed_key(old_key) & new_mask;
403                while grown[idx] != GLYPH_INDEX_EMPTY {
404                    idx = (idx + 1) & new_mask;
405                }
406                grown[idx] = old_entry;
407            }
408            *glyph_index = grown;
409        }
410        let mask: usize = glyph_index.len() - 1;
411        let packed_entry: u64 = packed_key | ((slot as u64) << GLYPH_INDEX_SLOT_SHIFT);
412        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
413        loop {
414            let existing: u64 = glyph_index[idx];
415            if existing == GLYPH_INDEX_EMPTY || (existing & GLYPH_INDEX_KEY_MASK) == packed_key {
416                glyph_index[idx] = packed_entry;
417                return;
418            }
419            idx = (idx + 1) & mask;
420        }
421    }
422
423    /// Packs quantized glyph style attributes into a compact 32-bit signature for ASCII table matching.
424    ///
425    /// # Arguments
426    ///
427    /// - `u16` - Quantized physical font size in tenths of a pixel.
428    /// - `bool` - Bold flag.
429    /// - `bool` - Monospace family flag.
430    /// - `bool` - Italic flag.
431    ///
432    /// # Returns
433    ///
434    /// - `u32` - Packed style signature.
435    #[inline(always)]
436    #[must_use]
437    pub(crate) fn pack_style_sig(
438        size_tenths: u16,
439        bold: bool,
440        monospace: bool,
441        italic: bool,
442    ) -> u32 {
443        (size_tenths as u32)
444            | (u32::from(bold) << 16)
445            | (u32::from(monospace) << 17)
446            | (u32::from(italic) << 18)
447    }
448
449    /// Returns the index of the `[u32; 128]` ASCII slot table matching `(size_tenths, bold, monospace, italic)`, creating it if absent.
450    ///
451    /// # Arguments
452    ///
453    /// - `&Self` - Mutable glyph atlas reference.
454    /// - `u16` - Quantized physical font size in tenths of a pixel.
455    /// - `bool` - Bold flag.
456    /// - `bool` - Monospace family flag.
457    /// - `bool` - Italic flag.
458    ///
459    /// # Returns
460    ///
461    /// - `usize` - Index inside `ascii_tables` for zero-hash ASCII glyph resolution.
462    pub(crate) fn ascii_table_index(
463        &mut self,
464        size_tenths: u16,
465        bold: bool,
466        monospace: bool,
467        italic: bool,
468    ) -> usize {
469        let style_sig: u32 = Self::pack_style_sig(size_tenths, bold, monospace, italic);
470        let Self {
471            ascii_tables,
472            last_ascii_style_sig,
473            last_ascii_table_idx,
474            ..
475        } = self;
476        if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len() {
477            return *last_ascii_table_idx;
478        }
479        for (idx, table) in ascii_tables.iter().enumerate() {
480            if table.style_sig == style_sig {
481                *last_ascii_style_sig = style_sig;
482                *last_ascii_table_idx = idx;
483                return idx;
484            }
485        }
486        let idx: usize = ascii_tables.len();
487        ascii_tables.push(AsciiGlyphStyleTable {
488            style_sig,
489            slots: [u32::MAX; 128],
490        });
491        *last_ascii_style_sig = style_sig;
492        *last_ascii_table_idx = idx;
493        idx
494    }
495
496    /// Performs a zero-allocation read-only lookup of the flat arena slot for `key`.
497    ///
498    /// # Arguments
499    ///
500    /// - `&Self` - Glyph atlas reference.
501    /// - `GlyphKey` - Quantized glyph lookup key.
502    ///
503    /// # Returns
504    ///
505    /// - `Option<u32>` - Cached arena slot index when resident.
506    #[inline]
507    #[must_use]
508    pub fn lookup_slot(&self, key: GlyphKey) -> Option<u32> {
509        let Self {
510            glyph_index,
511            ascii_tables,
512            last_ascii_style_sig,
513            last_ascii_table_idx,
514            ..
515        } = self;
516        let code: u32 = key.get_codepoint() as u32;
517        if code < 128 && !ascii_tables.is_empty() {
518            let style_sig: u32 = Self::pack_style_sig(
519                key.get_size_tenths(),
520                key.get_bold(),
521                key.get_monospace(),
522                key.get_italic(),
523            );
524            if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len() {
525                let cached: u32 = ascii_tables[*last_ascii_table_idx].slots[code as usize];
526                if cached != u32::MAX {
527                    return Some(cached);
528                }
529            } else {
530                for table in ascii_tables.iter() {
531                    if table.style_sig == style_sig {
532                        let cached: u32 = table.slots[code as usize];
533                        if cached != u32::MAX {
534                            return Some(cached);
535                        }
536                        break;
537                    }
538                }
539            }
540        }
541        let packed_key: u64 = Self::pack_glyph_key(key);
542        Self::lookup_index(glyph_index, packed_key)
543    }
544
545    /// Performs a zero-allocation read-only lookup of a cached `RasterizedGlyph`.
546    ///
547    /// # Arguments
548    ///
549    /// - `&Self` - Glyph atlas reference.
550    /// - `GlyphKey` - Quantized glyph lookup key.
551    ///
552    /// # Returns
553    ///
554    /// - `Option<&RasterizedGlyph>` - Cached glyph bitmap when resident.
555    #[inline]
556    #[must_use]
557    pub fn lookup(&self, key: GlyphKey) -> Option<&RasterizedGlyph> {
558        let slot: u32 = self.lookup_slot(key)?;
559        self.get_glyph_by_slot(slot)
560    }
561
562    /// Performs a zero-hash, zero-allocation read-only lookup of an ASCII glyph slot in `ascii_tables[table_idx]`.
563    ///
564    /// # Arguments
565    ///
566    /// - `&Self` - Glyph atlas reference.
567    /// - `usize` - Style table index previously obtained from `ascii_table_index`.
568    /// - `u8` - ASCII byte in `0..128`.
569    ///
570    /// # Returns
571    ///
572    /// - `Option<u32>` - Cached arena slot index when resident.
573    #[inline(always)]
574    #[must_use]
575    pub fn lookup_ascii_slot(&self, table_idx: usize, byte: u8) -> Option<u32> {
576        let Self { ascii_tables, .. } = self;
577        if byte >= 128 {
578            return None;
579        }
580        let table: &AsciiGlyphStyleTable = ascii_tables.get(table_idx)?;
581        let slot: u32 = table.slots[byte as usize];
582        if slot == u32::MAX { None } else { Some(slot) }
583    }
584
585    /// Returns a bounds-checked zero-allocation reference to the cached glyph at arena `slot`.
586    ///
587    /// # Arguments
588    ///
589    /// - `&Self` - Glyph atlas reference.
590    /// - `u32` - Arena slot index returned by `lookup_slot` or `lookup_ascii_slot`.
591    ///
592    /// # Returns
593    ///
594    /// - `Option<&RasterizedGlyph>` - Cached glyph bitmap when `slot` is in bounds.
595    #[inline(always)]
596    #[must_use]
597    pub fn get_glyph_by_slot(&self, slot: u32) -> Option<&RasterizedGlyph> {
598        let Self { entries, .. } = self;
599        entries
600            .get(slot as usize)
601            .map(|entry: &(GlyphKey, RasterizedGlyph)| &entry.1)
602    }
603
604    /// Appends unique uncached `GlyphKey` entries from `keys` into caller-provided `out_missing` with zero temporary allocations.
605    ///
606    /// # Arguments
607    ///
608    /// - `&Self` - Glyph atlas reference.
609    /// - `&[GlyphKey]` - Candidate glyph keys to probe.
610    /// - `&mut Vec<GlyphKey>` - Reusable output buffer receiving deduplicated missing keys.
611    ///
612    /// # Returns
613    ///
614    /// - `usize` - Number of newly appended missing glyph keys.
615    pub fn collect_missing_keys(
616        &self,
617        keys: &[GlyphKey],
618        out_missing: &mut Vec<GlyphKey>,
619    ) -> usize {
620        let start: usize = out_missing.len();
621        for &key in keys.iter() {
622            if self.lookup_slot(key).is_none() {
623                out_missing.push(key);
624            }
625        }
626        let added_raw: usize = out_missing.len() - start;
627        if added_raw <= 1 {
628            return added_raw;
629        }
630        out_missing[start..].sort_unstable();
631        let mut write: usize = start + 1;
632        for read in (start + 1)..out_missing.len() {
633            if out_missing[read] != out_missing[write - 1] {
634                out_missing[write] = out_missing[read];
635                write += 1;
636            }
637        }
638        out_missing.truncate(write);
639        write - start
640    }
641
642    /// Batch-rasterizes all missing unique glyphs in `keys` through `provider` in a single pass and inserts them into the atlas.
643    ///
644    /// # Arguments
645    ///
646    /// - `&Self` - Mutable glyph atlas reference.
647    /// - `&[GlyphKey]` - Glyph keys needed for the current frame or text run.
648    /// - `&dyn SystemFontProvider` - Native or deterministic font provider supporting batched rasterization.
649    ///
650    /// # Returns
651    ///
652    /// - `usize` - Number of newly rasterized and inserted glyphs (`0` when all keys were already cached).
653    pub fn prewarm_batch_with(
654        &mut self,
655        keys: &[GlyphKey],
656        provider: &dyn SystemFontProvider,
657    ) -> usize {
658        let mut missing: Vec<GlyphKey> = Vec::new();
659        let missing_count: usize = self.collect_missing_keys(keys, &mut missing);
660        if missing_count == 0 {
661            return 0;
662        }
663        let mut rasterized: Vec<Option<RasterizedGlyph>> = provider.rasterize_batch(&missing);
664        let mut inserted: usize = 0;
665        for (idx, key) in missing.into_iter().enumerate() {
666            let glyph: RasterizedGlyph = rasterized
667                .get_mut(idx)
668                .and_then(Option::take)
669                .unwrap_or_else(|| rasterize_glyph(key));
670            let packed_key: u64 = Self::pack_glyph_key(key);
671            let style_sig: u32 = Self::pack_style_sig(
672                key.get_size_tenths(),
673                key.get_bold(),
674                key.get_monospace(),
675                key.get_italic(),
676            );
677            let _: u32 = self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true);
678            inserted += 1;
679        }
680        inserted
681    }
682
683    /// Prewarms all missing unique glyphs for `text` under `(physical_size, style)` in a single provider batch (`0` allocations when warm).
684    ///
685    /// # Arguments
686    ///
687    /// - `&Self` - Mutable glyph atlas reference.
688    /// - `&str` - UTF-8 text string whose missing glyphs should be rasterized together.
689    /// - `f32` - Physical font size in pixels.
690    /// - `TextStyle` - Typography style parameters.
691    /// - `&dyn SystemFontProvider` - Native or deterministic font provider.
692    ///
693    /// # Returns
694    ///
695    /// - `usize` - Number of newly rasterized and inserted glyphs.
696    pub fn prewarm_text_with(
697        &mut self,
698        text: &str,
699        physical_size: f32,
700        style: TextStyle,
701        provider: &dyn SystemFontProvider,
702    ) -> usize {
703        let mut missing: Vec<GlyphKey> = Vec::new();
704        for ch in text.chars() {
705            let key: GlyphKey = GlyphKey::from_text_style(ch, physical_size, style);
706            if self.lookup_slot(key).is_none() {
707                missing.push(key);
708            }
709        }
710        if missing.is_empty() {
711            return 0;
712        }
713        missing.sort_unstable();
714        missing.dedup();
715        let mut rasterized: Vec<Option<RasterizedGlyph>> = provider.rasterize_batch(&missing);
716        let mut inserted: usize = 0;
717        for (idx, key) in missing.into_iter().enumerate() {
718            let glyph: RasterizedGlyph = rasterized
719                .get_mut(idx)
720                .and_then(Option::take)
721                .unwrap_or_else(|| rasterize_glyph(key));
722            let packed_key: u64 = Self::pack_glyph_key(key);
723            let style_sig: u32 = Self::pack_style_sig(
724                key.get_size_tenths(),
725                key.get_bold(),
726                key.get_monospace(),
727                key.get_italic(),
728            );
729            let _: u32 = self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true);
730            inserted += 1;
731        }
732        inserted
733    }
734
735    /// Resolves an ASCII byte directly through `ascii_tables[table_idx]` with zero hash probing on hits.
736    ///
737    /// # Arguments
738    ///
739    /// - `&Self` - Mutable glyph atlas reference.
740    /// - `usize` - Style table index returned by `ascii_table_index`.
741    /// - `u8` - ASCII codepoint byte in `0..128`.
742    /// - `(u16, bool, bool, bool)` - Quantized style metadata `(size_tenths, bold, monospace, italic)`.
743    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
744    ///
745    /// # Returns
746    ///
747    /// - `u32` - Direct slot index into `entries`.
748    #[inline(always)]
749    pub(crate) fn get_or_rasterize_ascii_slot_with(
750        &mut self,
751        table_idx: usize,
752        byte: u8,
753        key_meta: (u16, bool, bool, bool),
754        provider: &dyn SystemFontProvider,
755    ) -> u32 {
756        let Self {
757            ascii_tables,
758            entry_last_used,
759            entry_fence_ids,
760            active_fence_id,
761            lru_clock,
762            cache_hits,
763            ..
764        } = self;
765        let cached: u32 = ascii_tables[table_idx].slots[byte as usize];
766        if cached != u32::MAX {
767            *cache_hits = cache_hits.wrapping_add(1);
768            *lru_clock = lru_clock.wrapping_add(1);
769            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
770                *tick = *lru_clock;
771            }
772            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
773                *fence = (*fence).max(*active_fence_id);
774            }
775            return cached;
776        }
777        let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
778        let key: GlyphKey = GlyphKey {
779            codepoint: byte as char,
780            size_tenths,
781            bold,
782            monospace,
783            italic,
784        };
785        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
786        let Self { ascii_tables, .. } = self;
787        ascii_tables[table_idx].slots[byte as usize] = slot;
788        if byte.is_ascii_digit() {
789            for digit in ASCII_DIGIT_ZERO..=ASCII_DIGIT_NINE {
790                if digit == byte {
791                    continue;
792                }
793                let already_cached: bool = {
794                    let Self { ascii_tables, .. } = self;
795                    ascii_tables[table_idx].slots[digit as usize] != u32::MAX
796                };
797                if !already_cached {
798                    let d_key: GlyphKey = GlyphKey {
799                        codepoint: digit as char,
800                        size_tenths,
801                        bold,
802                        monospace,
803                        italic,
804                    };
805                    let d_slot: u32 = self.get_or_rasterize_slot_with(d_key, provider);
806                    let Self { ascii_tables, .. } = self;
807                    ascii_tables[table_idx].slots[digit as usize] = d_slot;
808                }
809            }
810        }
811        slot
812    }
813
814    /// Inserts a newly rasterized glyph into the arena, enforcing the bounded memory budget when unpinned.
815    ///
816    /// # Arguments
817    ///
818    /// - `&Self` - Mutable glyph atlas reference.
819    /// - `GlyphKey` - Quantized glyph lookup key.
820    /// - `u64` - Pre-packed 40-bit glyph key.
821    /// - `u32` - Pre-packed style signature for ASCII table updates.
822    /// - `RasterizedGlyph` - Newly rasterized coverage bitmap.
823    /// - `bool` - Whether a missing ASCII style table should be created automatically.
824    ///
825    /// # Returns
826    ///
827    /// - `u32` - Newly assigned arena slot index.
828    fn insert_rasterized_glyph(
829        &mut self,
830        key: GlyphKey,
831        packed_key: u64,
832        style_sig: u32,
833        glyph: RasterizedGlyph,
834        create_ascii_table: bool,
835    ) -> u32 {
836        let entry_sz: usize = Self::entry_bytes(&glyph);
837        let budget: usize = self.effective_budget_bytes();
838        let needs_evict: bool = {
839            let Self {
840                resident_bytes,
841                slots_pinned,
842                entries,
843                ..
844            } = self;
845            !*slots_pinned
846                && !entries.is_empty()
847                && resident_bytes.saturating_add(entry_sz) > budget
848        };
849        if needs_evict {
850            let target: usize = budget
851                .saturating_mul(3)
852                .saturating_div(4)
853                .saturating_sub(entry_sz);
854            self.evict_lru_to_target(target);
855        }
856        let code: u32 = key.get_codepoint() as u32;
857        let Self {
858            glyph_index,
859            entries,
860            entry_last_used,
861            entry_fence_ids,
862            active_fence_id,
863            ascii_tables,
864            revision,
865            resident_bytes,
866            lru_clock,
867            cache_misses,
868            ..
869        } = self;
870        if entries.is_empty() {
871            entries.reserve(GLYPH_ENTRIES_INIT_CAP);
872            entry_last_used.reserve(GLYPH_ENTRIES_INIT_CAP);
873            entry_fence_ids.reserve(GLYPH_ENTRIES_INIT_CAP);
874        }
875        *cache_misses = cache_misses.wrapping_add(1);
876        *lru_clock = lru_clock.wrapping_add(1);
877        let slot: u32 = entries.len() as u32;
878        entries.push((key, glyph));
879        entry_last_used.push(*lru_clock);
880        entry_fence_ids.push(*active_fence_id);
881        *resident_bytes = resident_bytes.saturating_add(entry_sz);
882        Self::insert_index(glyph_index, entries.len(), packed_key, slot);
883        if code < 128 {
884            let mut updated: bool = false;
885            for table in ascii_tables.iter_mut() {
886                if table.style_sig == style_sig {
887                    table.slots[code as usize] = slot;
888                    updated = true;
889                    break;
890                }
891            }
892            if create_ascii_table && !updated {
893                if ascii_tables.is_empty() {
894                    ascii_tables.reserve(8);
895                }
896                let mut slots: [u32; 128] = [u32::MAX; 128];
897                slots[code as usize] = slot;
898                ascii_tables.push(AsciiGlyphStyleTable { style_sig, slots });
899            }
900        }
901        *revision = revision.wrapping_add(1);
902        slot
903    }
904
905    /// Returns the arena slot index for `key`, rasterizing through `rasterize_glyph` on a miss.
906    ///
907    /// # Arguments
908    ///
909    /// - `&Self` - Mutable glyph atlas reference.
910    /// - `GlyphKey` - Quantized glyph lookup key.
911    ///
912    /// # Returns
913    ///
914    /// - `u32` - Direct slot index into `entries`.
915    #[inline]
916    pub(crate) fn get_or_rasterize_slot(&mut self, key: GlyphKey) -> u32 {
917        let code: u32 = key.get_codepoint() as u32;
918        let style_sig: u32 = Self::pack_style_sig(
919            key.get_size_tenths(),
920            key.get_bold(),
921            key.get_monospace(),
922            key.get_italic(),
923        );
924        let packed_key: u64 = Self::pack_glyph_key(key);
925        {
926            let Self {
927                glyph_index,
928                entry_last_used,
929                entry_fence_ids,
930                active_fence_id,
931                ascii_tables,
932                lru_clock,
933                cache_hits,
934                ..
935            } = self;
936            if code < 128 {
937                for table in ascii_tables.iter() {
938                    if table.style_sig == style_sig {
939                        let cached: u32 = table.slots[code as usize];
940                        if cached != u32::MAX {
941                            *cache_hits = cache_hits.wrapping_add(1);
942                            *lru_clock = lru_clock.wrapping_add(1);
943                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
944                                *tick = *lru_clock;
945                            }
946                            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
947                                *fence = (*fence).max(*active_fence_id);
948                            }
949                            return cached;
950                        }
951                        break;
952                    }
953                }
954            }
955            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
956                *cache_hits = cache_hits.wrapping_add(1);
957                *lru_clock = lru_clock.wrapping_add(1);
958                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
959                    *tick = *lru_clock;
960                }
961                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
962                    *fence = (*fence).max(*active_fence_id);
963                }
964                if code < 128 {
965                    for table in ascii_tables.iter_mut() {
966                        if table.style_sig == style_sig {
967                            table.slots[code as usize] = slot;
968                            break;
969                        }
970                    }
971                }
972                return slot;
973            }
974        }
975        let glyph: RasterizedGlyph = rasterize_glyph(key);
976        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
977    }
978
979    /// Returns the arena slot index for `key`, rasterizing through `provider` on a miss.
980    ///
981    /// # Arguments
982    ///
983    /// - `&Self` - Mutable glyph atlas reference.
984    /// - `GlyphKey` - Quantized glyph lookup key.
985    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
986    ///
987    /// # Returns
988    ///
989    /// - `u32` - Direct slot index into `entries`.
990    #[inline]
991    pub(crate) fn get_or_rasterize_slot_with(
992        &mut self,
993        key: GlyphKey,
994        provider: &dyn SystemFontProvider,
995    ) -> u32 {
996        let code: u32 = key.get_codepoint() as u32;
997        let style_sig: u32 = Self::pack_style_sig(
998            key.get_size_tenths(),
999            key.get_bold(),
1000            key.get_monospace(),
1001            key.get_italic(),
1002        );
1003        let packed_key: u64 = Self::pack_glyph_key(key);
1004        {
1005            let Self {
1006                glyph_index,
1007                entry_last_used,
1008                entry_fence_ids,
1009                active_fence_id,
1010                ascii_tables,
1011                last_ascii_style_sig,
1012                last_ascii_table_idx,
1013                lru_clock,
1014                cache_hits,
1015                ..
1016            } = self;
1017            if code < 128 && !ascii_tables.is_empty() {
1018                if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len()
1019                {
1020                    let cached: u32 = ascii_tables[*last_ascii_table_idx].slots[code as usize];
1021                    if cached != u32::MAX {
1022                        *cache_hits = cache_hits.wrapping_add(1);
1023                        *lru_clock = lru_clock.wrapping_add(1);
1024                        if let Some(tick) = entry_last_used.get_mut(cached as usize) {
1025                            *tick = *lru_clock;
1026                        }
1027                        if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
1028                            *fence = (*fence).max(*active_fence_id);
1029                        }
1030                        return cached;
1031                    }
1032                } else {
1033                    for (idx, table) in ascii_tables.iter().enumerate() {
1034                        if table.style_sig == style_sig {
1035                            *last_ascii_style_sig = style_sig;
1036                            *last_ascii_table_idx = idx;
1037                            let cached: u32 = table.slots[code as usize];
1038                            if cached != u32::MAX {
1039                                *cache_hits = cache_hits.wrapping_add(1);
1040                                *lru_clock = lru_clock.wrapping_add(1);
1041                                if let Some(tick) = entry_last_used.get_mut(cached as usize) {
1042                                    *tick = *lru_clock;
1043                                }
1044                                if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
1045                                    *fence = (*fence).max(*active_fence_id);
1046                                }
1047                                return cached;
1048                            }
1049                            break;
1050                        }
1051                    }
1052                }
1053            }
1054            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
1055                *cache_hits = cache_hits.wrapping_add(1);
1056                *lru_clock = lru_clock.wrapping_add(1);
1057                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
1058                    *tick = *lru_clock;
1059                }
1060                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
1061                    *fence = (*fence).max(*active_fence_id);
1062                }
1063                if code < 128 {
1064                    for (idx, table) in ascii_tables.iter_mut().enumerate() {
1065                        if table.style_sig == style_sig {
1066                            table.slots[code as usize] = slot;
1067                            *last_ascii_style_sig = style_sig;
1068                            *last_ascii_table_idx = idx;
1069                            break;
1070                        }
1071                    }
1072                }
1073                return slot;
1074            }
1075        }
1076        let glyph: RasterizedGlyph = provider
1077            .rasterize(key)
1078            .unwrap_or_else(|| rasterize_glyph(key));
1079        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
1080    }
1081
1082    /// Returns a read-only reference to the `RasterizedGlyph` at flat arena index `slot`.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// - `&Self` - Glyph atlas reference.
1087    /// - `u32` - Valid slot index into `entries`.
1088    ///
1089    /// # Returns
1090    ///
1091    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1092    #[inline(always)]
1093    #[must_use]
1094    pub(crate) fn glyph_by_slot(&self, slot: u32) -> &RasterizedGlyph {
1095        let Self { entries, .. } = self;
1096        &entries[slot as usize].1
1097    }
1098
1099    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing and inserting it on a miss.
1100    ///
1101    /// # Arguments
1102    ///
1103    /// - `&Self` - Mutable reference to the glyph atlas.
1104    /// - `GlyphKey` - Quantized glyph lookup key.
1105    ///
1106    /// # Returns
1107    ///
1108    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1109    #[inline]
1110    pub fn get_or_rasterize(&mut self, key: GlyphKey) -> &RasterizedGlyph {
1111        let slot: u32 = self.get_or_rasterize_slot(key);
1112        self.glyph_by_slot(slot)
1113    }
1114
1115    /// Returns the total number of cached glyph entries.
1116    ///
1117    /// # Arguments
1118    ///
1119    /// - `&Self` - Glyph atlas reference.
1120    ///
1121    /// # Returns
1122    ///
1123    /// - `usize` - Number of cached glyphs.
1124    #[must_use]
1125    pub fn len(&self) -> usize {
1126        self.get_entries().len()
1127    }
1128
1129    /// Returns true when the atlas contains no cached glyphs.
1130    ///
1131    /// # Arguments
1132    ///
1133    /// - `&Self` - Glyph atlas reference.
1134    ///
1135    /// # Returns
1136    ///
1137    /// - `bool` - True if empty.
1138    #[must_use]
1139    pub fn is_empty(&self) -> bool {
1140        self.get_entries().is_empty()
1141    }
1142
1143    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing through `provider` on a miss.
1144    ///
1145    /// # Arguments
1146    ///
1147    /// - `&Self` - Mutable reference to the glyph atlas.
1148    /// - `GlyphKey` - Quantized glyph lookup key.
1149    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
1150    ///
1151    /// # Returns
1152    ///
1153    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1154    #[inline]
1155    pub fn get_or_rasterize_with(
1156        &mut self,
1157        key: GlyphKey,
1158        provider: &dyn SystemFontProvider,
1159    ) -> &RasterizedGlyph {
1160        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
1161        self.glyph_by_slot(slot)
1162    }
1163
1164    /// Blits one glyph's 8-bit coverage bitmap into a white-RGB RGBA8 atlas slice at `(rx, ry)`.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&RasterizedGlyph` - Source coverage bitmap.
1169    /// - `&mut [u8]` - Destination RGBA8 atlas pixel buffer.
1170    /// - `usize` - Atlas width in pixels.
1171    /// - `u32` - Destination X pixel offset.
1172    /// - `u32` - Destination Y pixel offset.
1173    #[inline]
1174    fn blit_glyph_to_rgba(
1175        glyph: &RasterizedGlyph,
1176        pixels: &mut [u8],
1177        atlas_w: usize,
1178        rx: u32,
1179        ry: u32,
1180    ) {
1181        let gw: usize = glyph.get_width() as usize;
1182        let gh: usize = glyph.get_height() as usize;
1183        let cov: &[u8] = glyph.get_coverage().as_slice();
1184        let row_stride: usize = atlas_w * 4;
1185        let mut src_off: usize = 0;
1186        let mut dst_off: usize = ((ry as usize) * atlas_w + (rx as usize)) * 4;
1187        for _ in 0..gh {
1188            let src_row: &[u8] = &cov[src_off..src_off + gw];
1189            let dst_row: &mut [u8] = &mut pixels[dst_off..dst_off + gw * 4];
1190            let (src_quads, src_rem): (&[[u8; 4]], &[u8]) = src_row.as_chunks::<4>();
1191            let (dst_quads, dst_rem): (&mut [[u8; 16]], &mut [u8]) = dst_row.as_chunks_mut::<16>();
1192            for (a4, dst16) in src_quads.iter().zip(dst_quads.iter_mut()) {
1193                *dst16 = [
1194                    255, 255, 255, a4[0], 255, 255, 255, a4[1], 255, 255, 255, a4[2], 255, 255,
1195                    255, a4[3],
1196                ];
1197            }
1198            for (alpha, dst4) in src_rem
1199                .iter()
1200                .copied()
1201                .zip(dst_rem.as_chunks_mut::<4>().0.iter_mut())
1202            {
1203                *dst4 = [255, 255, 255, alpha];
1204            }
1205            src_off += gw;
1206            dst_off += row_stride;
1207        }
1208    }
1209
1210    /// Shelf-packs all cached glyphs into a single GPU-uploadable RGBA8 texture atlas.
1211    ///
1212    /// # Arguments
1213    ///
1214    /// - `&Self` - Glyph atlas reference.
1215    ///
1216    /// # Returns
1217    ///
1218    /// - `PackedGlyphAtlas` - Packed RGBA8 texture, per-glyph UV rects, and revision tag.
1219    #[must_use]
1220    pub fn pack_rgba_atlas(&self) -> PackedGlyphAtlas {
1221        let entries: &[(GlyphKey, RasterizedGlyph)] = self.get_entries().as_slice();
1222        let glyph_count: usize = entries.len();
1223        let mut total_row_w: u32 = 1;
1224        let mut max_glyph_w: u32 = 0;
1225        for (_, glyph) in entries.iter() {
1226            let gw: u32 = glyph.get_width();
1227            total_row_w = total_row_w.saturating_add(gw.saturating_add(1));
1228            if gw > max_glyph_w {
1229                max_glyph_w = gw;
1230            }
1231        }
1232        let min_needed_w: u32 = max_glyph_w.saturating_add(2).max(ATLAS_MIN_DIM);
1233        let preferred_w: u32 = if glyph_count > 160 || total_row_w > ATLAS_DEFAULT_WIDTH * 8 {
1234            (ATLAS_DEFAULT_WIDTH * 2).max(min_needed_w.next_power_of_two())
1235        } else {
1236            ATLAS_DEFAULT_WIDTH.max(min_needed_w.next_power_of_two())
1237        };
1238        let atlas_w: u32 = if total_row_w <= ATLAS_DEFAULT_WIDTH {
1239            total_row_w
1240                .max(ATLAS_MIN_DIM)
1241                .next_power_of_two()
1242                .min(ATLAS_DEFAULT_WIDTH)
1243        } else {
1244            preferred_w
1245        };
1246        let mut cursor_x: u32 = 1;
1247        let mut cursor_y: u32 = 1;
1248        let mut shelf_h: u32 = 0;
1249        let mut regions: HashMap<GlyphKey, (u32, u32, u32, u32)> =
1250            HashMap::with_capacity(glyph_count);
1251        let use_stack: bool = glyph_count <= ATLAS_STACK_PLACEMENTS;
1252        let mut stack_placements: [(usize, u32, u32); ATLAS_STACK_PLACEMENTS] =
1253            [(0, 0, 0); ATLAS_STACK_PLACEMENTS];
1254        let mut heap_placements: Vec<(usize, u32, u32)> = if use_stack {
1255            Vec::new()
1256        } else {
1257            Vec::with_capacity(glyph_count)
1258        };
1259        for (idx, (key, glyph)) in entries.iter().enumerate() {
1260            let gw: u32 = glyph.get_width();
1261            let gh: u32 = glyph.get_height();
1262            if cursor_x + gw + 1 > atlas_w {
1263                cursor_x = 1;
1264                cursor_y += shelf_h + 1;
1265                shelf_h = 0;
1266            }
1267            let _: Option<(u32, u32, u32, u32)> =
1268                regions.insert(*key, (cursor_x, cursor_y, gw, gh));
1269            if use_stack {
1270                stack_placements[idx] = (idx, cursor_x, cursor_y);
1271            } else {
1272                heap_placements.push((idx, cursor_x, cursor_y));
1273            }
1274            cursor_x += gw + 1;
1275            shelf_h = shelf_h.max(gh);
1276        }
1277        let atlas_h: u32 = (cursor_y + shelf_h + 1).max(ATLAS_MIN_DIM);
1278        let atlas_w_usize: usize = atlas_w as usize;
1279        let mut pixels: Vec<u8> = vec![0; atlas_w_usize * (atlas_h as usize) * 4];
1280        let placements: &[(usize, u32, u32)] = if use_stack {
1281            &stack_placements[..glyph_count]
1282        } else {
1283            heap_placements.as_slice()
1284        };
1285        for &(entry_idx, rx, ry) in placements.iter() {
1286            Self::blit_glyph_to_rgba(&entries[entry_idx].1, &mut pixels, atlas_w_usize, rx, ry);
1287        }
1288        PackedGlyphAtlas::new(atlas_w, atlas_h, pixels, regions, self.get_revision())
1289    }
1290
1291    /// Clears all cached glyphs and increments the atlas revision.
1292    ///
1293    /// # Arguments
1294    ///
1295    /// - `&Self` - Mutable reference to the glyph atlas.
1296    pub fn clear(&mut self) {
1297        self.clear_with_fence_deferral();
1298    }
1299}