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    /// Returns the number of recent DPI snapshots currently cached for hysteresis restore (`0..=2`).
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Glyph atlas reference.
182    ///
183    /// # Returns
184    ///
185    /// - `usize` - Number of retained recent-DPI hysteresis snapshots.
186    #[must_use]
187    pub fn recent_dpi_slot_count(&self) -> usize {
188        let Self {
189            recent_dpi_slots, ..
190        } = self;
191        recent_dpi_slots.len()
192    }
193
194    /// Invalidates bitmap atlas entries independently of text shaping whenever DPI scale, AA mode, or font chain changes, retaining up to two recent DPI snapshots for zero-thrash multi-monitor transitions while never reusing wrong-DPI glyphs.
195    ///
196    /// # Arguments
197    ///
198    /// - `&Self` - Mutable glyph atlas reference.
199    /// - `f32` - Active display scale factor.
200    /// - `AntialiasingMode` - Active anti-aliasing policy.
201    /// - `u64` - Active font fallback chain revision.
202    ///
203    /// # Returns
204    ///
205    /// - `bool` - `true` when active atlas bitmaps changed and outgoing GPU allocations were queued for fence-deferred release.
206    pub fn invalidate_for_render_params(
207        &mut self,
208        dpi_scale: f32,
209        aa: AntialiasingMode,
210        font_chain_revision: u64,
211    ) -> bool {
212        let next_dpi_bits: u32 = clamp_viewport_scale(dpi_scale).to_bits();
213        let prev_dpi_bits: u32 = self.get_active_dpi_scale_bits();
214        let prev_aa: AntialiasingMode = self.get_active_aa_mode();
215        let prev_font_rev: u64 = self.get_font_chain_revision();
216        if prev_dpi_bits == 0 {
217            let Self {
218                active_dpi_scale_bits,
219                active_aa_mode,
220                font_chain_revision: cur_font_rev,
221                ..
222            } = self;
223            *active_dpi_scale_bits = next_dpi_bits;
224            *active_aa_mode = aa;
225            *cur_font_rev = font_chain_revision;
226            return false;
227        }
228        let unchanged: bool =
229            prev_dpi_bits == next_dpi_bits && prev_aa == aa && prev_font_rev == font_chain_revision;
230        if unchanged {
231            return false;
232        }
233        let same_render_family: bool = prev_aa == aa && prev_font_rev == font_chain_revision;
234        let outgoing_snapshot: Option<DpiAtlasSnapshot> = if same_render_family {
235            let Self {
236                entries,
237                entry_last_used,
238                resident_bytes,
239                lru_clock,
240                ..
241            } = self;
242            if entries.is_empty() {
243                None
244            } else {
245                Some(DpiAtlasSnapshot {
246                    dpi_scale_bits: prev_dpi_bits,
247                    aa_mode: prev_aa,
248                    font_chain_revision: prev_font_rev,
249                    entries: entries.clone(),
250                    entry_last_used: entry_last_used.clone(),
251                    resident_bytes: *resident_bytes,
252                    stashed_tick: *lru_clock,
253                })
254            }
255        } else {
256            None
257        };
258        {
259            let Self {
260                active_dpi_scale_bits,
261                active_aa_mode,
262                font_chain_revision: cur_font_rev,
263                recent_dpi_slots,
264                ..
265            } = self;
266            *active_dpi_scale_bits = next_dpi_bits;
267            *active_aa_mode = aa;
268            *cur_font_rev = font_chain_revision;
269            if !same_render_family {
270                recent_dpi_slots.clear();
271            }
272        }
273        self.clear_with_fence_deferral();
274        let restored: Option<DpiAtlasSnapshot> = if same_render_family {
275            let Self {
276                recent_dpi_slots, ..
277            } = self;
278            let matched_pos: Option<usize> =
279                recent_dpi_slots.iter().position(|slot: &DpiAtlasSnapshot| {
280                    slot.dpi_scale_bits == next_dpi_bits
281                        && slot.aa_mode == aa
282                        && slot.font_chain_revision == font_chain_revision
283                });
284            let taken: Option<DpiAtlasSnapshot> =
285                matched_pos.map(|pos: usize| recent_dpi_slots.remove(pos));
286            if let Some(stash) = outgoing_snapshot {
287                recent_dpi_slots
288                    .retain(|slot: &DpiAtlasSnapshot| slot.dpi_scale_bits != stash.dpi_scale_bits);
289                if recent_dpi_slots.len() >= GLYPH_ATLAS_DPI_HYSTERESIS_SLOTS
290                    && let Some((oldest_idx, _)) = recent_dpi_slots
291                        .iter()
292                        .enumerate()
293                        .min_by_key(|(_, slot): &(usize, &DpiAtlasSnapshot)| slot.stashed_tick)
294                {
295                    let _: DpiAtlasSnapshot = recent_dpi_slots.remove(oldest_idx);
296                }
297                recent_dpi_slots.push(stash);
298            }
299            taken
300        } else {
301            None
302        };
303        if let Some(snapshot) = restored {
304            let active_fence: u64 = self.get_active_fence_id();
305            let Self {
306                glyph_index,
307                entries,
308                entry_last_used,
309                entry_fence_ids,
310                resident_bytes,
311                dpi_hysteresis_restores,
312                ..
313            } = self;
314            let count: usize = snapshot.entries.len();
315            *entries = snapshot.entries;
316            *entry_last_used = snapshot.entry_last_used;
317            *entry_fence_ids = vec![active_fence; count];
318            *resident_bytes = snapshot.resident_bytes;
319            glyph_index.fill(GLYPH_INDEX_EMPTY);
320            for (slot_idx, (key, _)) in entries.iter().enumerate() {
321                let packed_key: u64 = Self::pack_glyph_key(*key);
322                Self::insert_index(glyph_index, slot_idx + 1, packed_key, slot_idx as u32);
323            }
324            *dpi_hysteresis_restores = dpi_hysteresis_restores.saturating_add(1);
325        }
326        true
327    }
328
329    /// Clears all resident bitmap entries, moving in-flight GPU-referenced entries to `pending_reclaim`.
330    ///
331    /// # Arguments
332    ///
333    /// - `&Self` - Mutable glyph atlas reference.
334    fn clear_with_fence_deferral(&mut self) {
335        let Self {
336            glyph_index,
337            entries,
338            entry_last_used,
339            entry_fence_ids,
340            ascii_tables,
341            last_ascii_style_sig,
342            last_ascii_table_idx,
343            revision,
344            resident_bytes,
345            completed_fence_id,
346            pending_reclaim,
347            pending_reclaim_bytes,
348            reclaimed_entries,
349            ..
350        } = self;
351        let completed: u64 = *completed_fence_id;
352        for (idx, (_, glyph)) in entries.iter().enumerate() {
353            let bytes: usize = Self::entry_bytes(glyph);
354            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
355            if fence > completed {
356                pending_reclaim.push((fence, bytes));
357                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
358            } else {
359                *reclaimed_entries = reclaimed_entries.saturating_add(1);
360            }
361        }
362        glyph_index.fill(GLYPH_INDEX_EMPTY);
363        entries.clear();
364        entry_last_used.clear();
365        entry_fence_ids.clear();
366        ascii_tables.clear();
367        *last_ascii_style_sig = 0;
368        *last_ascii_table_idx = 0;
369        *resident_bytes = 0;
370        *revision = revision.wrapping_add(1);
371    }
372
373    /// 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.
374    ///
375    /// # Arguments
376    ///
377    /// - `&Self` - Mutable glyph atlas reference.
378    /// - `usize` - Target post-eviction resident byte ceiling.
379    fn evict_lru_to_target(&mut self, target_bytes: usize) {
380        let Self {
381            glyph_index,
382            entries,
383            entry_last_used,
384            entry_fence_ids,
385            ascii_tables,
386            revision,
387            resident_bytes,
388            evictions,
389            completed_fence_id,
390            pending_reclaim,
391            pending_reclaim_bytes,
392            reclaimed_entries,
393            ..
394        } = self;
395        let count: usize = entries.len();
396        if count == 0 || *resident_bytes <= target_bytes {
397            return;
398        }
399        let mut order: Vec<usize> = (0..count).collect();
400        order.sort_unstable_by_key(|idx: &usize| entry_last_used.get(*idx).copied().unwrap_or(0));
401        let mut keep: Vec<bool> = vec![true; count];
402        let mut remaining_bytes: usize = *resident_bytes;
403        let mut evicted_count: usize = 0;
404        let completed: u64 = *completed_fence_id;
405        for idx in order.into_iter() {
406            if remaining_bytes <= target_bytes {
407                break;
408            }
409            let bytes: usize = Self::entry_bytes(&entries[idx].1);
410            let fence: u64 = entry_fence_ids.get(idx).copied().unwrap_or(0);
411            if fence > completed {
412                pending_reclaim.push((fence, bytes));
413                *pending_reclaim_bytes = pending_reclaim_bytes.saturating_add(bytes);
414            } else {
415                *reclaimed_entries = reclaimed_entries.saturating_add(1);
416            }
417            remaining_bytes = remaining_bytes.saturating_sub(bytes);
418            keep[idx] = false;
419            evicted_count += 1;
420        }
421        if evicted_count == 0 {
422            return;
423        }
424        let mut write_idx: usize = 0;
425        let mut next_resident: usize = 0;
426        for (read_idx, &kept) in keep.iter().enumerate() {
427            if kept {
428                if write_idx != read_idx {
429                    entries.swap(write_idx, read_idx);
430                    if read_idx < entry_last_used.len() && write_idx < entry_last_used.len() {
431                        entry_last_used.swap(write_idx, read_idx);
432                    }
433                    if read_idx < entry_fence_ids.len() && write_idx < entry_fence_ids.len() {
434                        entry_fence_ids.swap(write_idx, read_idx);
435                    }
436                }
437                next_resident =
438                    next_resident.saturating_add(Self::entry_bytes(&entries[write_idx].1));
439                write_idx += 1;
440            }
441        }
442        entries.truncate(write_idx);
443        entry_last_used.truncate(write_idx);
444        entry_fence_ids.truncate(write_idx);
445        *resident_bytes = next_resident;
446        *evictions = evictions.saturating_add(evicted_count as u64);
447        glyph_index.fill(GLYPH_INDEX_EMPTY);
448        for (slot_idx, (key, _)) in entries.iter().enumerate() {
449            let packed_key: u64 = Self::pack_glyph_key(*key);
450            Self::insert_index(glyph_index, slot_idx + 1, packed_key, slot_idx as u32);
451        }
452        for table in ascii_tables.iter_mut() {
453            table.slots.fill(u32::MAX);
454        }
455        *revision = revision.wrapping_add(1);
456    }
457
458    /// Probes the open-addressed `glyph_index` slice for `packed_key`.
459    ///
460    /// # Arguments
461    ///
462    /// - `&[u64]` - Power-of-two open-addressed index table.
463    /// - `u64` - Lossless 40-bit packed glyph key.
464    ///
465    /// # Returns
466    ///
467    /// - `Option<u32>` - Cached arena slot index when present.
468    #[inline(always)]
469    #[must_use]
470    fn lookup_index(glyph_index: &[u64], packed_key: u64) -> Option<u32> {
471        let cap: usize = glyph_index.len();
472        if cap == 0 {
473            return None;
474        }
475        let mask: usize = cap - 1;
476        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
477        loop {
478            let entry: u64 = glyph_index[idx];
479            if entry == GLYPH_INDEX_EMPTY {
480                return None;
481            }
482            if (entry & GLYPH_INDEX_KEY_MASK) == packed_key {
483                return Some((entry >> GLYPH_INDEX_SLOT_SHIFT) as u32);
484            }
485            idx = (idx + 1) & mask;
486        }
487    }
488
489    /// Inserts `(packed_key, slot)` into the open-addressed `glyph_index` table, doubling capacity at 75% load.
490    ///
491    /// # Arguments
492    ///
493    /// - `&mut Vec<u64>` - Open-addressed index table storage.
494    /// - `usize` - Current total entry count including the newly inserted glyph.
495    /// - `u64` - Lossless 40-bit packed glyph key.
496    /// - `u32` - Arena slot index into `entries`.
497    fn insert_index(glyph_index: &mut Vec<u64>, entry_count: usize, packed_key: u64, slot: u32) {
498        let cap: usize = glyph_index.len();
499        if cap == 0 {
500            glyph_index.resize(GLYPH_INDEX_INIT_CAP, GLYPH_INDEX_EMPTY);
501        } else if entry_count * 4 > cap * 3 {
502            let new_cap: usize = cap * 2;
503            let new_mask: usize = new_cap - 1;
504            let mut grown: Vec<u64> = vec![GLYPH_INDEX_EMPTY; new_cap];
505            for old_entry in glyph_index.iter().copied() {
506                if old_entry == GLYPH_INDEX_EMPTY {
507                    continue;
508                }
509                let old_key: u64 = old_entry & GLYPH_INDEX_KEY_MASK;
510                let mut idx: usize = Self::hash_packed_key(old_key) & new_mask;
511                while grown[idx] != GLYPH_INDEX_EMPTY {
512                    idx = (idx + 1) & new_mask;
513                }
514                grown[idx] = old_entry;
515            }
516            *glyph_index = grown;
517        }
518        let mask: usize = glyph_index.len() - 1;
519        let packed_entry: u64 = packed_key | ((slot as u64) << GLYPH_INDEX_SLOT_SHIFT);
520        let mut idx: usize = Self::hash_packed_key(packed_key) & mask;
521        loop {
522            let existing: u64 = glyph_index[idx];
523            if existing == GLYPH_INDEX_EMPTY || (existing & GLYPH_INDEX_KEY_MASK) == packed_key {
524                glyph_index[idx] = packed_entry;
525                return;
526            }
527            idx = (idx + 1) & mask;
528        }
529    }
530
531    /// Packs quantized glyph style attributes into a compact 32-bit signature for ASCII table matching.
532    ///
533    /// # Arguments
534    ///
535    /// - `u16` - Quantized physical font size in tenths of a pixel.
536    /// - `bool` - Bold flag.
537    /// - `bool` - Monospace family flag.
538    /// - `bool` - Italic flag.
539    ///
540    /// # Returns
541    ///
542    /// - `u32` - Packed style signature.
543    #[inline(always)]
544    #[must_use]
545    pub(crate) fn pack_style_sig(
546        size_tenths: u16,
547        bold: bool,
548        monospace: bool,
549        italic: bool,
550    ) -> u32 {
551        (size_tenths as u32)
552            | (u32::from(bold) << 16)
553            | (u32::from(monospace) << 17)
554            | (u32::from(italic) << 18)
555    }
556
557    /// Returns the index of the `[u32; 128]` ASCII slot table matching `(size_tenths, bold, monospace, italic)`, creating it if absent.
558    ///
559    /// # Arguments
560    ///
561    /// - `&Self` - Mutable glyph atlas reference.
562    /// - `u16` - Quantized physical font size in tenths of a pixel.
563    /// - `bool` - Bold flag.
564    /// - `bool` - Monospace family flag.
565    /// - `bool` - Italic flag.
566    ///
567    /// # Returns
568    ///
569    /// - `usize` - Index inside `ascii_tables` for zero-hash ASCII glyph resolution.
570    pub(crate) fn ascii_table_index(
571        &mut self,
572        size_tenths: u16,
573        bold: bool,
574        monospace: bool,
575        italic: bool,
576    ) -> usize {
577        let style_sig: u32 = Self::pack_style_sig(size_tenths, bold, monospace, italic);
578        let Self {
579            ascii_tables,
580            last_ascii_style_sig,
581            last_ascii_table_idx,
582            ..
583        } = self;
584        if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len() {
585            return *last_ascii_table_idx;
586        }
587        for (idx, table) in ascii_tables.iter().enumerate() {
588            if table.style_sig == style_sig {
589                *last_ascii_style_sig = style_sig;
590                *last_ascii_table_idx = idx;
591                return idx;
592            }
593        }
594        let idx: usize = ascii_tables.len();
595        ascii_tables.push(AsciiGlyphStyleTable {
596            style_sig,
597            slots: [u32::MAX; 128],
598        });
599        *last_ascii_style_sig = style_sig;
600        *last_ascii_table_idx = idx;
601        idx
602    }
603
604    /// Performs a zero-allocation read-only lookup of the flat arena slot for `key`.
605    ///
606    /// # Arguments
607    ///
608    /// - `&Self` - Glyph atlas reference.
609    /// - `GlyphKey` - Quantized glyph lookup key.
610    ///
611    /// # Returns
612    ///
613    /// - `Option<u32>` - Cached arena slot index when resident.
614    #[inline]
615    #[must_use]
616    pub fn lookup_slot(&self, key: GlyphKey) -> Option<u32> {
617        let Self {
618            glyph_index,
619            ascii_tables,
620            last_ascii_style_sig,
621            last_ascii_table_idx,
622            ..
623        } = self;
624        let code: u32 = key.get_codepoint() as u32;
625        if code < 128 && !ascii_tables.is_empty() {
626            let style_sig: u32 = Self::pack_style_sig(
627                key.get_size_tenths(),
628                key.get_bold(),
629                key.get_monospace(),
630                key.get_italic(),
631            );
632            if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len() {
633                let cached: u32 = ascii_tables[*last_ascii_table_idx].slots[code as usize];
634                if cached != u32::MAX {
635                    return Some(cached);
636                }
637            } else {
638                for table in ascii_tables.iter() {
639                    if table.style_sig == style_sig {
640                        let cached: u32 = table.slots[code as usize];
641                        if cached != u32::MAX {
642                            return Some(cached);
643                        }
644                        break;
645                    }
646                }
647            }
648        }
649        let packed_key: u64 = Self::pack_glyph_key(key);
650        Self::lookup_index(glyph_index, packed_key)
651    }
652
653    /// Performs a zero-allocation read-only lookup of a cached `RasterizedGlyph`.
654    ///
655    /// # Arguments
656    ///
657    /// - `&Self` - Glyph atlas reference.
658    /// - `GlyphKey` - Quantized glyph lookup key.
659    ///
660    /// # Returns
661    ///
662    /// - `Option<&RasterizedGlyph>` - Cached glyph bitmap when resident.
663    #[inline]
664    #[must_use]
665    pub fn lookup(&self, key: GlyphKey) -> Option<&RasterizedGlyph> {
666        let slot: u32 = self.lookup_slot(key)?;
667        self.get_glyph_by_slot(slot)
668    }
669
670    /// Performs a zero-hash, zero-allocation read-only lookup of an ASCII glyph slot in `ascii_tables[table_idx]`.
671    ///
672    /// # Arguments
673    ///
674    /// - `&Self` - Glyph atlas reference.
675    /// - `usize` - Style table index previously obtained from `ascii_table_index`.
676    /// - `u8` - ASCII byte in `0..128`.
677    ///
678    /// # Returns
679    ///
680    /// - `Option<u32>` - Cached arena slot index when resident.
681    #[inline(always)]
682    #[must_use]
683    pub fn lookup_ascii_slot(&self, table_idx: usize, byte: u8) -> Option<u32> {
684        let Self { ascii_tables, .. } = self;
685        if byte >= 128 {
686            return None;
687        }
688        let table: &AsciiGlyphStyleTable = ascii_tables.get(table_idx)?;
689        let slot: u32 = table.slots[byte as usize];
690        if slot == u32::MAX { None } else { Some(slot) }
691    }
692
693    /// Returns a bounds-checked zero-allocation reference to the cached glyph at arena `slot`.
694    ///
695    /// # Arguments
696    ///
697    /// - `&Self` - Glyph atlas reference.
698    /// - `u32` - Arena slot index returned by `lookup_slot` or `lookup_ascii_slot`.
699    ///
700    /// # Returns
701    ///
702    /// - `Option<&RasterizedGlyph>` - Cached glyph bitmap when `slot` is in bounds.
703    #[inline(always)]
704    #[must_use]
705    pub fn get_glyph_by_slot(&self, slot: u32) -> Option<&RasterizedGlyph> {
706        let Self { entries, .. } = self;
707        entries
708            .get(slot as usize)
709            .map(|entry: &(GlyphKey, RasterizedGlyph)| &entry.1)
710    }
711
712    /// Appends unique uncached `GlyphKey` entries from `keys` into caller-provided `out_missing` with zero temporary allocations.
713    ///
714    /// # Arguments
715    ///
716    /// - `&Self` - Glyph atlas reference.
717    /// - `&[GlyphKey]` - Candidate glyph keys to probe.
718    /// - `&mut Vec<GlyphKey>` - Reusable output buffer receiving deduplicated missing keys.
719    ///
720    /// # Returns
721    ///
722    /// - `usize` - Number of newly appended missing glyph keys.
723    pub fn collect_missing_keys(
724        &self,
725        keys: &[GlyphKey],
726        out_missing: &mut Vec<GlyphKey>,
727    ) -> usize {
728        let start: usize = out_missing.len();
729        for &key in keys.iter() {
730            if self.lookup_slot(key).is_none() {
731                out_missing.push(key);
732            }
733        }
734        let added_raw: usize = out_missing.len() - start;
735        if added_raw <= 1 {
736            return added_raw;
737        }
738        out_missing[start..].sort_unstable();
739        let mut write: usize = start + 1;
740        for read in (start + 1)..out_missing.len() {
741            if out_missing[read] != out_missing[write - 1] {
742                out_missing[write] = out_missing[read];
743                write += 1;
744            }
745        }
746        out_missing.truncate(write);
747        write - start
748    }
749
750    /// Batch-rasterizes all missing unique glyphs in `keys` through `provider` in a single pass and inserts them into the atlas.
751    ///
752    /// # Arguments
753    ///
754    /// - `&Self` - Mutable glyph atlas reference.
755    /// - `&[GlyphKey]` - Glyph keys needed for the current frame or text run.
756    /// - `&dyn SystemFontProvider` - Native or deterministic font provider supporting batched rasterization.
757    ///
758    /// # Returns
759    ///
760    /// - `usize` - Number of newly rasterized and inserted glyphs (`0` when all keys were already cached).
761    pub fn prewarm_batch_with(
762        &mut self,
763        keys: &[GlyphKey],
764        provider: &dyn SystemFontProvider,
765    ) -> usize {
766        let mut missing: Vec<GlyphKey> = Vec::new();
767        let missing_count: usize = self.collect_missing_keys(keys, &mut missing);
768        if missing_count == 0 {
769            return 0;
770        }
771        let mut rasterized: Vec<Option<RasterizedGlyph>> = provider.rasterize_batch(&missing);
772        let mut inserted: usize = 0;
773        for (idx, key) in missing.into_iter().enumerate() {
774            let glyph: RasterizedGlyph = rasterized
775                .get_mut(idx)
776                .and_then(Option::take)
777                .unwrap_or_else(|| rasterize_glyph(key));
778            let packed_key: u64 = Self::pack_glyph_key(key);
779            let style_sig: u32 = Self::pack_style_sig(
780                key.get_size_tenths(),
781                key.get_bold(),
782                key.get_monospace(),
783                key.get_italic(),
784            );
785            let _: u32 = self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true);
786            inserted += 1;
787        }
788        inserted
789    }
790
791    /// Prewarms all missing unique glyphs for `text` under `(physical_size, style)` in a single provider batch (`0` allocations when warm).
792    ///
793    /// # Arguments
794    ///
795    /// - `&Self` - Mutable glyph atlas reference.
796    /// - `&str` - UTF-8 text string whose missing glyphs should be rasterized together.
797    /// - `f32` - Physical font size in pixels.
798    /// - `TextStyle` - Typography style parameters.
799    /// - `&dyn SystemFontProvider` - Native or deterministic font provider.
800    ///
801    /// # Returns
802    ///
803    /// - `usize` - Number of newly rasterized and inserted glyphs.
804    pub fn prewarm_text_with(
805        &mut self,
806        text: &str,
807        physical_size: f32,
808        style: TextStyle,
809        provider: &dyn SystemFontProvider,
810    ) -> usize {
811        let mut missing: Vec<GlyphKey> = Vec::new();
812        for ch in text.chars() {
813            let key: GlyphKey = GlyphKey::from_text_style(ch, physical_size, style);
814            if self.lookup_slot(key).is_none() {
815                missing.push(key);
816            }
817        }
818        if missing.is_empty() {
819            return 0;
820        }
821        missing.sort_unstable();
822        missing.dedup();
823        let mut rasterized: Vec<Option<RasterizedGlyph>> = provider.rasterize_batch(&missing);
824        let mut inserted: usize = 0;
825        for (idx, key) in missing.into_iter().enumerate() {
826            let glyph: RasterizedGlyph = rasterized
827                .get_mut(idx)
828                .and_then(Option::take)
829                .unwrap_or_else(|| rasterize_glyph(key));
830            let packed_key: u64 = Self::pack_glyph_key(key);
831            let style_sig: u32 = Self::pack_style_sig(
832                key.get_size_tenths(),
833                key.get_bold(),
834                key.get_monospace(),
835                key.get_italic(),
836            );
837            let _: u32 = self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true);
838            inserted += 1;
839        }
840        inserted
841    }
842
843    /// Resolves an ASCII byte directly through `ascii_tables[table_idx]` with zero hash probing on hits.
844    ///
845    /// # Arguments
846    ///
847    /// - `&Self` - Mutable glyph atlas reference.
848    /// - `usize` - Style table index returned by `ascii_table_index`.
849    /// - `u8` - ASCII codepoint byte in `0..128`.
850    /// - `(u16, bool, bool, bool)` - Quantized style metadata `(size_tenths, bold, monospace, italic)`.
851    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
852    ///
853    /// # Returns
854    ///
855    /// - `u32` - Direct slot index into `entries`.
856    #[inline(always)]
857    pub(crate) fn get_or_rasterize_ascii_slot_with(
858        &mut self,
859        table_idx: usize,
860        byte: u8,
861        key_meta: (u16, bool, bool, bool),
862        provider: &dyn SystemFontProvider,
863    ) -> u32 {
864        let Self {
865            ascii_tables,
866            entry_last_used,
867            entry_fence_ids,
868            active_fence_id,
869            lru_clock,
870            cache_hits,
871            ..
872        } = self;
873        let cached: u32 = ascii_tables[table_idx].slots[byte as usize];
874        if cached != u32::MAX {
875            *cache_hits = cache_hits.wrapping_add(1);
876            *lru_clock = lru_clock.wrapping_add(1);
877            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
878                *tick = *lru_clock;
879            }
880            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
881                *fence = (*fence).max(*active_fence_id);
882            }
883            return cached;
884        }
885        let (size_tenths, bold, monospace, italic): (u16, bool, bool, bool) = key_meta;
886        let key: GlyphKey = GlyphKey {
887            codepoint: byte as char,
888            size_tenths,
889            bold,
890            monospace,
891            italic,
892        };
893        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
894        let Self { ascii_tables, .. } = self;
895        ascii_tables[table_idx].slots[byte as usize] = slot;
896        if byte.is_ascii_digit() {
897            for digit in ASCII_DIGIT_ZERO..=ASCII_DIGIT_NINE {
898                if digit == byte {
899                    continue;
900                }
901                let already_cached: bool = {
902                    let Self { ascii_tables, .. } = self;
903                    ascii_tables[table_idx].slots[digit as usize] != u32::MAX
904                };
905                if !already_cached {
906                    let d_key: GlyphKey = GlyphKey {
907                        codepoint: digit as char,
908                        size_tenths,
909                        bold,
910                        monospace,
911                        italic,
912                    };
913                    let d_slot: u32 = self.get_or_rasterize_slot_with(d_key, provider);
914                    let Self { ascii_tables, .. } = self;
915                    ascii_tables[table_idx].slots[digit as usize] = d_slot;
916                }
917            }
918        }
919        slot
920    }
921
922    /// Inserts a newly rasterized glyph into the arena, enforcing the bounded memory budget when unpinned.
923    ///
924    /// # Arguments
925    ///
926    /// - `&Self` - Mutable glyph atlas reference.
927    /// - `GlyphKey` - Quantized glyph lookup key.
928    /// - `u64` - Pre-packed 40-bit glyph key.
929    /// - `u32` - Pre-packed style signature for ASCII table updates.
930    /// - `RasterizedGlyph` - Newly rasterized coverage bitmap.
931    /// - `bool` - Whether a missing ASCII style table should be created automatically.
932    ///
933    /// # Returns
934    ///
935    /// - `u32` - Newly assigned arena slot index.
936    fn insert_rasterized_glyph(
937        &mut self,
938        key: GlyphKey,
939        packed_key: u64,
940        style_sig: u32,
941        glyph: RasterizedGlyph,
942        create_ascii_table: bool,
943    ) -> u32 {
944        let entry_sz: usize = Self::entry_bytes(&glyph);
945        let budget: usize = self.effective_budget_bytes();
946        let needs_evict: bool = {
947            let Self {
948                resident_bytes,
949                slots_pinned,
950                entries,
951                ..
952            } = self;
953            !*slots_pinned
954                && !entries.is_empty()
955                && resident_bytes.saturating_add(entry_sz) > budget
956        };
957        if needs_evict {
958            let target: usize = budget
959                .saturating_mul(3)
960                .saturating_div(4)
961                .saturating_sub(entry_sz);
962            self.evict_lru_to_target(target);
963        }
964        let code: u32 = key.get_codepoint() as u32;
965        let Self {
966            glyph_index,
967            entries,
968            entry_last_used,
969            entry_fence_ids,
970            active_fence_id,
971            ascii_tables,
972            revision,
973            resident_bytes,
974            lru_clock,
975            cache_misses,
976            ..
977        } = self;
978        if entries.is_empty() {
979            entries.reserve(GLYPH_ENTRIES_INIT_CAP);
980            entry_last_used.reserve(GLYPH_ENTRIES_INIT_CAP);
981            entry_fence_ids.reserve(GLYPH_ENTRIES_INIT_CAP);
982        }
983        *cache_misses = cache_misses.wrapping_add(1);
984        *lru_clock = lru_clock.wrapping_add(1);
985        let slot: u32 = entries.len() as u32;
986        entries.push((key, glyph));
987        entry_last_used.push(*lru_clock);
988        entry_fence_ids.push(*active_fence_id);
989        *resident_bytes = resident_bytes.saturating_add(entry_sz);
990        Self::insert_index(glyph_index, entries.len(), packed_key, slot);
991        if code < 128 {
992            let mut updated: bool = false;
993            for table in ascii_tables.iter_mut() {
994                if table.style_sig == style_sig {
995                    table.slots[code as usize] = slot;
996                    updated = true;
997                    break;
998                }
999            }
1000            if create_ascii_table && !updated {
1001                if ascii_tables.is_empty() {
1002                    ascii_tables.reserve(8);
1003                }
1004                let mut slots: [u32; 128] = [u32::MAX; 128];
1005                slots[code as usize] = slot;
1006                ascii_tables.push(AsciiGlyphStyleTable { style_sig, slots });
1007            }
1008        }
1009        *revision = revision.wrapping_add(1);
1010        slot
1011    }
1012
1013    /// Returns the arena slot index for `key`, rasterizing through `rasterize_glyph` on a miss.
1014    ///
1015    /// # Arguments
1016    ///
1017    /// - `&Self` - Mutable glyph atlas reference.
1018    /// - `GlyphKey` - Quantized glyph lookup key.
1019    ///
1020    /// # Returns
1021    ///
1022    /// - `u32` - Direct slot index into `entries`.
1023    #[inline]
1024    pub(crate) fn get_or_rasterize_slot(&mut self, key: GlyphKey) -> u32 {
1025        let code: u32 = key.get_codepoint() as u32;
1026        let style_sig: u32 = Self::pack_style_sig(
1027            key.get_size_tenths(),
1028            key.get_bold(),
1029            key.get_monospace(),
1030            key.get_italic(),
1031        );
1032        let packed_key: u64 = Self::pack_glyph_key(key);
1033        {
1034            let Self {
1035                glyph_index,
1036                entry_last_used,
1037                entry_fence_ids,
1038                active_fence_id,
1039                ascii_tables,
1040                lru_clock,
1041                cache_hits,
1042                ..
1043            } = self;
1044            if code < 128 {
1045                for table in ascii_tables.iter() {
1046                    if table.style_sig == style_sig {
1047                        let cached: u32 = table.slots[code as usize];
1048                        if cached != u32::MAX {
1049                            *cache_hits = cache_hits.wrapping_add(1);
1050                            *lru_clock = lru_clock.wrapping_add(1);
1051                            if let Some(tick) = entry_last_used.get_mut(cached as usize) {
1052                                *tick = *lru_clock;
1053                            }
1054                            if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
1055                                *fence = (*fence).max(*active_fence_id);
1056                            }
1057                            return cached;
1058                        }
1059                        break;
1060                    }
1061                }
1062            }
1063            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
1064                *cache_hits = cache_hits.wrapping_add(1);
1065                *lru_clock = lru_clock.wrapping_add(1);
1066                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
1067                    *tick = *lru_clock;
1068                }
1069                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
1070                    *fence = (*fence).max(*active_fence_id);
1071                }
1072                if code < 128 {
1073                    for table in ascii_tables.iter_mut() {
1074                        if table.style_sig == style_sig {
1075                            table.slots[code as usize] = slot;
1076                            break;
1077                        }
1078                    }
1079                }
1080                return slot;
1081            }
1082        }
1083        let glyph: RasterizedGlyph = rasterize_glyph(key);
1084        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
1085    }
1086
1087    /// Returns the arena slot index for `key`, rasterizing through `provider` on a miss.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&Self` - Mutable glyph atlas reference.
1092    /// - `GlyphKey` - Quantized glyph lookup key.
1093    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
1094    ///
1095    /// # Returns
1096    ///
1097    /// - `u32` - Direct slot index into `entries`.
1098    #[inline]
1099    pub(crate) fn get_or_rasterize_slot_with(
1100        &mut self,
1101        key: GlyphKey,
1102        provider: &dyn SystemFontProvider,
1103    ) -> u32 {
1104        let code: u32 = key.get_codepoint() as u32;
1105        let style_sig: u32 = Self::pack_style_sig(
1106            key.get_size_tenths(),
1107            key.get_bold(),
1108            key.get_monospace(),
1109            key.get_italic(),
1110        );
1111        let packed_key: u64 = Self::pack_glyph_key(key);
1112        {
1113            let Self {
1114                glyph_index,
1115                entry_last_used,
1116                entry_fence_ids,
1117                active_fence_id,
1118                ascii_tables,
1119                last_ascii_style_sig,
1120                last_ascii_table_idx,
1121                lru_clock,
1122                cache_hits,
1123                ..
1124            } = self;
1125            if code < 128 && !ascii_tables.is_empty() {
1126                if *last_ascii_style_sig == style_sig && *last_ascii_table_idx < ascii_tables.len()
1127                {
1128                    let cached: u32 = ascii_tables[*last_ascii_table_idx].slots[code as usize];
1129                    if cached != u32::MAX {
1130                        *cache_hits = cache_hits.wrapping_add(1);
1131                        *lru_clock = lru_clock.wrapping_add(1);
1132                        if let Some(tick) = entry_last_used.get_mut(cached as usize) {
1133                            *tick = *lru_clock;
1134                        }
1135                        if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
1136                            *fence = (*fence).max(*active_fence_id);
1137                        }
1138                        return cached;
1139                    }
1140                } else {
1141                    for (idx, table) in ascii_tables.iter().enumerate() {
1142                        if table.style_sig == style_sig {
1143                            *last_ascii_style_sig = style_sig;
1144                            *last_ascii_table_idx = idx;
1145                            let cached: u32 = table.slots[code as usize];
1146                            if cached != u32::MAX {
1147                                *cache_hits = cache_hits.wrapping_add(1);
1148                                *lru_clock = lru_clock.wrapping_add(1);
1149                                if let Some(tick) = entry_last_used.get_mut(cached as usize) {
1150                                    *tick = *lru_clock;
1151                                }
1152                                if let Some(fence) = entry_fence_ids.get_mut(cached as usize) {
1153                                    *fence = (*fence).max(*active_fence_id);
1154                                }
1155                                return cached;
1156                            }
1157                            break;
1158                        }
1159                    }
1160                }
1161            }
1162            if let Some(slot) = Self::lookup_index(glyph_index, packed_key) {
1163                *cache_hits = cache_hits.wrapping_add(1);
1164                *lru_clock = lru_clock.wrapping_add(1);
1165                if let Some(tick) = entry_last_used.get_mut(slot as usize) {
1166                    *tick = *lru_clock;
1167                }
1168                if let Some(fence) = entry_fence_ids.get_mut(slot as usize) {
1169                    *fence = (*fence).max(*active_fence_id);
1170                }
1171                if code < 128 {
1172                    for (idx, table) in ascii_tables.iter_mut().enumerate() {
1173                        if table.style_sig == style_sig {
1174                            table.slots[code as usize] = slot;
1175                            *last_ascii_style_sig = style_sig;
1176                            *last_ascii_table_idx = idx;
1177                            break;
1178                        }
1179                    }
1180                }
1181                return slot;
1182            }
1183        }
1184        let glyph: RasterizedGlyph = provider
1185            .rasterize(key)
1186            .unwrap_or_else(|| rasterize_glyph(key));
1187        self.insert_rasterized_glyph(key, packed_key, style_sig, glyph, true)
1188    }
1189
1190    /// Returns a read-only reference to the `RasterizedGlyph` at flat arena index `slot`.
1191    ///
1192    /// # Arguments
1193    ///
1194    /// - `&Self` - Glyph atlas reference.
1195    /// - `u32` - Valid slot index into `entries`.
1196    ///
1197    /// # Returns
1198    ///
1199    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1200    #[inline(always)]
1201    #[must_use]
1202    pub(crate) fn glyph_by_slot(&self, slot: u32) -> &RasterizedGlyph {
1203        let Self { entries, .. } = self;
1204        &entries[slot as usize].1
1205    }
1206
1207    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing and inserting it on a miss.
1208    ///
1209    /// # Arguments
1210    ///
1211    /// - `&Self` - Mutable reference to the glyph atlas.
1212    /// - `GlyphKey` - Quantized glyph lookup key.
1213    ///
1214    /// # Returns
1215    ///
1216    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1217    #[inline]
1218    pub fn get_or_rasterize(&mut self, key: GlyphKey) -> &RasterizedGlyph {
1219        let slot: u32 = self.get_or_rasterize_slot(key);
1220        self.glyph_by_slot(slot)
1221    }
1222
1223    /// Returns the total number of cached glyph entries.
1224    ///
1225    /// # Arguments
1226    ///
1227    /// - `&Self` - Glyph atlas reference.
1228    ///
1229    /// # Returns
1230    ///
1231    /// - `usize` - Number of cached glyphs.
1232    #[must_use]
1233    pub fn len(&self) -> usize {
1234        self.get_entries().len()
1235    }
1236
1237    /// Returns true when the atlas contains no cached glyphs.
1238    ///
1239    /// # Arguments
1240    ///
1241    /// - `&Self` - Glyph atlas reference.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `bool` - True if empty.
1246    #[must_use]
1247    pub fn is_empty(&self) -> bool {
1248        self.get_entries().is_empty()
1249    }
1250
1251    /// Returns the cached `RasterizedGlyph` for `key`, rasterizing through `provider` on a miss.
1252    ///
1253    /// # Arguments
1254    ///
1255    /// - `&Self` - Mutable reference to the glyph atlas.
1256    /// - `GlyphKey` - Quantized glyph lookup key.
1257    /// - `&dyn SystemFontProvider` - Native or deterministic font rasterization provider.
1258    ///
1259    /// # Returns
1260    ///
1261    /// - `&RasterizedGlyph` - Cached coverage bitmap and pixel metrics.
1262    #[inline]
1263    pub fn get_or_rasterize_with(
1264        &mut self,
1265        key: GlyphKey,
1266        provider: &dyn SystemFontProvider,
1267    ) -> &RasterizedGlyph {
1268        let slot: u32 = self.get_or_rasterize_slot_with(key, provider);
1269        self.glyph_by_slot(slot)
1270    }
1271
1272    /// Blits one glyph's 8-bit coverage bitmap into a white-RGB RGBA8 atlas slice at `(rx, ry)`.
1273    ///
1274    /// # Arguments
1275    ///
1276    /// - `&RasterizedGlyph` - Source coverage bitmap.
1277    /// - `&mut [u8]` - Destination RGBA8 atlas pixel buffer.
1278    /// - `usize` - Atlas width in pixels.
1279    /// - `u32` - Destination X pixel offset.
1280    /// - `u32` - Destination Y pixel offset.
1281    #[inline]
1282    fn blit_glyph_to_rgba(
1283        glyph: &RasterizedGlyph,
1284        pixels: &mut [u8],
1285        atlas_w: usize,
1286        rx: u32,
1287        ry: u32,
1288    ) {
1289        let gw: usize = glyph.get_width() as usize;
1290        let gh: usize = glyph.get_height() as usize;
1291        let cov: &[u8] = glyph.get_coverage().as_slice();
1292        let row_stride: usize = atlas_w * 4;
1293        let mut src_off: usize = 0;
1294        let mut dst_off: usize = ((ry as usize) * atlas_w + (rx as usize)) * 4;
1295        for _ in 0..gh {
1296            let src_row: &[u8] = &cov[src_off..src_off + gw];
1297            let dst_row: &mut [u8] = &mut pixels[dst_off..dst_off + gw * 4];
1298            let (src_quads, src_rem): (&[[u8; 4]], &[u8]) = src_row.as_chunks::<4>();
1299            let (dst_quads, dst_rem): (&mut [[u8; 16]], &mut [u8]) = dst_row.as_chunks_mut::<16>();
1300            for (a4, dst16) in src_quads.iter().zip(dst_quads.iter_mut()) {
1301                *dst16 = [
1302                    255, 255, 255, a4[0], 255, 255, 255, a4[1], 255, 255, 255, a4[2], 255, 255,
1303                    255, a4[3],
1304                ];
1305            }
1306            for (alpha, dst4) in src_rem
1307                .iter()
1308                .copied()
1309                .zip(dst_rem.as_chunks_mut::<4>().0.iter_mut())
1310            {
1311                *dst4 = [255, 255, 255, alpha];
1312            }
1313            src_off += gw;
1314            dst_off += row_stride;
1315        }
1316    }
1317
1318    /// Blits up to `(max_w, max_h)` texels of one glyph's 8-bit coverage bitmap into a white-RGB RGBA8 atlas slice at `(rx, ry)`.
1319    ///
1320    /// # Arguments
1321    ///
1322    /// - `&RasterizedGlyph` - Source coverage bitmap.
1323    /// - `&mut [u8]` - Destination RGBA8 atlas pixel buffer.
1324    /// - `usize` - Atlas width in pixels.
1325    /// - `u32` - Destination X pixel offset.
1326    /// - `u32` - Destination Y pixel offset.
1327    /// - `u32` - Maximum width in pixels to copy.
1328    /// - `u32` - Maximum height in pixels to copy.
1329    #[inline]
1330    fn blit_glyph_to_rgba_bounded(
1331        glyph: &RasterizedGlyph,
1332        pixels: &mut [u8],
1333        atlas_w: usize,
1334        rx: u32,
1335        ry: u32,
1336        max_w: u32,
1337        max_h: u32,
1338    ) {
1339        let full_w: usize = glyph.get_width() as usize;
1340        let gw: usize = full_w.min(max_w as usize);
1341        let gh: usize = (glyph.get_height() as usize).min(max_h as usize);
1342        if gw == 0 || gh == 0 {
1343            return;
1344        }
1345        let cov: &[u8] = glyph.get_coverage().as_slice();
1346        let row_stride: usize = atlas_w * 4;
1347        let mut src_off: usize = 0;
1348        let mut dst_off: usize = ((ry as usize) * atlas_w + (rx as usize)) * 4;
1349        for _ in 0..gh {
1350            let src_row: &[u8] = &cov[src_off..src_off + gw];
1351            let dst_row: &mut [u8] = &mut pixels[dst_off..dst_off + gw * 4];
1352            let (src_quads, src_rem): (&[[u8; 4]], &[u8]) = src_row.as_chunks::<4>();
1353            let (dst_quads, dst_rem): (&mut [[u8; 16]], &mut [u8]) = dst_row.as_chunks_mut::<16>();
1354            for (a4, dst16) in src_quads.iter().zip(dst_quads.iter_mut()) {
1355                *dst16 = [
1356                    255, 255, 255, a4[0], 255, 255, 255, a4[1], 255, 255, 255, a4[2], 255, 255,
1357                    255, a4[3],
1358                ];
1359            }
1360            for (alpha, dst4) in src_rem
1361                .iter()
1362                .copied()
1363                .zip(dst_rem.as_chunks_mut::<4>().0.iter_mut())
1364            {
1365                *dst4 = [255, 255, 255, alpha];
1366            }
1367            src_off += full_w;
1368            dst_off += row_stride;
1369        }
1370    }
1371
1372    /// Shelf-packs all cached glyphs into a single GPU-uploadable RGBA8 texture atlas using up to `GLYPH_ATLAS_DEFAULT_PAGE_DIM` width.
1373    ///
1374    /// # Arguments
1375    ///
1376    /// - `&Self` - Glyph atlas reference.
1377    ///
1378    /// # Returns
1379    ///
1380    /// - `PackedGlyphAtlas` - Packed RGBA8 texture, per-glyph UV rects, and revision tag.
1381    #[must_use]
1382    pub fn pack_rgba_atlas(&self) -> PackedGlyphAtlas {
1383        let entries: &[(GlyphKey, RasterizedGlyph)] = self.get_entries().as_slice();
1384        let glyph_count: usize = entries.len();
1385        let mut total_row_w: u32 = 1;
1386        let mut max_glyph_w: u32 = 0;
1387        for (_, glyph) in entries.iter() {
1388            let gw: u32 = glyph.get_width();
1389            total_row_w = total_row_w.saturating_add(gw.saturating_add(1));
1390            if gw > max_glyph_w {
1391                max_glyph_w = gw;
1392            }
1393        }
1394        let min_needed_w: u32 = max_glyph_w.saturating_add(2).max(ATLAS_MIN_DIM);
1395        let preferred_w: u32 = if glyph_count > 320 || total_row_w > ATLAS_DEFAULT_WIDTH * 16 {
1396            GLYPH_ATLAS_DEFAULT_PAGE_DIM.max(min_needed_w.next_power_of_two())
1397        } else if glyph_count > 160 || total_row_w > ATLAS_DEFAULT_WIDTH * 8 {
1398            (ATLAS_DEFAULT_WIDTH * 2).max(min_needed_w.next_power_of_two())
1399        } else {
1400            ATLAS_DEFAULT_WIDTH.max(min_needed_w.next_power_of_two())
1401        };
1402        let atlas_w: u32 = if total_row_w <= ATLAS_DEFAULT_WIDTH {
1403            total_row_w
1404                .max(ATLAS_MIN_DIM)
1405                .next_power_of_two()
1406                .min(ATLAS_DEFAULT_WIDTH)
1407        } else {
1408            preferred_w
1409        };
1410        let mut cursor_x: u32 = 1;
1411        let mut cursor_y: u32 = 1;
1412        let mut shelf_h: u32 = 0;
1413        let mut regions: HashMap<GlyphKey, (u32, u32, u32, u32)> =
1414            HashMap::with_capacity(glyph_count);
1415        let use_stack: bool = glyph_count <= ATLAS_STACK_PLACEMENTS;
1416        let mut stack_placements: [(usize, u32, u32); ATLAS_STACK_PLACEMENTS] =
1417            [(0, 0, 0); ATLAS_STACK_PLACEMENTS];
1418        let mut heap_placements: Vec<(usize, u32, u32)> = if use_stack {
1419            Vec::new()
1420        } else {
1421            Vec::with_capacity(glyph_count)
1422        };
1423        for (idx, (key, glyph)) in entries.iter().enumerate() {
1424            let gw: u32 = glyph.get_width();
1425            let gh: u32 = glyph.get_height();
1426            if cursor_x + gw + 1 > atlas_w {
1427                cursor_x = 1;
1428                cursor_y += shelf_h + 1;
1429                shelf_h = 0;
1430            }
1431            let _: Option<(u32, u32, u32, u32)> =
1432                regions.insert(*key, (cursor_x, cursor_y, gw, gh));
1433            if use_stack {
1434                stack_placements[idx] = (idx, cursor_x, cursor_y);
1435            } else {
1436                heap_placements.push((idx, cursor_x, cursor_y));
1437            }
1438            cursor_x += gw + 1;
1439            shelf_h = shelf_h.max(gh);
1440        }
1441        let atlas_h: u32 = (cursor_y + shelf_h + 1).max(ATLAS_MIN_DIM);
1442        let atlas_w_usize: usize = atlas_w as usize;
1443        let mut pixels: Vec<u8> = vec![0; atlas_w_usize * (atlas_h as usize) * 4];
1444        let placements: &[(usize, u32, u32)] = if use_stack {
1445            &stack_placements[..glyph_count]
1446        } else {
1447            heap_placements.as_slice()
1448        };
1449        for &(entry_idx, rx, ry) in placements.iter() {
1450            Self::blit_glyph_to_rgba(&entries[entry_idx].1, &mut pixels, atlas_w_usize, rx, ry);
1451        }
1452        PackedGlyphAtlas::new(atlas_w, atlas_h, pixels, regions, self.get_revision())
1453    }
1454
1455    /// Shelf-packs cached glyphs into a multi-page RGBA8 atlas where every page obeys `<= min(max_texture_dim, 2048)` per axis and LRU page eviction bounds total page count to `max_pages`.
1456    ///
1457    /// # Arguments
1458    ///
1459    /// - `&Self` - Glyph atlas reference.
1460    /// - `u32` - Hardware GPU maximum texture dimension in pixels.
1461    /// - `usize` - Maximum resident page count (`0` uses `GLYPH_ATLAS_DEFAULT_MAX_PAGES`).
1462    ///
1463    /// # Returns
1464    ///
1465    /// - `PackedMultiPageGlyphAtlas` - Bounded multi-page RGBA8 glyph atlas with per-glyph page placements and LRU eviction count.
1466    #[must_use]
1467    pub fn pack_multipage_rgba_atlas(
1468        &self,
1469        max_texture_dim: u32,
1470        max_pages: usize,
1471    ) -> PackedMultiPageGlyphAtlas {
1472        let page_limit: u32 =
1473            max_texture_dim.clamp(GLYPH_ATLAS_MIN_PAGE_DIM, GLYPH_ATLAS_DEFAULT_PAGE_DIM);
1474        let effective_max_pages: usize = if max_pages == 0 {
1475            GLYPH_ATLAS_DEFAULT_MAX_PAGES
1476        } else {
1477            max_pages
1478        };
1479        let entries: &[(GlyphKey, RasterizedGlyph)] = self.get_entries().as_slice();
1480        let Self {
1481            entry_last_used, ..
1482        } = self;
1483        if entries.is_empty() {
1484            return PackedMultiPageGlyphAtlas::new(
1485                page_limit,
1486                Vec::new(),
1487                HashMap::new(),
1488                self.get_revision(),
1489                0,
1490            );
1491        }
1492        let max_cell_dim: u32 = page_limit.saturating_sub(2).max(1);
1493        let mut order: Vec<usize> = (0..entries.len()).collect();
1494        order.sort_unstable_by(|lhs: &usize, rhs: &usize| {
1495            let lhs_tick: u64 = entry_last_used.get(*lhs).copied().unwrap_or(0);
1496            let rhs_tick: u64 = entry_last_used.get(*rhs).copied().unwrap_or(0);
1497            rhs_tick
1498                .cmp(&lhs_tick)
1499                .then_with(|| {
1500                    entries[*rhs]
1501                        .1
1502                        .get_height()
1503                        .cmp(&entries[*lhs].1.get_height())
1504                })
1505                .then_with(|| entries[*lhs].0.cmp(&entries[*rhs].0))
1506        });
1507        let mut raw_pages: Vec<RawGlyphPageBucket> = Vec::new();
1508        let mut cur_x: u32 = 1;
1509        let mut cur_y: u32 = 1;
1510        let mut shelf_h: u32 = 0;
1511        let mut page_used_w: u32 = ATLAS_MIN_DIM;
1512        let mut page_max_tick: u64 = 0;
1513        let mut page_items: Vec<RawGlyphPageItem> = Vec::new();
1514        for entry_idx in order.into_iter() {
1515            let glyph: &RasterizedGlyph = &entries[entry_idx].1;
1516            let gw: u32 = glyph.get_width().min(max_cell_dim);
1517            let gh: u32 = glyph.get_height().min(max_cell_dim);
1518            let tick: u64 = entry_last_used.get(entry_idx).copied().unwrap_or(0);
1519            if cur_x > 1 && cur_x.saturating_add(gw).saturating_add(1) > page_limit {
1520                cur_x = 1;
1521                cur_y = cur_y.saturating_add(shelf_h).saturating_add(1);
1522                shelf_h = 0;
1523            }
1524            if !page_items.is_empty() && cur_y.saturating_add(gh).saturating_add(1) > page_limit {
1525                let final_w: u32 = page_used_w
1526                    .max(ATLAS_MIN_DIM)
1527                    .next_power_of_two()
1528                    .min(page_limit);
1529                let final_h: u32 = cur_y
1530                    .saturating_add(shelf_h)
1531                    .saturating_add(1)
1532                    .clamp(ATLAS_MIN_DIM, page_limit);
1533                raw_pages.push(RawGlyphPageBucket {
1534                    width: final_w,
1535                    height: final_h,
1536                    last_used_tick: page_max_tick,
1537                    items: take(&mut page_items),
1538                });
1539                cur_x = 1;
1540                cur_y = 1;
1541                shelf_h = 0;
1542                page_used_w = ATLAS_MIN_DIM;
1543                page_max_tick = 0;
1544            }
1545            page_items.push(RawGlyphPageItem {
1546                entry_idx,
1547                x: cur_x,
1548                y: cur_y,
1549                width: gw,
1550                height: gh,
1551            });
1552            cur_x = cur_x.saturating_add(gw).saturating_add(1);
1553            page_used_w = page_used_w.max(cur_x);
1554            shelf_h = shelf_h.max(gh);
1555            page_max_tick = page_max_tick.max(tick);
1556        }
1557        if !page_items.is_empty() {
1558            let final_w: u32 = page_used_w
1559                .max(ATLAS_MIN_DIM)
1560                .next_power_of_two()
1561                .min(page_limit);
1562            let final_h: u32 = cur_y
1563                .saturating_add(shelf_h)
1564                .saturating_add(1)
1565                .clamp(ATLAS_MIN_DIM, page_limit);
1566            raw_pages.push(RawGlyphPageBucket {
1567                width: final_w,
1568                height: final_h,
1569                last_used_tick: page_max_tick,
1570                items: page_items,
1571            });
1572        }
1573        let mut evicted_pages: u64 = 0;
1574        if raw_pages.len() > effective_max_pages {
1575            let mut page_order: Vec<usize> = (0..raw_pages.len()).collect();
1576            page_order.sort_unstable_by(|lhs: &usize, rhs: &usize| {
1577                raw_pages[*rhs]
1578                    .last_used_tick
1579                    .cmp(&raw_pages[*lhs].last_used_tick)
1580                    .then_with(|| lhs.cmp(rhs))
1581            });
1582            page_order.truncate(effective_max_pages);
1583            page_order.sort_unstable();
1584            let mut keep_flags: Vec<bool> = vec![false; raw_pages.len()];
1585            for keep_idx in page_order.into_iter() {
1586                keep_flags[keep_idx] = true;
1587            }
1588            evicted_pages = (raw_pages.len() - effective_max_pages) as u64;
1589            let mut kept_raw: Vec<RawGlyphPageBucket> = Vec::with_capacity(effective_max_pages);
1590            for (idx, page) in raw_pages.into_iter().enumerate() {
1591                if keep_flags[idx] {
1592                    kept_raw.push(page);
1593                }
1594            }
1595            raw_pages = kept_raw;
1596        }
1597        let mut pages: Vec<GlyphAtlasPage> = Vec::with_capacity(raw_pages.len());
1598        let mut placements: HashMap<GlyphKey, GlyphPagePlacement> =
1599            HashMap::with_capacity(entries.len());
1600        for (page_idx_usize, page_bucket) in raw_pages.into_iter().enumerate() {
1601            let page_idx: u32 = page_idx_usize as u32;
1602            let page_w: u32 = page_bucket.width;
1603            let page_h: u32 = page_bucket.height;
1604            let page_w_usize: usize = page_w as usize;
1605            let mut pixels: Vec<u8> = vec![0; page_w_usize * (page_h as usize) * 4];
1606            let glyph_count: usize = page_bucket.items.len();
1607            for item in page_bucket.items.into_iter() {
1608                let key: GlyphKey = entries[item.entry_idx].0;
1609                let glyph: &RasterizedGlyph = &entries[item.entry_idx].1;
1610                Self::blit_glyph_to_rgba_bounded(
1611                    glyph,
1612                    &mut pixels,
1613                    page_w_usize,
1614                    item.x,
1615                    item.y,
1616                    item.width,
1617                    item.height,
1618                );
1619                let _: Option<GlyphPagePlacement> = placements.insert(
1620                    key,
1621                    GlyphPagePlacement::new(page_idx, item.x, item.y, item.width, item.height),
1622                );
1623            }
1624            pages.push(GlyphAtlasPage::new(
1625                page_idx,
1626                page_w,
1627                page_h,
1628                pixels,
1629                glyph_count,
1630                page_bucket.last_used_tick,
1631            ));
1632        }
1633        PackedMultiPageGlyphAtlas::new(
1634            page_limit,
1635            pages,
1636            placements,
1637            self.get_revision(),
1638            evicted_pages,
1639        )
1640    }
1641
1642    /// Clears all cached glyphs and increments the atlas revision.
1643    ///
1644    /// # Arguments
1645    ///
1646    /// - `&Self` - Mutable reference to the glyph atlas.
1647    pub fn clear(&mut self) {
1648        let Self {
1649            recent_dpi_slots, ..
1650        } = self;
1651        recent_dpi_slots.clear();
1652        self.clear_with_fence_deferral();
1653    }
1654}