Skip to main content

sim_engine/renderer/text/
types.rs

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