Skip to main content

sim_engine/text/
font.rs

1//! Single-font horizontal shaping and bounded grayscale outline rasterization.
2
3use ab_glyph::Font;
4
5mod config;
6mod raster;
7mod session;
8#[cfg(test)]
9mod session_tests;
10#[cfg(test)]
11mod tests;
12pub use config::{
13    FontBudget, FontBudgetResource, FontError, TextDirection, TextLayoutBudget, TextStyle,
14};
15use config::{check, reserve};
16pub use raster::RasterizedGlyph;
17pub use session::{ShapedLineError, TextShapingSession};
18
19/// One owned TTF/OpenType outline face (collection index zero).
20///
21/// Source bytes are retained once inside ab_glyph; rustybuzz borrows those bytes
22/// while shaping. The source Vec capacity is checked before parsing. Font
23/// discovery, fallback selection, variable-font axes, color/bitmap glyphs,
24/// wrapping and bidi paragraph layout are outside this API.
25/// Cloning shares the original bytes and parsed font without copying them.
26#[derive(Debug, Clone)]
27pub struct FontFace {
28    font: std::sync::Arc<ab_glyph::FontVec>,
29    source_capacity: usize,
30    glyph_count: usize,
31}
32
33impl FontFace {
34    /// Loads already-read TTF/OTF bytes without duplicating their backing storage.
35    /// The caller owns filesystem/network I/O and font licensing.
36    pub fn from_bytes(bytes: Vec<u8>, budget: FontBudget) -> Result<Self, FontError> {
37        check(
38            FontBudgetResource::FontBytes,
39            bytes.capacity(),
40            budget.max_font_bytes(),
41        )?;
42        let face =
43            rustybuzz::ttf_parser::Face::parse(&bytes, 0).map_err(|_| FontError::InvalidFont)?;
44        let tables = face.tables();
45        if tables.glyf.is_none() && tables.cff.is_none() && tables.cff2.is_none() {
46            return Err(FontError::InvalidFont);
47        }
48        let glyph_count = usize::from(face.number_of_glyphs());
49        check(
50            FontBudgetResource::FontGlyphs,
51            glyph_count,
52            budget.max_font_glyphs(),
53        )?;
54        if face.units_per_em() == 0 || face.ascender() <= face.descender() {
55            return Err(FontError::InvalidFont);
56        }
57        let source_capacity = bytes.capacity();
58        let font = ab_glyph::FontVec::try_from_vec(bytes).map_err(|_| FontError::InvalidFont)?;
59        Ok(Self {
60            font: std::sync::Arc::new(font),
61            source_capacity,
62            glyph_count,
63        })
64    }
65
66    /// Original font bytes, borrowed without an additional owned copy.
67    pub fn font_data(&self) -> &[u8] {
68        self.font.as_slice()
69    }
70    /// Source Vec capacity referenced by this handle; clones share it.
71    /// Dependency-parsed metadata is excluded.
72    pub const fn allocation_bytes(&self) -> usize {
73        self.source_capacity
74    }
75    /// Number of font-local glyph identifiers, including the missing-glyph entry.
76    pub const fn glyph_count(&self) -> usize {
77        self.glyph_count
78    }
79
80    /// Shapes a horizontal single-script directional run at baseline `(0, 0)`.
81    ///
82    /// Positions/advances use logical pixels, with positive y downward. Kerning,
83    /// ligatures and combining-mark offsets come from rustybuzz/OpenType tables.
84    /// Auto infers one direction/script, not a mixed-direction bidi paragraph.
85    /// Newlines, controls and missing glyphs return errors; spaces retain advance.
86    /// DPI changes raster resolution, not logical layout or kerning decisions.
87    pub fn shape_line(
88        &self,
89        text: &str,
90        style: &TextStyle,
91        budget: &TextLayoutBudget,
92    ) -> Result<ShapedLine, FontError> {
93        TextShapingSession::new(self, *style, *budget)?.shape_line(text)
94    }
95
96    /// Rasterizes one glyph at physical em size and baseline `(0, 0)`.
97    /// Outlines are preflighted without allocating curves; pixel bounds and
98    /// command counts are checked before bounded curve and coverage allocations.
99    /// No hinting or subpixel-position variants are applied. Empty outlines
100    /// (for example spaces) return an empty bitmap, not a missing-glyph error.
101    pub fn rasterize_glyph(
102        &self,
103        glyph_id: u16,
104        style: &TextStyle,
105        budget: &TextLayoutBudget,
106    ) -> Result<RasterizedGlyph, FontError> {
107        raster::rasterize(self, glyph_id, style, budget)
108    }
109}
110
111/// A shaped glyph's font-local identity and baseline-relative logical placement.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct ShapedGlyph {
114    glyph_id: u16,
115    logical_x: f32,
116    logical_y: f32,
117    cluster: usize,
118}
119
120impl ShapedGlyph {
121    /// Identifier in the FontFace that produced this line.
122    pub const fn glyph_id(self) -> u16 {
123        self.glyph_id
124    }
125    /// Baseline-relative horizontal origin, in logical pixels.
126    pub const fn logical_x(self) -> f32 {
127        self.logical_x
128    }
129    /// Baseline-relative vertical origin, in logical pixels, positive downward.
130    pub const fn logical_y(self) -> f32 {
131        self.logical_y
132    }
133    /// Original UTF-8 byte offset associated with this shaped cluster.
134    pub const fn cluster(self) -> usize {
135        self.cluster
136    }
137}
138
139/// Immutable shaped placement; rasterization and GPU ownership are separate.
140#[derive(Debug)]
141pub struct ShapedLine {
142    font: FontFace,
143    style: TextStyle,
144    text: String,
145    glyphs: Vec<ShapedGlyph>,
146    advance: f32,
147    ascent: f32,
148    descent: f32,
149    line_height: f32,
150}
151
152impl ShapedLine {
153    /// Original UTF-8 input; retained so prepared text needs no second shaping pass.
154    pub fn text(&self) -> &str {
155        &self.text
156    }
157    /// Immutable font shared with the original face, not a duplicate byte buffer.
158    pub const fn font(&self) -> &FontFace {
159        &self.font
160    }
161    /// Exact em size, DPI and requested direction used for this line.
162    pub const fn style(&self) -> &TextStyle {
163        &self.style
164    }
165    /// Checks font identity, exact style and input/output limits without reshaping.
166    /// Clones of a face share identity; separately loaded identical bytes do not.
167    /// Raster limits apply later when an atlas encounters an uncached glyph.
168    pub fn validate_for(
169        &self,
170        font: &FontFace,
171        style: &TextStyle,
172        budget: &TextLayoutBudget,
173    ) -> Result<(), ShapedLineError> {
174        self.validate_provenance(font, style)?;
175        check(
176            FontBudgetResource::TextBytes,
177            self.text.len(),
178            budget.max_text_bytes(),
179        )?;
180        check(
181            FontBudgetResource::ShapedGlyphs,
182            self.glyphs.len(),
183            budget.max_shaped_glyphs(),
184        )?;
185        Ok(())
186    }
187
188    pub(crate) fn validate_provenance(
189        &self,
190        font: &FontFace,
191        style: &TextStyle,
192    ) -> Result<(), ShapedLineError> {
193        if !std::sync::Arc::ptr_eq(&self.font.font, &font.font) {
194            return Err(ShapedLineError::FontMismatch);
195        }
196        if self.style != *style {
197            return Err(ShapedLineError::StyleMismatch);
198        }
199        Ok(())
200    }
201    /// Shaper output order. Drawing this sequence at its offsets preserves marks.
202    pub fn glyphs(&self) -> &[ShapedGlyph] {
203        &self.glyphs
204    }
205    /// Horizontal pen advance in logical pixels, including whitespace.
206    pub const fn advance(&self) -> f32 {
207        self.advance
208    }
209    /// Signed font ascender in logical pixels; normally positive above baseline.
210    pub const fn ascent(&self) -> f32 {
211        self.ascent
212    }
213    /// Signed font descender in logical pixels; normally negative below baseline.
214    pub const fn descent(&self) -> f32 {
215        self.descent
216    }
217    /// Font-recommended line spacing in logical pixels, including line gap.
218    pub const fn line_height(&self) -> f32 {
219        self.line_height
220    }
221    /// Owned UTF-8 and glyph metadata capacity in bytes, excluding the shared font.
222    pub fn allocation_bytes(&self) -> usize {
223        self.glyphs
224            .capacity()
225            .saturating_mul(std::mem::size_of::<ShapedGlyph>())
226            .saturating_add(self.text.capacity())
227    }
228}
229
230fn represent(value: f64) -> Result<f32, FontError> {
231    let result = value as f32;
232    if result.is_finite() {
233        Ok(result)
234    } else {
235        Err(FontError::InvalidGeometry)
236    }
237}