ferravex_render/
text.rs

1//! Styled bitmap text: a modern mixed-case face, drop shadows, outlines,
2//! letter spacing, alignment, measurement and allocation-free word wrapping.
3//!
4//! [`FontFace::Modern`] is a hand-authored proportional pixel face with
5//! lowercase, descenders, punctuation, tabular digits, UI symbols
6//! (`• · × → ← ↑ ↓ ★ ♥ …`) and Latin-1 accents. [`FontFace::Classic`] is the
7//! original 5×7 uppercase face, so existing art direction can opt into shadows
8//! and outlines without changing letterforms. The legacy
9//! [`crate::draw_text_ex`] and `ui` text APIs are unchanged.
10//!
11//! Sizes follow the legacy convention: one font pixel is `size / 8` logical
12//! units, so `size: 16.0` draws two-unit pixels and both faces keep integer
13//! crispness at multiples of 8. At the same size, the modern capital height
14//! (8 font pixels) is one pixel taller than the classic one (7).
15//!
16//! Geometry is one quad per horizontal run of lit pixels per row, merged across
17//! neighbouring glyphs, written directly into the frame's vertex stream with no
18//! allocation. [`measure_text_styled`] uses exactly the advances that
19//! [`draw_text_styled`] draws.
20//!
21//! ```
22//! use ferravex_render::{Color, text::{TextAlign, TextStyle, draw_text_styled, measure_text_styled}};
23//! let title = TextStyle::modern(24., Color::from_hex(0xfff4d6))
24//!     .with_shadow(Color::new(0., 0., 0., 0.6))
25//!     .with_align(TextAlign::Center);
26//! let size = measure_text_styled("Level complete!", title);
27//! draw_text_styled("Level complete!", 640., 120., title);
28//! assert_eq!(size.line_count, 1);
29//! ```
30use crate::{Color, font, font_modern, shapes::Sink};
31
32/// Look up a single glyph's `(width, rows)` in the built-in [`FontFace::Modern`]
33/// bitmap face (13 rows, baseline under row 10, bit `width - 1 - col` lit).
34///
35/// ```
36/// let (w, rows) = ferravex_render::text::modern_glyph('0').unwrap();
37/// assert_eq!(w, 5);
38/// assert_ne!(rows[3], 0);
39/// ```
40#[inline]
41pub fn modern_glyph(c: char) -> Option<(u8, [u16; 13])> {
42    font_modern::TABLE.get(c).map(|g| (g.width, g.rows))
43}
44
45/// Kerning adjustment in font pixels between two adjacent [`FontFace::Modern`] glyphs.
46///
47/// ```
48/// assert_eq!(ferravex_render::text::modern_kerning('T', 'o'), -1);
49/// assert_eq!(ferravex_render::text::modern_kerning('A', 'B'), 0);
50/// ```
51#[inline]
52pub fn modern_kerning(left: char, right: char) -> i8 {
53    font_modern::kerning(left, right)
54}
55
56/// Bitmap typeface for [`TextStyle`].
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
58pub enum FontFace {
59    /// The original 5×7 uppercase-only face (lowercase draws as uppercase).
60    Classic,
61    /// Mixed-case proportional face with descenders and accents.
62    #[default]
63    Modern,
64}
65
66/// Horizontal anchoring of each line relative to the `x` passed to drawing.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum TextAlign {
69    /// `x` is the left edge.
70    #[default]
71    Left,
72    /// `x` is the center.
73    Center,
74    /// `x` is the right edge.
75    Right,
76}
77
78/// Font metrics of a face in font pixels.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct FaceMetrics {
81    /// Rows from the top of a line to the baseline.
82    pub ascent: u8,
83    /// Rows below the baseline used by descenders.
84    pub descent: u8,
85    /// Baseline-to-baseline distance.
86    pub line_height: u8,
87    pub cap_height: u8,
88    pub x_height: u8,
89}
90
91impl FontFace {
92    /// Integer metrics in font pixels.
93    ///
94    /// ```
95    /// use ferravex_render::text::FontFace;
96    /// let m = FontFace::Modern.metrics();
97    /// assert_eq!((m.cap_height, m.x_height, m.descent, m.line_height), (8, 6, 2, 14));
98    /// assert_eq!(FontFace::Classic.metrics().line_height, 8);
99    /// ```
100    pub const fn metrics(self) -> FaceMetrics {
101        match self {
102            Self::Classic => FaceMetrics {
103                ascent: 7,
104                descent: 0,
105                line_height: 8,
106                cap_height: 7,
107                x_height: 7,
108            },
109            Self::Modern => FaceMetrics {
110                ascent: font_modern::ASCENT,
111                descent: font_modern::DESCENT,
112                line_height: font_modern::LINE_HEIGHT,
113                cap_height: font_modern::CAP_HEIGHT,
114                x_height: font_modern::X_HEIGHT,
115            },
116        }
117    }
118
119    /// Whether the face has art for `c` (space included). Unsupported
120    /// characters draw as `?` and are counted in [`TextMetrics::unsupported`].
121    ///
122    /// ```
123    /// use ferravex_render::text::FontFace;
124    /// assert!(FontFace::Modern.supports('é') && FontFace::Modern.supports('★'));
125    /// assert!(!FontFace::Classic.supports('é'));
126    /// assert!(FontFace::Classic.supports('a')); // drawn as 'A'
127    /// ```
128    pub fn supports(self, c: char) -> bool {
129        match self {
130            Self::Classic => c == ' ' || font::glyph(c.to_ascii_uppercase()) != [0; 7],
131            Self::Modern => font_modern::TABLE.get(c).is_some(),
132        }
133    }
134
135    /// Every character the face draws, in authoring order.
136    ///
137    /// ```
138    /// use ferravex_render::text::FontFace;
139    /// assert!(FontFace::Modern.characters().count() > 180);
140    /// ```
141    pub fn characters(self) -> impl Iterator<Item = char> {
142        let classic = (' '..='~')
143            .chain("°×—·→←↑↓".chars())
144            .filter(|&c| !c.is_ascii_lowercase() && Self::Classic.supports(c));
145        let modern = font_modern::TABLE.chars();
146        let (a, b) = match self {
147            Self::Classic => (Some(classic), None),
148            Self::Modern => (None, Some(modern)),
149        };
150        a.into_iter().flatten().chain(b.into_iter().flatten())
151    }
152}
153
154/// Appearance of styled text. Construct with [`TextStyle::modern`] or
155/// [`TextStyle::classic`] and refine with the `with_*` methods.
156///
157/// ```
158/// use ferravex_render::{Color, text::{FontFace, TextAlign, TextStyle}};
159/// let style = TextStyle::modern(16., Color::new(1., 1., 1., 1.))
160///     .with_outline(Color::new(0., 0., 0., 1.))
161///     .with_letter_spacing(1.)
162///     .with_align(TextAlign::Right);
163/// assert_eq!(style.face, FontFace::Modern);
164/// assert_eq!(style.pixel(), 2.);
165/// ```
166#[derive(Clone, Copy, Debug, PartialEq)]
167pub struct TextStyle {
168    pub face: FontFace,
169    /// One font pixel is `size / 8` logical units.
170    pub size: f32,
171    pub color: Color,
172    /// One-font-pixel drop shadow (down and right), drawn under the outline.
173    pub shadow: Option<Color>,
174    /// One-font-pixel outline around every glyph. Outlines of adjacent glyphs
175    /// merge, so translucent outlines do not double-blend.
176    pub outline: Option<Color>,
177    /// Extra space between glyphs in font pixels (may be fractional or negative).
178    pub letter_spacing: f32,
179    /// Extra space between lines in font pixels.
180    pub line_spacing: f32,
181    pub align: TextAlign,
182    /// Rounds each line's origin to the device pixel grid (default `true`) so
183    /// integer-scaled glyphs stay crisp at fractional positions.
184    pub pixel_snap: bool,
185}
186
187impl Default for TextStyle {
188    fn default() -> Self {
189        Self::modern(16., crate::WHITE)
190    }
191}
192
193impl TextStyle {
194    /// Modern face at `size` (one font pixel = `size / 8`).
195    pub const fn modern(size: f32, color: Color) -> Self {
196        Self {
197            face: FontFace::Modern,
198            size,
199            color,
200            shadow: None,
201            outline: None,
202            letter_spacing: 0.,
203            line_spacing: 0.,
204            align: TextAlign::Left,
205            pixel_snap: true,
206        }
207    }
208    /// Classic 5×7 face at `size`.
209    pub const fn classic(size: f32, color: Color) -> Self {
210        let mut style = Self::modern(size, color);
211        style.face = FontFace::Classic;
212        style
213    }
214    pub const fn with_face(mut self, face: FontFace) -> Self {
215        self.face = face;
216        self
217    }
218    pub const fn with_size(mut self, size: f32) -> Self {
219        self.size = size;
220        self
221    }
222    pub const fn with_color(mut self, color: Color) -> Self {
223        self.color = color;
224        self
225    }
226    pub const fn with_shadow(mut self, color: Color) -> Self {
227        self.shadow = Some(color);
228        self
229    }
230    pub const fn with_outline(mut self, color: Color) -> Self {
231        self.outline = Some(color);
232        self
233    }
234    pub const fn with_letter_spacing(mut self, pixels: f32) -> Self {
235        self.letter_spacing = pixels;
236        self
237    }
238    pub const fn with_line_spacing(mut self, pixels: f32) -> Self {
239        self.line_spacing = pixels;
240        self
241    }
242    pub const fn with_align(mut self, align: TextAlign) -> Self {
243        self.align = align;
244        self
245    }
246    pub const fn with_pixel_snap(mut self, snap: bool) -> Self {
247        self.pixel_snap = snap;
248        self
249    }
250    /// Size of one font pixel in logical units.
251    pub fn pixel(&self) -> f32 {
252        self.size / 8.
253    }
254    /// Baseline-to-baseline distance in logical units.
255    pub fn line_height(&self) -> f32 {
256        (self.face.metrics().line_height as f32 + self.line_spacing) * self.pixel()
257    }
258    /// Baseline that optically centers capitals and digits on `center_y`.
259    ///
260    /// ```
261    /// use ferravex_render::{Color, text::TextStyle};
262    /// let style = TextStyle::modern(16., Color::new(1., 1., 1., 1.));
263    /// assert_eq!(style.centered_baseline(100.), 108.); // 8 px caps of 2 units
264    /// ```
265    pub fn centered_baseline(&self, center_y: f32) -> f32 {
266        center_y + self.face.metrics().cap_height as f32 * self.pixel() * 0.5
267    }
268    fn is_valid(&self) -> bool {
269        let c = self.color;
270        self.size.is_finite()
271            && self.size > 0.
272            && self.letter_spacing.is_finite()
273            && self.line_spacing.is_finite()
274            && [c.r, c.g, c.b, c.a].iter().all(|v| v.is_finite())
275    }
276}
277
278/// Measured size of styled text in logical units.
279#[derive(Clone, Copy, Debug, Default, PartialEq)]
280pub struct TextMetrics {
281    /// Widest line from the first glyph's left edge to the last glyph's right
282    /// edge (no trailing spacing). Shadows and outlines add one font pixel.
283    pub width: f32,
284    /// From the first line's top to the last line's descender bottom.
285    pub height: f32,
286    /// Lines separated by `\n` (a trailing `\r` is ignored); empty text has none.
287    pub line_count: usize,
288    /// Baseline-to-baseline distance.
289    pub line_height: f32,
290    /// Top of a line to its baseline (includes room for capital accents).
291    pub ascent: f32,
292    /// Baseline to the bottom of descenders.
293    pub descent: f32,
294    pub cap_height: f32,
295    pub x_height: f32,
296    /// Characters drawn with the `?` fallback.
297    pub unsupported: usize,
298}
299
300// ---------------------------------------------------------------------------
301// Glyph access.
302
303#[derive(Clone, Copy)]
304struct Shape {
305    width: u8,
306    /// Lit bits of one row; bit `width - 1 - column`.
307    bits: u16,
308}
309
310#[inline]
311fn modern(c: char) -> (&'static font_modern::Glyph, bool) {
312    match font_modern::TABLE.get(c) {
313        Some(g) => (g, true),
314        None => (
315            font_modern::TABLE.get('?').expect("modern '?' glyph"),
316            false,
317        ),
318    }
319}
320
321#[inline]
322fn classic(c: char) -> ([u8; 7], bool) {
323    let rows = font::glyph(c.to_ascii_uppercase());
324    if c == ' ' || rows != [0; 7] {
325        (rows, true)
326    } else {
327        (font::glyph('?'), false)
328    }
329}
330
331#[inline]
332fn width_of(face: FontFace, c: char) -> (u8, bool) {
333    match face {
334        FontFace::Classic => (5, classic(c).1),
335        FontFace::Modern => {
336            let (g, ok) = modern(c);
337            (g.width, ok)
338        }
339    }
340}
341
342/// Row `row` of `c`, where rows may lie outside the cell (they are clear).
343#[inline]
344fn row_of(face: FontFace, c: char, row: i32) -> Shape {
345    match face {
346        FontFace::Classic => {
347            let rows = classic(c).0;
348            let bits = usize::try_from(row)
349                .ok()
350                .and_then(|r| rows.get(r))
351                .map_or(0, |&b| b as u16);
352            Shape { width: 5, bits }
353        }
354        FontFace::Modern => {
355            let g = modern(c).0;
356            let bits = usize::try_from(row)
357                .ok()
358                .and_then(|r| g.rows.get(r))
359                .map_or(0, |&b| b);
360            Shape {
361                width: g.width,
362                bits,
363            }
364        }
365    }
366}
367
368fn kern(face: FontFace, left: char, right: char) -> i8 {
369    match face {
370        FontFace::Classic => 0,
371        FontFace::Modern => font_modern::kerning(left, right),
372    }
373}
374
375fn rows(face: FontFace) -> i32 {
376    match face {
377        FontFace::Classic => 7,
378        FontFace::Modern => font_modern::ROWS as i32,
379    }
380}
381
382/// Walks a line's glyph origins in font pixels: `(char, x, width)`.
383fn layout(line: &str, face: FontFace, spacing: f32) -> impl Iterator<Item = (char, f32, u8)> + '_ {
384    let mut x = 0.;
385    let mut prev: Option<char> = None;
386    line.chars().map(move |c| {
387        if let Some(p) = prev {
388            x += 1. + spacing + kern(face, p, c) as f32;
389        }
390        let width = width_of(face, c).0;
391        let origin = x;
392        x += width as f32;
393        prev = Some(c);
394        (c, origin, width)
395    })
396}
397
398/// Ink advance of one line in font pixels and its unsupported count.
399fn line_units(line: &str, face: FontFace, spacing: f32) -> (f32, usize) {
400    let mut end: f32 = 0.;
401    let mut missing = 0;
402    for (c, x, w) in layout(line, face, spacing) {
403        end = x + w as f32;
404        missing += usize::from(!width_of(face, c).1);
405    }
406    (end.max(0.), missing)
407}
408
409fn lines(text: &str) -> impl Iterator<Item = &str> {
410    text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l))
411}
412
413/// Measures styled text exactly as [`draw_text_styled`] lays it out.
414/// Invalid styles (non-finite or nonpositive size) measure as empty.
415///
416/// ```
417/// use ferravex_render::{Color, text::{TextStyle, measure_text_styled}};
418/// let style = TextStyle::modern(8., Color::new(1., 1., 1., 1.));
419/// let m = measure_text_styled("Hi", style);
420/// assert_eq!(m.width, 7.); // H (5) + spacing (1) + i (1)
421/// assert_eq!((m.line_height, m.cap_height, m.ascent, m.descent), (14., 8., 11., 2.));
422/// let two = measure_text_styled("Hi\nthere", style);
423/// assert_eq!((two.line_count, two.height), (2, 27.));
424/// ```
425pub fn measure_text_styled(text: &str, style: TextStyle) -> TextMetrics {
426    let px = style.pixel();
427    let m = style.face.metrics();
428    let mut out = TextMetrics {
429        line_height: style.line_height(),
430        ascent: m.ascent as f32 * px,
431        descent: m.descent as f32 * px,
432        cap_height: m.cap_height as f32 * px,
433        x_height: m.x_height as f32 * px,
434        ..Default::default()
435    };
436    if !style.is_valid() || text.is_empty() {
437        return out;
438    }
439    let mut widest: f32 = 0.;
440    for line in lines(text) {
441        let (units, missing) = line_units(line, style.face, style.letter_spacing);
442        widest = widest.max(units);
443        out.unsupported += missing;
444        out.line_count += 1;
445    }
446    out.width = widest * px;
447    out.height = (out.line_count - 1) as f32 * out.line_height + out.ascent + out.descent;
448    out
449}
450
451/// Width in logical units of a single line (no `\n` handling).
452///
453/// ```
454/// use ferravex_render::{Color, text::{TextStyle, text_width}};
455/// let s = TextStyle::modern(16., Color::new(1., 1., 1., 1.));
456/// assert_eq!(text_width("10", s), text_width("88", s)); // tabular digits
457/// ```
458pub fn text_width(line: &str, style: TextStyle) -> f32 {
459    if !style.is_valid() {
460        return 0.;
461    }
462    line_units(line, style.face, style.letter_spacing).0 * style.pixel()
463}
464
465// ---------------------------------------------------------------------------
466// Drawing.
467
468#[derive(Clone, Copy)]
469struct Layer {
470    color: Color,
471    /// Offset in font pixels.
472    dx: f32,
473    dy: f32,
474    dilate: bool,
475}
476
477/// Dilated row bits (one pixel in all eight directions), one column wider on
478/// both sides: bit `width + 1 - column'` where `column' = column + 1`.
479#[inline]
480fn dilated(face: FontFace, c: char, row: i32) -> Shape {
481    let mut acc = 0_u16;
482    let mut width = 0;
483    for r in row - 1..=row + 1 {
484        let s = row_of(face, c, r);
485        width = s.width;
486        let e = s.bits << 1;
487        acc |= e | (e << 1) | (e >> 1);
488    }
489    Shape {
490        width: width + 2,
491        bits: acc,
492    }
493}
494
495/// Mask of columns `start..end` in a row of `width` columns.
496#[inline]
497fn span(start: i32, end: i32, width: i32) -> u16 {
498    ((((1_u32 << (end - start)) - 1) << (width - end)) & 0xffff) as u16
499}
500
501/// Whether `start..end` is a maximal lit run of `bits`.
502#[inline]
503fn is_run(bits: u16, start: i32, end: i32, width: i32) -> bool {
504    let mask = span(start, end, width);
505    let left = start == 0 || bits & span(start - 1, start, width) == 0;
506    let right = end == width || bits & span(end, end + 1, width) == 0;
507    bits & mask == mask && left && right
508}
509
510/// Maximal lit runs `(start, end)` of one row, left to right.
511fn runs(bits: u16, width: i32) -> impl Iterator<Item = (i32, i32)> {
512    let lit = move |col: i32| col < width && bits >> (width - 1 - col) & 1 != 0;
513    let mut col = 0;
514    std::iter::from_fn(move || {
515        while col < width && !lit(col) {
516            col += 1;
517        }
518        if col >= width {
519            return None;
520        }
521        let start = col;
522        while lit(col) {
523            col += 1;
524        }
525        Some((start, col))
526    })
527}
528
529/// Glyph-by-glyph rectangles: each maximal horizontal run is extended down
530/// over identical runs in the following rows, so stems become one quad.
531fn draw_line_stacked(
532    sink: &mut Sink,
533    line: &str,
534    left: f32,
535    baseline: f32,
536    px: f32,
537    style: &TextStyle,
538    layer: Layer,
539) {
540    let face = style.face;
541    let ascent = face.metrics().ascent as f32;
542    let count = rows(face);
543    for (c, origin, _) in layout(line, face, style.letter_spacing) {
544        let mut bits = [0_u16; font_modern::ROWS];
545        let mut width = 0;
546        for (r, slot) in bits.iter_mut().enumerate().take(count as usize) {
547            let shape = row_of(face, c, r as i32);
548            *slot = shape.bits;
549            width = shape.width as i32;
550        }
551        for r in 0..count as usize {
552            for (start, end) in runs(bits[r], width) {
553                if r > 0 && is_run(bits[r - 1], start, end, width) {
554                    continue; // Already covered by the rectangle above.
555                }
556                let mut height = 1;
557                while r + height < count as usize && is_run(bits[r + height], start, end, width) {
558                    height += 1;
559                }
560                let x = left + (origin + start as f32 + layer.dx) * px;
561                let y = baseline + (r as f32 - ascent + layer.dy) * px;
562                sink.rect(
563                    x,
564                    y,
565                    (end - start) as f32 * px,
566                    height as f32 * px,
567                    layer.color,
568                );
569            }
570        }
571    }
572}
573
574/// Row-by-row runs merged across neighbouring glyphs (used for outlines so a
575/// translucent outline never overlaps itself).
576fn draw_line_merged(
577    sink: &mut Sink,
578    line: &str,
579    left: f32,
580    baseline: f32,
581    px: f32,
582    style: &TextStyle,
583    layer: Layer,
584) {
585    let face = style.face;
586    let ascent = face.metrics().ascent as f32;
587    let (first, last) = if layer.dilate {
588        (-1, rows(face))
589    } else {
590        (0, rows(face) - 1)
591    };
592    for row in first..=last {
593        let top = baseline + (row as f32 - ascent + layer.dy) * px;
594        // Current merged run in font pixels.
595        let mut run: Option<(f32, f32)> = None;
596        let flush = |run: (f32, f32), sink: &mut Sink| {
597            let x = left + (run.0 + layer.dx) * px;
598            sink.rect(x, top, (run.1 - run.0) * px, px, layer.color);
599        };
600        for (c, origin, _) in layout(line, face, style.letter_spacing) {
601            let (shape, origin) = if layer.dilate {
602                (dilated(face, c, row), origin - 1.)
603            } else {
604                (row_of(face, c, row), origin)
605            };
606            for (start, end) in runs(shape.bits, shape.width as i32) {
607                let s = origin + start as f32;
608                let e = origin + end as f32;
609                run = match run {
610                    Some((a, b)) if s <= b + 1e-4 => Some((a.min(s), b.max(e))),
611                    Some(done) => {
612                        flush(done, sink);
613                        Some((s, e))
614                    }
615                    None => Some((s, e)),
616                };
617            }
618        }
619        if let Some(done) = run {
620            flush(done, sink);
621        }
622    }
623}
624
625/// Draws styled text. `y` is the first line's baseline (as with
626/// [`crate::draw_text_ex`]) and `x` anchors each line per [`TextStyle::align`].
627/// Lines split on `\n`. Returns the same value as [`measure_text_styled`].
628///
629/// Each layer emits one quad (6 vertices) per merged horizontal run per row;
630/// a shadow or outline adds one more layer. Nothing is drawn for an invalid
631/// style or non-finite position.
632///
633/// ```
634/// use ferravex_render::{Color, text::{TextStyle, draw_text_styled}};
635/// let hud = TextStyle::modern(16., Color::from_hex(0xe4eef2)).with_shadow(Color::new(0., 0., 0., 0.55));
636/// draw_text_styled("Score 12,480 ★", 24., 40., hud);
637/// ```
638pub fn draw_text_styled(text: &str, x: f32, y: f32, style: TextStyle) -> TextMetrics {
639    let metrics = measure_text_styled(text, style);
640    if metrics.line_count == 0 || !x.is_finite() || !y.is_finite() {
641        return metrics;
642    }
643    crate::edit(|s| {
644        let mut sink = Sink::new(s);
645        let dp = sink.device_pixel();
646        let px = style.pixel();
647        let snap = |v: f32| {
648            if style.pixel_snap {
649                (v / dp).round() * dp
650            } else {
651                v
652            }
653        };
654        let mut layers = [None; 3];
655        if let Some(color) = style.shadow {
656            layers[0] = Some(Layer {
657                color,
658                dx: 1.,
659                dy: 1.,
660                dilate: style.outline.is_some(),
661            });
662        }
663        if let Some(color) = style.outline {
664            layers[1] = Some(Layer {
665                color,
666                dx: 0.,
667                dy: 0.,
668                dilate: true,
669            });
670        }
671        layers[2] = Some(Layer {
672            color: style.color,
673            dx: 0.,
674            dy: 0.,
675            dilate: false,
676        });
677        // Layers are drawn back to front over the whole text so a line's shadow
678        // never covers the line above it.
679        for layer in layers.into_iter().flatten() {
680            let mut baseline = y;
681            for line in lines(text) {
682                let width = line_units(line, style.face, style.letter_spacing).0 * px;
683                let left = match style.align {
684                    TextAlign::Left => x,
685                    TextAlign::Center => x - width * 0.5,
686                    TextAlign::Right => x - width,
687                };
688                let (left, line_y) = (snap(left), snap(baseline));
689                if layer.dilate {
690                    draw_line_merged(&mut sink, line, left, line_y, px, &style, layer);
691                } else {
692                    draw_line_stacked(&mut sink, line, left, line_y, px, &style, layer);
693                }
694                baseline += metrics.line_height;
695            }
696        }
697    });
698    metrics
699}
700
701/// Greedy word-wrapped lines of `text` no wider than `max_width` (logical
702/// units). Explicit `\n` breaks are kept; runs of spaces at a wrap are dropped;
703/// a word wider than the limit is split between characters. Borrowed slices,
704/// no allocation.
705///
706/// ```
707/// use ferravex_render::{Color, text::{TextStyle, text_width, wrap_text}};
708/// let s = TextStyle::modern(8., Color::new(1., 1., 1., 1.));
709/// let lines: Vec<&str> = wrap_text("Press Space to jump over the gap", 60., s).collect();
710/// assert_eq!(lines, ["Press Space", "to jump over", "the gap"]);
711/// assert!(lines.iter().all(|l| text_width(l, s) <= 60.));
712/// ```
713pub fn wrap_text(text: &str, max_width: f32, style: TextStyle) -> WrapLines<'_> {
714    let limit = if style.is_valid() && max_width.is_finite() {
715        (max_width / style.pixel()).max(0.)
716    } else {
717        f32::INFINITY
718    };
719    WrapLines {
720        rest: (!text.is_empty()).then_some(text),
721        paragraph: "",
722        limit,
723        face: style.face,
724        spacing: style.letter_spacing,
725    }
726}
727
728/// Iterator returned by [`wrap_text`].
729#[derive(Clone, Debug)]
730pub struct WrapLines<'a> {
731    /// Unprocessed text after the current paragraph.
732    rest: Option<&'a str>,
733    /// Remainder of the current paragraph.
734    paragraph: &'a str,
735    limit: f32,
736    face: FontFace,
737    spacing: f32,
738}
739
740impl<'a> Iterator for WrapLines<'a> {
741    type Item = &'a str;
742    fn next(&mut self) -> Option<&'a str> {
743        if self.paragraph.is_empty() {
744            let rest = self.rest?;
745            let (line, tail) = match rest.find('\n') {
746                Some(i) => (&rest[..i], Some(&rest[i + 1..])),
747                None => (rest, None),
748            };
749            self.rest = tail;
750            let line = line.strip_suffix('\r').unwrap_or(line);
751            if line.is_empty() {
752                return Some(line);
753            }
754            self.paragraph = line;
755        }
756        let text = self.paragraph;
757        let mut right = 0.;
758        let mut prev: Option<char> = None;
759        // Last break opportunity: (end of the line, start of the next word).
760        let mut word_end: Option<usize> = None;
761        let mut space_break: Option<(usize, usize)> = None;
762        for (i, c) in text.char_indices() {
763            let advance = prev.map_or(0., |p| 1. + self.spacing + kern(self.face, p, c) as f32);
764            let next_right = right + advance + width_of(self.face, c).0 as f32;
765            if c == ' ' {
766                if prev.is_some_and(|p| p != ' ') {
767                    word_end = Some(i);
768                }
769            } else {
770                if prev == Some(' ')
771                    && let Some(end) = word_end
772                {
773                    space_break = Some((end, i));
774                }
775                if next_right > self.limit + 1e-4 && i > 0 {
776                    let (line, next) = match space_break {
777                        Some((end, next)) => (&text[..end], &text[next..]),
778                        None => (&text[..i], &text[i..]),
779                    };
780                    self.paragraph = next;
781                    return Some(line);
782                }
783            }
784            right = next_right;
785            prev = Some(c);
786        }
787        self.paragraph = "";
788        Some(text.trim_end_matches(' '))
789    }
790}
791
792/// Draws `text` word-wrapped to `max_width` starting at baseline `y`; `x`
793/// anchors lines per the style's alignment. Returns the wrapped block's metrics.
794///
795/// ```
796/// use ferravex_render::{Color, text::{TextStyle, draw_text_wrapped}};
797/// let body = TextStyle::modern(16., Color::from_hex(0xc8d3dc));
798/// let m = draw_text_wrapped("Collect every gem before the lava rises.", 40., 200., 240., body);
799/// assert!(m.width <= 240. && m.line_count >= 2);
800/// ```
801pub fn draw_text_wrapped(
802    text: &str,
803    x: f32,
804    y: f32,
805    max_width: f32,
806    style: TextStyle,
807) -> TextMetrics {
808    let mut total = measure_text_styled("", style);
809    if !style.is_valid() {
810        return total;
811    }
812    let mut baseline = y;
813    for line in wrap_text(text, max_width, style) {
814        let m = draw_text_styled(line, x, baseline, style);
815        total.width = total.width.max(m.width);
816        total.unsupported += m.unsupported;
817        total.line_count += 1;
818        baseline += total.line_height;
819    }
820    if total.line_count > 0 {
821        total.height =
822            (total.line_count - 1) as f32 * total.line_height + total.ascent + total.descent;
823    }
824    total
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use crate::shapes::tests::capture;
831
832    const WHITE: Color = Color::new(1., 1., 1., 1.);
833
834    /// Rasterizes captured rects (pairs of triangles) at pixel centers into a
835    /// coverage grid of quad counts per pixel.
836    fn coverage(vertices: &[[f32; 8]], w: usize, h: usize) -> Vec<u8> {
837        let mut grid = vec![0_u8; w * h];
838        for quad in vertices.chunks(6) {
839            let xs = quad.iter().map(|v| (v[0] + 1.) * w as f32 * 0.5);
840            let ys = quad.iter().map(|v| (1. - v[1]) * h as f32 * 0.5);
841            let (x0, x1) = xs.fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
842            let (y0, y1) = ys.fold((f32::MAX, f32::MIN), |(a, b), y| (a.min(y), b.max(y)));
843            for py in 0..h {
844                for px in 0..w {
845                    let (cx, cy) = (px as f32 + 0.5, py as f32 + 0.5);
846                    if cx > x0 && cx < x1 && cy > y0 && cy < y1 {
847                        grid[py * w + px] += 1;
848                    }
849                }
850            }
851        }
852        grid
853    }
854
855    #[test]
856    fn measure_equals_draw_extent_for_both_faces_and_alignments() {
857        for face in [FontFace::Modern, FontFace::Classic] {
858            for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
859                let style = TextStyle::modern(16., WHITE)
860                    .with_face(face)
861                    .with_align(align);
862                let text = "Hydra Wave 7 — x×y";
863                let m = measure_text_styled(text, style);
864                let v = capture(800, 200, || {
865                    draw_text_styled(text, 400., 100., style);
866                });
867                let xs = v.iter().map(|v| (v[0] + 1.) * 400.);
868                let (lo, hi) = xs.fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
869                let expect_left = match align {
870                    TextAlign::Left => 400.,
871                    TextAlign::Center => 400. - m.width / 2.,
872                    TextAlign::Right => 400. - m.width,
873                };
874                assert!(
875                    (lo - expect_left.round()).abs() < 1e-3,
876                    "{face:?} {align:?} {lo}"
877                );
878                assert!(
879                    (hi - lo - m.width).abs() < 1e-3,
880                    "{face:?} {align:?} {}",
881                    hi - lo
882                );
883            }
884        }
885    }
886
887    #[test]
888    fn merged_runs_cover_exactly_the_lit_pixels_without_overlap() {
889        let text = "Quick fox, jumpy dwarves! 0123456789 ÀÉÎõü ★♥→";
890        let style = TextStyle::modern(8., WHITE);
891        let v = capture(400, 40, || {
892            draw_text_styled(text, 2., 20., style);
893        });
894        let grid = coverage(&v, 400, 40);
895        assert!(grid.iter().all(|&n| n <= 1), "runs overlap");
896        let lit: usize = text
897            .chars()
898            .map(|c| {
899                modern(c)
900                    .0
901                    .rows
902                    .iter()
903                    .map(|r| r.count_ones() as usize)
904                    .sum::<usize>()
905            })
906            .sum();
907        assert_eq!(grid.iter().filter(|&&n| n == 1).count(), lit);
908        // Far fewer quads than lit pixels.
909        assert!(
910            v.len() / 6 < lit * 2 / 5,
911            "{} quads for {lit} pixels",
912            v.len() / 6
913        );
914    }
915
916    const HUD: [&str; 10] = [
917        "SCORE 012480",
918        "BEST 98000",
919        "WAVE 7/10",
920        "LIVES 3",
921        "COMBO X12",
922        "HEALTH 87%",
923        "TIME 02:15.40",
924        "PRESS SPACE TO JUMP",
925        "PAUSED - ESC TO RESUME",
926        "GEMS 14 / 20  KEYS 2",
927    ];
928
929    #[test]
930    fn legacy_draw_text_ex_merges_row_runs_and_styled_text_saves_vertices() {
931        use crate::{TextParams, draw_text_ex};
932        let (w, h) = (420, 240);
933        let v = capture(w as u32, h as u32, || {
934            for (i, line) in HUD.iter().enumerate() {
935                draw_text_ex(
936                    line,
937                    4.,
938                    20. + i as f32 * 22.,
939                    TextParams {
940                        font_size: 16,
941                        font_scale: 1.,
942                        color: WHITE,
943                    },
944                );
945            }
946        });
947        // Expected per-pixel coverage from the bitmaps.
948        let mut expected = vec![0_u8; w * h];
949        let (mut lit, mut runs) = (0, 0);
950        for (i, line) in HUD.iter().enumerate() {
951            for (k, c) in line.chars().enumerate() {
952                for (row, bits) in font::glyph(c).into_iter().enumerate() {
953                    for col in 0..5 {
954                        let on = |col: usize| col < 5 && bits & (1 << (4 - col)) != 0;
955                        if on(col) {
956                            lit += 1;
957                            runs += usize::from(col == 0 || !on(col - 1));
958                            let x0 = 4 + k * 12 + col * 2;
959                            let y0 = (20 + i * 22) - 14 + row * 2;
960                            for y in y0..y0 + 2 {
961                                for x in x0..x0 + 2 {
962                                    expected[y * w + x] = 1;
963                                }
964                            }
965                        }
966                    }
967                }
968            }
969        }
970        assert_eq!(coverage(&v, w, h), expected);
971        // One 6-vertex quad per maximal horizontal run of lit font pixels,
972        // each exactly one font pixel (2 units) tall, matching the
973        // per-pixel `draw_rectangle` reference coverage with fewer vertices.
974        assert_eq!(v.len(), runs * 6);
975        assert!(runs * 3 < lit * 2, "runs {runs}, lit pixels {lit}");
976        for quad in v.chunks(6) {
977            let ys = quad.iter().map(|v| (1. - v[1]) * h as f32 * 0.5);
978            let (lo, hi) = ys.fold((f32::MAX, f32::MIN), |(lo, hi), y| (lo.min(y), hi.max(y)));
979            assert!((hi - lo - 2.).abs() < 1e-3, "{lo}..{hi}");
980        }
981        let reference = capture(w as u32, h as u32, || {
982            for (i, line) in HUD.iter().enumerate() {
983                let mut x = 4.;
984                for c in line.chars() {
985                    for (row, bits) in font::glyph(c).into_iter().enumerate() {
986                        for col in 0..5 {
987                            if bits & (1 << (4 - col)) != 0 {
988                                let y = 20. + i as f32 * 22. - 14. + row as f32 * 2.;
989                                crate::draw_rectangle(x + col as f32 * 2., y, 2., 2., WHITE);
990                            }
991                        }
992                    }
993                    x += 12.;
994                }
995            }
996        });
997        assert_eq!(reference.len(), lit * 6);
998        assert_eq!(coverage(&v, w, h), coverage(&reference, w, h));
999        let per_pixel = lit * 6;
1000        let modern = capture(w as u32, h as u32, || {
1001            for (i, line) in HUD.iter().enumerate() {
1002                draw_text_styled(
1003                    line,
1004                    4.,
1005                    20. + i as f32 * 28.,
1006                    TextStyle::modern(16., WHITE),
1007                );
1008            }
1009        })
1010        .len();
1011        let classic_styled = capture(w as u32, h as u32, || {
1012            for (i, line) in HUD.iter().enumerate() {
1013                draw_text_styled(
1014                    line,
1015                    4.,
1016                    20. + i as f32 * 22.,
1017                    TextStyle::classic(16., WHITE),
1018                );
1019            }
1020        })
1021        .len();
1022        println!(
1023            "HUD vertices: per-pixel {per_pixel}, classic draw_text_ex runs {}, classic styled {classic_styled} \
1024             ({:.0}% fewer), modern styled {modern} ({:.0}% fewer)",
1025            v.len(),
1026            100. * (1. - classic_styled as f32 / per_pixel as f32),
1027            100. * (1. - modern as f32 / per_pixel as f32),
1028        );
1029        assert!(classic_styled * 2 < per_pixel && modern * 2 < per_pixel);
1030    }
1031
1032    #[test]
1033    fn outline_and_shadow_layers_merge_and_order_back_to_front() {
1034        let style = TextStyle::modern(8., WHITE)
1035            .with_outline(Color::new(0., 0., 0., 0.5))
1036            .with_shadow(Color::new(0., 0., 1., 0.5));
1037        let v = capture(100, 30, || {
1038            draw_text_styled("ab", 10., 15., style);
1039        });
1040        // Shadow first, outline second, body last.
1041        assert_eq!(v[0][6], 1.);
1042        assert_eq!(v.last().unwrap()[4], 1.);
1043        let outline: Vec<_> = v
1044            .iter()
1045            .filter(|v| v[7] == 0.5 && v[6] == 0.)
1046            .copied()
1047            .collect();
1048        let grid = coverage(&outline, 100, 30);
1049        assert!(
1050            grid.iter().all(|&n| n <= 1),
1051            "translucent outline double-blends"
1052        );
1053        let m = measure_text_styled("ab", style);
1054        let (lo, hi) = outline
1055            .iter()
1056            .map(|v| (v[0] + 1.) * 50.)
1057            .fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(x), b.max(x)));
1058        assert!(
1059            (lo - 9.).abs() < 1e-3 && (hi - 11. - m.width).abs() < 1e-3,
1060            "{lo} {hi}"
1061        );
1062    }
1063
1064    #[test]
1065    fn wrapping_respects_width_newlines_and_long_words() {
1066        let s = TextStyle::modern(8., WHITE);
1067        let all: Vec<_> = wrap_text("a\n\nbb  cc\r\nsupercalifragilistic", 20., s).collect();
1068        assert_eq!(all[..4], ["a", "", "bb", "cc"]);
1069        assert!(
1070            all[4..]
1071                .iter()
1072                .all(|l| text_width(l, s) <= 20. && !l.is_empty())
1073        );
1074        assert_eq!(all[4..].concat(), "supercalifragilistic");
1075        assert_eq!(wrap_text("", 10., s).count(), 0);
1076        assert_eq!(wrap_text("x", 0., s).collect::<Vec<_>>(), ["x"]);
1077        let m = draw_text_wrapped("one two three four", 0., 20., 40., s);
1078        assert_eq!(
1079            m.line_count,
1080            wrap_text("one two three four", 40., s).count()
1081        );
1082    }
1083
1084    #[test]
1085    fn tabular_digits_kerning_and_invalid_styles() {
1086        let s = TextStyle::modern(8., WHITE);
1087        let w = text_width("0000", s);
1088        for n in ["1111", "1234", "9876", "7171"] {
1089            assert_eq!(text_width(n, s), w);
1090        }
1091        assert_eq!(text_width("To", s), text_width("T", s) + text_width("o", s));
1092        assert_eq!(
1093            text_width("Ta", s) + 1.,
1094            text_width("T", s) + 1. + text_width("a", s)
1095        );
1096        assert_eq!(measure_text_styled("☃", s).unsupported, 1);
1097        let bad = TextStyle::modern(f32::NAN, WHITE);
1098        assert_eq!(measure_text_styled("abc", bad).line_count, 0);
1099        assert!(
1100            capture(64, 64, || {
1101                draw_text_styled("abc", 0., 10., bad);
1102                draw_text_styled("abc", f32::INFINITY, 10., s);
1103            })
1104            .is_empty()
1105        );
1106    }
1107}