ferravex_render/
font.rs

1//! Allocation-free measurements for the immediate renderer's 5×7 bitmap font.
2//!
3//! Obtain checked metrics with [`crate::Font::try_metrics`]. Measurements use
4//! local, Y-down coordinates before camera transforms, clipping or UI shadows.
5//! ASCII lowercase letters use uppercase glyphs; other unsupported characters
6//! are blank but still advance, exactly as in [`crate::draw_text_ex`]. The
7//! separate UI renderer's `?` substitution and word wrapping are not applied.
8
9use crate::Rect;
10
11/// A font size, scale or resulting coordinate cannot be measured safely.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum FontMeasureError {
14    /// Font size must be nonzero.
15    ZeroSize,
16    /// Scale must be finite and strictly positive.
17    InvalidScale,
18    /// Scaling or layout overflowed, underflowed to zero, or lost enough `f32`
19    /// precision that an advance or an outer visible pixel edge no longer moves.
20    Unrepresentable,
21}
22
23impl std::fmt::Display for FontMeasureError {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        f.write_str(match self {
26            Self::ZeroSize => "bitmap font size must be nonzero",
27            Self::InvalidScale => "bitmap font scale must be finite and positive",
28            Self::Unrepresentable => "bitmap text geometry is not representable in f32",
29        })
30    }
31}
32
33impl std::error::Error for FontMeasureError {}
34
35/// Validated, reusable font geometry. No atlas, text buffer or allocation is needed.
36///
37/// ```
38/// let font = ferravex_render::get_default_font();
39/// let metrics = font.try_metrics(16, 0.5)?;
40/// assert_eq!(metrics.pixel_size(), 1.0);
41/// assert_eq!(metrics.glyph_advance(), 6.0);
42/// assert_eq!(metrics.baseline(), 7.0);
43/// assert_eq!(metrics.line_height(), 8.0);
44/// # Ok::<(), Box<dyn std::error::Error>>(())
45/// ```
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct BitmapFontMetrics {
48    pixel_size: f32,
49}
50
51/// Logical size and tight visible bounds of a measured label.
52///
53/// ```
54/// let metrics = ferravex_render::get_default_font().try_metrics(8, 1.0)?;
55/// let text = metrics.measure_line("A ")?;
56/// assert_eq!((text.width, text.height, text.line_count), (12.0, 7.0, 1));
57/// assert_eq!(text.ink_bounds, Some(ferravex_render::Rect::new(0.0, 0.0, 5.0, 7.0)));
58/// # Ok::<(), Box<dyn std::error::Error>>(())
59/// ```
60#[derive(Clone, Copy, Debug, Default, PartialEq)]
61pub struct BitmapTextMetrics {
62    /// Maximum line advance, including the final one-pixel gap and blank cells.
63    /// Advances accumulate in the same order as `draw_text_ex` at local X = 0.
64    pub width: f32,
65    /// Distance from the first line's top to the last line's baseline.
66    /// Empty input has zero height; explicit blank lines reserve their height.
67    pub height: f32,
68    /// Number of logical lines, including trailing blank lines. Empty input is zero.
69    pub line_count: usize,
70    /// Number of unsupported Unicode scalar values, excluding ordinary spaces
71    /// and the line separators recognized by `measure_multiline`.
72    pub unsupported_glyphs: usize,
73    /// Tight union of the glyph rectangles relative to the first line's top-left.
74    /// `None` means no visible glyph pixels, even when logical size is nonzero.
75    pub ink_bounds: Option<Rect>,
76}
77
78impl crate::Font {
79    /// Validates the size and scale used by [`crate::draw_text_ex`].
80    ///
81    /// Pixel size is `size as f32 * scale / 8.0`, preserving the renderer's
82    /// operation order. Zero size, nonpositive/nonfinite scale and unrepresentable
83    /// geometry return an error. Text extent is checked separately on measurement.
84    ///
85    /// ```
86    /// let font = ferravex_render::get_default_font();
87    /// assert!(font.try_metrics(0, 1.0).is_err());
88    /// assert!(font.try_metrics(16, f32::NAN).is_err());
89    /// let metrics = font.try_metrics(16, 1.5)?;
90    /// assert_eq!(metrics.measure_line("Score")?.width, 90.0);
91    /// # Ok::<(), Box<dyn std::error::Error>>(())
92    /// ```
93    pub fn try_metrics(
94        &self,
95        size: u16,
96        scale: f32,
97    ) -> Result<BitmapFontMetrics, FontMeasureError> {
98        if size == 0 {
99            return Err(FontMeasureError::ZeroSize);
100        }
101        if !scale.is_finite() || scale <= 0.0 {
102            return Err(FontMeasureError::InvalidScale);
103        }
104        let pixel_size = size as f32 * scale / 8.0;
105        if !pixel_size.is_finite() || pixel_size <= 0.0 || !(8.0 * pixel_size).is_finite() {
106            return Err(FontMeasureError::Unrepresentable);
107        }
108        Ok(BitmapFontMetrics { pixel_size })
109    }
110}
111
112impl BitmapFontMetrics {
113    /// Side length of one bitmap pixel in logical drawing coordinates.
114    pub fn pixel_size(self) -> f32 {
115        self.pixel_size
116    }
117
118    /// Horizontal advance per Unicode scalar: five columns plus one spacing column.
119    pub fn glyph_advance(self) -> f32 {
120        6.0 * self.pixel_size
121    }
122
123    /// Baseline offset from a line's top: seven pixel rows, with no descenders.
124    /// Pass `top + baseline()` as the Y argument to `draw_text_ex`.
125    pub fn baseline(self) -> f32 {
126        7.0 * self.pixel_size
127    }
128
129    /// Baseline-to-baseline distance: seven pixel rows plus one spacing row.
130    pub fn line_height(self) -> f32 {
131        8.0 * self.pixel_size
132    }
133
134    /// Measures one immediate-renderer line without allocation.
135    ///
136    /// Every scalar advances, including unsupported controls such as LF, CR and
137    /// tab. There is no Unicode case expansion, shaping or fallback substitution.
138    /// Empty input has no lines, size or ink; spaces reserve size but have no ink.
139    /// Returns an error if the resulting geometry is unrepresentable.
140    ///
141    /// ```
142    /// let metrics = ferravex_render::get_default_font().try_metrics(8, 1.0)?;
143    /// let text = metrics.measure_line("a☃ ")?;
144    /// assert_eq!(text.width, 18.0);
145    /// assert_eq!(text.unsupported_glyphs, 1);
146    /// assert_eq!(text.ink_bounds.unwrap().w, 5.0);
147    /// # Ok::<(), Box<dyn std::error::Error>>(())
148    /// ```
149    pub fn measure_line(self, text: &str) -> Result<BitmapTextMetrics, FontMeasureError> {
150        self.measure(text, false)
151    }
152
153    /// Measures explicit LF/CRLF-separated lines without allocation or wrapping.
154    ///
155    /// Lines share a left edge and advance by `line_height()`. Blank and trailing
156    /// lines reserve vertical space; bare CR remains an unsupported blank cell.
157    /// `draw_text_ex` itself does **not** split lines: draw each line separately
158    /// with successive baselines, removing CR from CRLF separators first.
159    /// Returns an error if the resulting geometry is unrepresentable.
160    ///
161    /// ```
162    /// use ferravex_render::{TextParams, WHITE, draw_text_ex, get_default_font};
163    /// let metrics = get_default_font().try_metrics(16, 1.0)?;
164    /// let label = "LEVEL 1\nREADY";
165    /// let measured = metrics.measure_multiline(label)?;
166    /// assert_eq!((measured.width, measured.height), (84.0, 30.0));
167    /// let mut baseline = 20.0 + metrics.baseline();
168    /// for line in label.split('\n') {
169    ///     draw_text_ex(line, 10.0, baseline, TextParams {
170    ///         font_size: 16, font_scale: 1.0, color: WHITE,
171    ///     });
172    ///     baseline += metrics.line_height();
173    /// }
174    /// # Ok::<(), Box<dyn std::error::Error>>(())
175    /// ```
176    pub fn measure_multiline(self, text: &str) -> Result<BitmapTextMetrics, FontMeasureError> {
177        self.measure(text, true)
178    }
179
180    fn measure(self, text: &str, multiline: bool) -> Result<BitmapTextMetrics, FontMeasureError> {
181        let mut result = BitmapTextMetrics::default();
182        if text.is_empty() {
183            return Ok(result);
184        }
185        let mut x = 0.0;
186        let mut baseline = self.baseline();
187        result.line_count = 1;
188        // Keep extrema until the end to avoid repeated min + width rounding.
189        let mut ink: Option<[f32; 4]> = None;
190        let mut chars = text.chars().peekable();
191        while let Some(c) = chars.next() {
192            let crlf = multiline && c == '\r' && chars.peek() == Some(&'\n');
193            if multiline && (c == '\n' || crlf) {
194                if crlf {
195                    chars.next();
196                }
197                result.width = result.width.max(x);
198                x = 0.0;
199                baseline = checked_advance(baseline, self.line_height())?;
200                result.line_count += 1;
201                continue;
202            }
203
204            let rows = glyph(c.to_ascii_uppercase());
205            if c != ' ' && rows == [0; 7] {
206                result.unsupported_glyphs += 1;
207            }
208            for (row, bits) in rows.into_iter().enumerate() {
209                if bits == 0 {
210                    continue;
211                }
212                // Row extrema use the same rectangle arithmetic as draw_text_ex.
213                let left = x + (bits.leading_zeros() - 3) as f32 * self.pixel_size;
214                let last = x + (4 - bits.trailing_zeros()) as f32 * self.pixel_size;
215                let top = baseline - self.baseline() + row as f32 * self.pixel_size;
216                let right = checked_advance(last, self.pixel_size)?;
217                let bottom = checked_advance(top, self.pixel_size)?;
218                ink = Some(match ink {
219                    None => [left, top, right, bottom],
220                    Some([l, t, r, b]) => [l.min(left), t.min(top), r.max(right), b.max(bottom)],
221                });
222            }
223            x = checked_advance(x, self.glyph_advance())?;
224        }
225        result.width = result.width.max(x);
226        result.height = baseline;
227        result.ink_bounds =
228            ink.map(|[left, top, right, bottom]| Rect::new(left, top, right - left, bottom - top));
229        Ok(result)
230    }
231}
232
233fn checked_advance(position: f32, distance: f32) -> Result<f32, FontMeasureError> {
234    let next = position + distance;
235    if !next.is_finite() || next <= position {
236        Err(FontMeasureError::Unrepresentable)
237    } else {
238        Ok(next)
239    }
240}
241
242// Original Ferravex 5×7 glyph geometry; shared with Orbit Breaker.
243pub fn glyph(c: char) -> [u8; 7] {
244    match c {
245        'A' => [14, 17, 17, 31, 17, 17, 17],
246        'B' => [30, 17, 17, 30, 17, 17, 30],
247        'C' => [14, 17, 16, 16, 16, 17, 14],
248        'D' => [30, 17, 17, 17, 17, 17, 30],
249        'E' => [31, 16, 16, 30, 16, 16, 31],
250        'F' => [31, 16, 16, 30, 16, 16, 16],
251        'G' => [14, 17, 16, 23, 17, 17, 15],
252        'H' => [17, 17, 17, 31, 17, 17, 17],
253        'I' => [31, 4, 4, 4, 4, 4, 31],
254        'J' => [7, 2, 2, 2, 18, 18, 12],
255        'K' => [17, 18, 20, 24, 20, 18, 17],
256        'L' => [16, 16, 16, 16, 16, 16, 31],
257        'M' => [17, 27, 21, 21, 17, 17, 17],
258        'N' => [17, 25, 21, 19, 17, 17, 17],
259        'O' => [14, 17, 17, 17, 17, 17, 14],
260        'P' => [30, 17, 17, 30, 16, 16, 16],
261        'Q' => [14, 17, 17, 17, 21, 18, 13],
262        'R' => [30, 17, 17, 30, 20, 18, 17],
263        'S' => [15, 16, 16, 14, 1, 1, 30],
264        'T' => [31, 4, 4, 4, 4, 4, 4],
265        'U' => [17, 17, 17, 17, 17, 17, 14],
266        'V' => [17, 17, 17, 17, 17, 10, 4],
267        'W' => [17, 17, 17, 21, 21, 21, 10],
268        'X' => [17, 17, 10, 4, 10, 17, 17],
269        'Y' => [17, 17, 10, 4, 4, 4, 4],
270        'Z' => [31, 1, 2, 4, 8, 16, 31],
271        '0' => [14, 17, 19, 21, 25, 17, 14],
272        '1' => [4, 12, 4, 4, 4, 4, 14],
273        '2' => [14, 17, 1, 2, 4, 8, 31],
274        '3' => [30, 1, 1, 14, 1, 1, 30],
275        '4' => [2, 6, 10, 18, 31, 2, 2],
276        '5' => [31, 16, 16, 30, 1, 1, 30],
277        '6' => [14, 16, 16, 30, 17, 17, 14],
278        '7' => [31, 1, 2, 4, 8, 8, 8],
279        '8' => [14, 17, 17, 14, 17, 17, 14],
280        '9' => [14, 17, 17, 15, 1, 1, 14],
281        '$' => [4, 15, 20, 14, 5, 30, 4],
282        ',' => [0, 0, 0, 12, 12, 4, 8],
283        ';' => [12, 12, 0, 12, 12, 4, 8],
284        ':' => [0, 12, 12, 0, 12, 12, 0],
285        '+' => [0, 4, 4, 31, 4, 4, 0],
286        '(' => [2, 4, 8, 8, 8, 4, 2],
287        ')' => [8, 4, 2, 2, 2, 4, 8],
288        '%' => [17, 2, 4, 4, 8, 16, 17],
289        '!' => [4, 4, 4, 4, 4, 0, 4],
290        '?' => [14, 17, 1, 2, 4, 0, 4],
291        '°' => [6, 9, 9, 6, 0, 0, 0],
292        '×' => [0, 17, 10, 4, 10, 17, 0],
293        '—' => [0, 0, 0, 31, 0, 0, 0],
294        '·' => [0, 0, 0, 4, 0, 0, 0],
295        '→' => [0, 4, 2, 31, 2, 4, 0],
296        '←' => [0, 4, 8, 31, 8, 4, 0],
297        '↑' => [4, 14, 21, 4, 4, 4, 0],
298        '↓' => [4, 4, 4, 4, 21, 14, 4],
299        '/' => [1, 1, 2, 4, 8, 16, 16],
300        '-' => [0, 0, 0, 31, 0, 0, 0],
301        '.' => [0, 0, 0, 0, 0, 12, 12],
302        '[' => [14, 8, 8, 8, 8, 8, 14],
303        ']' => [14, 2, 2, 2, 2, 2, 14],
304        '=' => [0, 0, 31, 0, 31, 0, 0],
305        '_' => [0, 0, 0, 0, 0, 0, 31],
306        '\'' => [4, 4, 2, 0, 0, 0, 0],
307        '\"' => [10, 10, 5, 0, 0, 0, 0],
308        '&' => [12, 18, 20, 8, 21, 18, 13],
309        '*' => [0, 21, 14, 31, 14, 21, 0],
310        '<' => [2, 4, 8, 16, 8, 4, 2],
311        '>' => [8, 4, 2, 1, 2, 4, 8],
312        '#' => [10, 31, 10, 10, 31, 10, 0],
313        _ => [0; 7],
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use crate::{Font, Mat4, State, TextParams, WHITE, draw_text_ex};
321
322    fn drawn_bounds<'a>(
323        lines: impl IntoIterator<Item = &'a str>,
324        size: u16,
325        scale: f32,
326    ) -> Option<Rect> {
327        crate::edit(|s| {
328            *s = State::default();
329            // Capture the actual submitted drawing geometry without a camera transform.
330            s.matrix = Mat4::IDENTITY;
331        });
332        let px = size as f32 * scale / 8.0;
333        let mut y = 7.0 * px;
334        for line in lines {
335            draw_text_ex(
336                line,
337                0.0,
338                y,
339                TextParams {
340                    font_size: size,
341                    font_scale: scale,
342                    color: WHITE,
343                },
344            );
345            y += 8.0 * px;
346        }
347        crate::read(|s| {
348            let first = s.vertices.first()?;
349            let [mut left, mut top, mut right, mut bottom] =
350                [first[0], first[1], first[0], first[1]];
351            for v in &s.vertices {
352                left = left.min(v[0]);
353                top = top.min(v[1]);
354                right = right.max(v[0]);
355                bottom = bottom.max(v[1]);
356            }
357            Some(Rect::new(left, top, right - left, bottom - top))
358        })
359    }
360
361    #[test]
362    fn checked_font_geometry_rejects_invalid_inputs_and_derived_overflow() {
363        assert_eq!(Font.try_metrics(0, 1.0), Err(FontMeasureError::ZeroSize));
364        for scale in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
365            assert_eq!(
366                Font.try_metrics(8, scale),
367                Err(FontMeasureError::InvalidScale)
368            );
369        }
370        for (size, scale) in [(1, f32::from_bits(1)), (8, f32::MAX), (u16::MAX, f32::MAX)] {
371            assert_eq!(
372                Font.try_metrics(size, scale),
373                Err(FontMeasureError::Unrepresentable)
374            );
375        }
376        for (size, scale) in [(1, f32::MIN_POSITIVE), (1, f32::MAX), (u16::MAX, 0.125)] {
377            let metrics = Font.try_metrics(size, scale).unwrap();
378            assert!(metrics.pixel_size() > 0.0);
379            assert!(metrics.line_height().is_finite());
380        }
381    }
382
383    #[test]
384    fn scaled_advances_baselines_and_ink_are_distinct() {
385        let metrics = Font.try_metrics(16, 1.5).unwrap();
386        assert_eq!(metrics.pixel_size(), 3.0);
387        assert_eq!(metrics.glyph_advance(), 18.0);
388        assert_eq!(metrics.baseline(), 21.0);
389        assert_eq!(metrics.line_height(), 24.0);
390        let text = metrics.measure_line("A ").unwrap();
391        assert_eq!((text.width, text.height, text.line_count), (36.0, 21.0, 1));
392        assert_eq!(text.ink_bounds, Some(Rect::new(0.0, 0.0, 15.0, 21.0)));
393        let punctuation = metrics.measure_line(".").unwrap();
394        assert_eq!(punctuation.ink_bounds, Some(Rect::new(3.0, 15.0, 6.0, 6.0)));
395    }
396
397    #[test]
398    fn empty_blank_and_unsupported_scalars_have_explicit_sizes() {
399        let metrics = Font.try_metrics(8, 1.0).unwrap();
400        assert_eq!(metrics.measure_line(""), Ok(BitmapTextMetrics::default()));
401        assert_eq!(
402            metrics.measure_multiline(""),
403            Ok(BitmapTextMetrics::default())
404        );
405        let blank = metrics.measure_line("  ").unwrap();
406        assert_eq!(
407            (blank.width, blank.height, blank.line_count),
408            (12.0, 7.0, 1)
409        );
410        assert_eq!(blank.ink_bounds, None);
411        assert_eq!(blank.unsupported_glyphs, 0);
412        let missing = metrics.measure_line("☃é😀ß\t\r\n").unwrap();
413        assert_eq!(missing.width, 42.0);
414        assert_eq!(missing.unsupported_glyphs, 7);
415        assert_eq!(missing.ink_bounds, None);
416        assert_eq!(metrics.measure_line("abc"), metrics.measure_line("ABC"));
417        assert_eq!(
418            metrics.measure_line("°×—·→←↑↓").unwrap().unsupported_glyphs,
419            0
420        );
421    }
422
423    #[test]
424    fn multiline_tracks_longest_line_crlf_and_trailing_empty_lines() {
425        let metrics = Font.try_metrics(8, 1.0).unwrap();
426        let label = metrics.measure_multiline("\nA☃\r\n.\n").unwrap();
427        assert_eq!(
428            (label.width, label.height, label.line_count),
429            (12.0, 31.0, 4)
430        );
431        assert_eq!(label.unsupported_glyphs, 1);
432        assert_eq!(label.ink_bounds, Some(Rect::new(0.0, 8.0, 5.0, 15.0)));
433        assert_eq!(label.ink_bounds, drawn_bounds(["", "A☃", ".", ""], 8, 1.0));
434        for text in ["\n", "\r\n"] {
435            let blank = metrics.measure_multiline(text).unwrap();
436            assert_eq!(
437                (blank.width, blank.height, blank.line_count),
438                (0.0, 15.0, 2)
439            );
440            assert_eq!(blank.unsupported_glyphs, 0);
441            assert_eq!(blank.ink_bounds, None);
442        }
443        let bare_cr = metrics.measure_multiline("A\r").unwrap();
444        assert_eq!(
445            (
446                bare_cr.width,
447                bare_cr.line_count,
448                bare_cr.unsupported_glyphs
449            ),
450            (12.0, 1, 1)
451        );
452        assert_eq!(
453            metrics.measure_multiline("A\r\n"),
454            metrics.measure_multiline("A\n")
455        );
456    }
457
458    #[test]
459    fn ink_bounds_match_actual_raster_rectangles_for_ascii_and_supported_unicode() {
460        let chars = (0..=127).map(char::from).chain("°×—·→←↑↓☃é😀ß".chars());
461        for c in chars {
462            let mut buffer = [0; 4];
463            let text = c.encode_utf8(&mut buffer);
464            for (size, scale) in [(8, 1.0), (16, 1.5), (17, 0.7), (1, 0.25)] {
465                let metrics = Font.try_metrics(size, scale).unwrap();
466                let measured = metrics.measure_line(text).unwrap();
467                assert_eq!(
468                    measured.ink_bounds,
469                    drawn_bounds([&*text], size, scale),
470                    "{c:?}, {size}, {scale}"
471                );
472            }
473        }
474    }
475
476    #[test]
477    fn label_bounds_match_fractional_raster_advances_and_successive_baselines() {
478        for (size, scale) in [(8, 1.0), (16, 1.5), (17, 0.7), (1, 0.25)] {
479            let metrics = Font.try_metrics(size, scale).unwrap();
480            let line = " a☃ . 1 LONG LABEL 29:!? → ";
481            assert_eq!(
482                metrics.measure_line(line).unwrap().ink_bounds,
483                drawn_bounds([line], size, scale)
484            );
485            let mut pen = 0.0;
486            for _ in line.chars() {
487                pen += 6.0 * (size as f32 * scale / 8.0);
488            }
489            assert_eq!(metrics.measure_line(line).unwrap().width, pen);
490            let text = "\n.a☃.\nAAA\n.\n";
491            assert_eq!(
492                metrics.measure_multiline(text).unwrap().ink_bounds,
493                drawn_bounds(text.split('\n'), size, scale)
494            );
495        }
496    }
497
498    #[test]
499    fn layout_overflow_is_checked_after_valid_font_setup() {
500        let metrics = Font.try_metrics(1, f32::MAX).unwrap();
501        assert!(metrics.measure_line("A").is_ok());
502        for text in ["AA", "  ", "☃☃"] {
503            assert_eq!(
504                metrics.measure_line(text),
505                Err(FontMeasureError::Unrepresentable)
506            );
507        }
508        assert_eq!(
509            metrics.measure_multiline("\n"),
510            Err(FontMeasureError::Unrepresentable)
511        );
512        assert_eq!(
513            metrics.measure_multiline("A\nB"),
514            Err(FontMeasureError::Unrepresentable)
515        );
516        // Exercise precision loss without allocating a many-million-character label.
517        assert_eq!(
518            checked_advance(16_777_216.0, 1.0),
519            Err(FontMeasureError::Unrepresentable)
520        );
521    }
522}