Skip to main content

sim_engine/renderer/text/
types.rs

1use super::*;
2
3/// Fixed atlas texel/cache capacity and per-run limits for optional font rendering.
4///
5/// The default is a 1024x1024 RGBA atlas (4 MiB CPU plus 4 MiB GPU), at most
6/// 4096 cached glyphs and the default [`GlyphRunBudget`]. Glyph cache metadata is
7/// reserved once and grows neither beyond its count limit nor through eviction.
8/// Shared font bytes, shaping/rasterizer scratch and host-owned runs are separate.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct TextAtlasBudget {
11    width: u32,
12    height: u32,
13    max_cached_glyphs: usize,
14    run: GlyphRunBudget,
15}
16
17impl TextAtlasBudget {
18    /// Creates fixed physical-texel dimensions and a glyph count in `1..=65535`.
19    /// Dimensions are additionally checked against the actual GPU at atlas creation.
20    pub fn new(
21        width: u32,
22        height: u32,
23        max_cached_glyphs: usize,
24        run: GlyphRunBudget,
25    ) -> Result<Self, TextError> {
26        if width < 5 || height < 5 || !(1..=65535).contains(&max_cached_glyphs) {
27            return Err(TextError::InvalidBudget);
28        }
29        let budget = Self {
30            width,
31            height,
32            max_cached_glyphs,
33            run,
34        };
35        budget.image_budget()?;
36        Ok(budget)
37    }
38    /// Returns fixed atlas width in physical texels.
39    pub const fn width(self) -> u32 {
40        self.width
41    }
42    /// Returns fixed atlas height in physical texels.
43    pub const fn height(self) -> u32 {
44        self.height
45    }
46    /// Returns maximum cached glyphs, including spacing glyphs.
47    pub const fn max_cached_glyphs(self) -> usize {
48        self.max_cached_glyphs
49    }
50    /// Returns limits applied to each created retained glyph run.
51    pub const fn run_budget(self) -> GlyphRunBudget {
52        self.run
53    }
54
55    pub(super) fn image_budget(self) -> Result<ImageBudget, TextError> {
56        let bytes = (self.width as usize)
57            .checked_mul(self.height as usize)
58            .and_then(|area| area.checked_mul(4))
59            .ok_or(TextError::InvalidBudget)?;
60        Ok(ImageBudget::new(self.width, self.height, bytes)?)
61    }
62}
63
64impl Default for TextAtlasBudget {
65    fn default() -> Self {
66        Self {
67            width: 1024,
68            height: 1024,
69            max_cached_glyphs: 4096,
70            run: GlyphRunBudget::default(),
71        }
72    }
73}
74
75/// A rejected text asset, layout, cache operation or GPU resource operation.
76#[derive(Debug)]
77pub enum TextError {
78    /// Font parsing, shaping or rasterization failed its validation or work limits.
79    Font(FontError),
80    /// The underlying glyph/image allocation or identity contract was violated.
81    Glyph(GlyphError),
82    /// Atlas dimensions/counts or their checked byte calculation are invalid.
83    InvalidBudget,
84    /// The fixed shelf-packed atlas cannot fit a new padded glyph.
85    AtlasFull,
86    /// The fixed number of cached glyph identities has been reached.
87    GlyphCacheFull,
88    /// A run belongs to another font atlas, even if both use the same font bytes.
89    AtlasMismatch,
90    /// Bitmap bearings or positioned glyph coordinates cannot form a finite logical quad.
91    InvalidPlacement,
92    /// An engine-owned CPU allocation could not be reserved.
93    AllocationFailed,
94}
95
96impl fmt::Display for TextError {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            Self::Font(error) => write!(formatter, "text font: {error}"),
100            Self::Glyph(error) => write!(formatter, "text glyph resource: {error}"),
101            Self::InvalidBudget => formatter.write_str("invalid text atlas budget"),
102            Self::AtlasFull => formatter.write_str("fixed text atlas is full"),
103            Self::GlyphCacheFull => formatter.write_str("text glyph cache count limit reached"),
104            Self::AtlasMismatch => formatter.write_str("text run belongs to another atlas"),
105            Self::InvalidPlacement => {
106                formatter.write_str("text placement is not finite or representable")
107            }
108            Self::AllocationFailed => formatter.write_str("text storage allocation failed"),
109        }
110    }
111}
112impl Error for TextError {
113    fn source(&self) -> Option<&(dyn Error + 'static)> {
114        match self {
115            Self::Font(error) => Some(error),
116            Self::Glyph(error) => Some(error),
117            _ => None,
118        }
119    }
120}
121impl From<FontError> for TextError {
122    fn from(error: FontError) -> Self {
123        Self::Font(error)
124    }
125}
126impl From<GlyphError> for TextError {
127    fn from(error: GlyphError) -> Self {
128        Self::Glyph(error)
129    }
130}
131impl From<ImageError> for TextError {
132    fn from(error: ImageError) -> Self {
133        Self::Glyph(error.into())
134    }
135}
136
137/// Successful update diagnostics. Unchanged text reports zero work.
138#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
139pub struct TextUpdateReport {
140    changed: bool,
141    instance_uploaded_bytes: usize,
142    cached_glyphs_added: usize,
143}
144impl TextUpdateReport {
145    pub(super) const fn new(instance_uploaded_bytes: usize, cached_glyphs_added: usize) -> Self {
146        Self {
147            changed: true,
148            instance_uploaded_bytes,
149            cached_glyphs_added,
150        }
151    }
152    /// Returns whether the retained UTF-8 text changed.
153    pub const fn changed(self) -> bool {
154        self.changed
155    }
156    /// Returns glyph instance upload bytes, excluding cache-miss atlas pixel uploads.
157    pub const fn instance_uploaded_bytes(self) -> usize {
158        self.instance_uploaded_bytes
159    }
160    /// Returns newly cached glyph count, including spacing glyphs.
161    pub const fn cached_glyphs_added(self) -> usize {
162        self.cached_glyphs_added
163    }
164}