Skip to main content

sim_engine/text/font/
mod.rs

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