Skip to main content

nadir_render/
font.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The font asset: a cooked font file, `atlas/<font>.font.kbj`, whose
16//! glyphs are frames of a sprite of an atlas (ADR-0035, ADR-0054).
17
18use nadir_assets::{
19    Asset, AssetError, AssetPath, AssetServer, DecodeCtx, FinalizeCtx, Handle, Scope,
20};
21use nadir_codec::font;
22use nadir_core::IVec2;
23
24use crate::{Atlas, AtlasSprite, Texture};
25
26/// How far from 0 a glyph's offsets and advance, a kerning amount and the
27/// line height may be, in pixels: ±32767 (`i16::MAX`), far past any font,
28/// so that a line's sums cannot overflow.
29const METRIC: i32 = i16::MAX as i32;
30
31/// A bitmap font the cook made from a BMFont: its metrics, its glyphs by
32/// character, its kerning pairs, and the glyph a character it lacks draws.
33/// Each glyph is a frame of a sprite of an atlas, which [`Font::atlas`] and
34/// [`Font::sprite`] name.
35///
36/// It needs no GPU, so a game can make it before its window opens, and it
37/// lays text out on its own ([`Font::layout`], [`Font::measure`]). To be
38/// drawn, its atlas and the atlas's pages must be loaded too:
39/// [`Font::load_now_in`] loads all three. It has no placeholder.
40#[derive(Clone, Debug, PartialEq)]
41pub struct Font {
42    face: String,
43    size: i32,
44    line_height: u32,
45    base: u32,
46    atlas: String,
47    sprite: String,
48    /// By character, ascending.
49    glyphs: Vec<(char, Glyph)>,
50    /// By (first, second), ascending.
51    kerning: Vec<(char, char, i32)>,
52    fallback: Glyph,
53    /// The highest frame a glyph names, the fallback's included.
54    last_frame: u32,
55}
56
57/// Why an atlas does not fit a font: what [`Font::sprite_in`] finds, with
58/// nothing allocated, so that a text can be skipped each frame for free.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub(crate) enum Misfit {
61    /// The atlas has no sprite of the font's name.
62    NoSprite,
63    /// The sprite has this many frames, fewer than the glyphs name.
64    TooFewFrames(usize),
65}
66
67/// A glyph of a [`Font`]: the frame of its font's sprite that holds its
68/// pixels, where it goes from the pen, and how far it moves the pen.
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
70pub struct Glyph {
71    frame: Option<u32>,
72    offset: IVec2,
73    advance: i32,
74}
75
76impl Font {
77    /// Loads the font file at `path`, then the atlas file it names, at once,
78    /// and starts loading the atlas's pages, all in `scope`: what a font
79    /// needs to be drawn. It blocks until the two files are read, as
80    /// [`AssetServer::load_now_in`] does; the pages, textures, are made on
81    /// the GPU by a later finish.
82    ///
83    /// `server.load::<Font>(path)` loads the font file alone: its texts are
84    /// then not drawn until its atlas and pages are loaded too.
85    ///
86    /// # Errors
87    ///
88    /// Any [`AssetError`] of the font or its atlas, and
89    /// [`AssetError::Invalid`] when the atlas has no sprite of the font's
90    /// name, or that sprite has fewer frames than the font's glyphs name.
91    pub fn load_now_in(
92        server: &mut AssetServer,
93        path: &str,
94        scope: Scope,
95        ctx: &mut FinalizeCtx<'_>,
96    ) -> Result<Handle<Font>, AssetError> {
97        let handle = server.load_now_in::<Font>(path, scope, ctx)?;
98        let font = server.get(handle).ok_or_else(|| {
99            AssetError::Invalid(format!("the font `{path}` is not in the asset server"))
100        })?;
101        let atlas_path = font.atlas.clone();
102        let atlas = server.load_now_in::<Atlas>(&atlas_path, scope, ctx)?;
103        let (Some(font), Some(atlas)) = (server.get(handle), server.get(atlas)) else {
104            return Err(AssetError::Invalid(format!(
105                "the font `{path}` or its atlas `{atlas_path}` is not in the asset server"
106            )));
107        };
108        font.sprite_in(atlas).map_err(|misfit| {
109            AssetError::Invalid(format!("the font `{path}`: {}", font.misfit(misfit)))
110        })?;
111        let pages: Vec<String> = atlas
112            .pages()
113            .iter()
114            .map(|page| page.path().to_string())
115            .collect();
116        for page in pages {
117            server.load_in::<Texture>(&page, scope);
118        }
119        Ok(handle)
120    }
121
122    /// Its face's name, as BMFont gave it: it may be empty.
123    pub fn face(&self) -> &str {
124        &self.face
125    }
126
127    /// Its size, as BMFont gave it: a negative size is BMFont's "match the
128    /// characters' height".
129    pub fn size(&self) -> i32 {
130        self.size
131    }
132
133    /// The pixels from one line's top to the next's.
134    pub fn line_height(&self) -> u32 {
135        self.line_height
136    }
137
138    /// The pixels from a line's top to its baseline.
139    pub fn base(&self) -> u32 {
140        self.base
141    }
142
143    /// The path of its atlas file, such as `atlas/fonts.kbj`, among the
144    /// cooked files.
145    pub fn atlas(&self) -> &str {
146        &self.atlas
147    }
148
149    /// The name of the sprite of its atlas whose frames are its glyphs, such
150    /// as `fonts/ui`.
151    pub fn sprite(&self) -> &str {
152        &self.sprite
153    }
154
155    /// The glyph of `character`, if the font has one.
156    pub fn glyph(&self, character: char) -> Option<Glyph> {
157        let index = self
158            .glyphs
159            .binary_search_by_key(&character, |&(id, _)| id)
160            .ok()?;
161        self.glyphs.get(index).map(|&(_, glyph)| glyph)
162    }
163
164    /// The glyph a character the font lacks draws: BMFont's fallback glyph,
165    /// if the font has one, else its `?`. It has a frame.
166    pub fn fallback(&self) -> Glyph {
167        self.fallback
168    }
169
170    /// The pixels added to `first`'s advance when `second` follows it: 0 for
171    /// a pair the font does not kern.
172    pub fn kerning(&self, first: char, second: char) -> i32 {
173        self.kerning
174            .binary_search_by_key(&(first, second), |&(a, b, _)| (a, b))
175            .map_or(0, |index| self.kerning[index].2)
176    }
177
178    /// The sprite of `atlas` whose frames are the glyphs, if `atlas` has it
179    /// and it has every frame the glyphs name; otherwise why not.
180    pub(crate) fn sprite_in<'a>(&self, atlas: &'a Atlas) -> Result<&'a AtlasSprite, Misfit> {
181        let sprite = atlas.sprite(&self.sprite).ok_or(Misfit::NoSprite)?;
182        let frames = sprite.frames().len();
183        if self.last_frame as usize >= frames {
184            return Err(Misfit::TooFewFrames(frames));
185        }
186        Ok(sprite)
187    }
188
189    /// What `misfit` means for this font, to be logged.
190    pub(crate) fn misfit(&self, misfit: Misfit) -> String {
191        match misfit {
192            Misfit::NoSprite => format!("its atlas has no sprite `{}`", self.sprite),
193            Misfit::TooFewFrames(frames) => format!(
194                "its glyphs name frame {} of the sprite `{}`, which has {frames}",
195                self.last_frame, self.sprite
196            ),
197        }
198    }
199}
200
201impl Glyph {
202    /// Its frame, an index into its font's sprite's
203    /// [`AtlasSprite::frames`]: `None` for a glyph with no pixels, such as
204    /// a space.
205    pub fn frame(&self) -> Option<usize> {
206        self.frame.map(|frame| frame as usize)
207    }
208
209    /// Where its rectangle's top-left corner is from the pen, which is on
210    /// the line's top: BMFont's `xoffset` and `yoffset`. Its frame is that
211    /// rectangle trimmed: [`AtlasFrame::offset`](crate::AtlasFrame::offset)
212    /// places its pixels in it.
213    pub fn offset(&self) -> IVec2 {
214        self.offset
215    }
216
217    /// How far it moves the pen to the right: BMFont's `xadvance`.
218    pub fn advance(&self) -> i32 {
219        self.advance
220    }
221}
222
223impl Asset for Font {
224    type Decoded = Font;
225    const EXTENSIONS: &'static [&'static str] = &["kbj"];
226
227    fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Font, AssetError> {
228        let file = font::parse(bytes, ctx.limits()).map_err(AssetError::Decode)?;
229        AssetPath::new(&file.atlas)
230            .ok()
231            .filter(|path| path.as_str() == file.atlas && path.extension() == Some("kbj"))
232            .ok_or_else(|| {
233                AssetError::Invalid(format!(
234                    "its atlas, `{}`, is not the path of an atlas file",
235                    file.atlas
236                ))
237            })?;
238        let within = |value: i32| (-METRIC..=METRIC).contains(&value);
239        let line_height = i32::try_from(file.line_height)
240            .ok()
241            .filter(|&height| within(height))
242            .ok_or_else(|| {
243                AssetError::Invalid(format!(
244                    "its line height, {}, is past {METRIC} pixels",
245                    file.line_height
246                ))
247            })?;
248        let metrics = |what: String, x: i32, y: i32, advance: i32| {
249            if within(x) && within(y) && within(advance) {
250                Ok(())
251            } else {
252                Err(AssetError::Invalid(format!(
253                    "{what}'s offset ({x}, {y}) or advance {advance} is past {METRIC} pixels"
254                )))
255            }
256        };
257        let mut last_frame = file.fallback.frame;
258        let mut glyphs = Vec::with_capacity(file.glyphs.len());
259        for glyph in &file.glyphs {
260            metrics(
261                format!("the glyph {:?} (U+{:04X})", glyph.id, glyph.id as u32),
262                glyph.x,
263                glyph.y,
264                glyph.advance,
265            )?;
266            last_frame = last_frame.max(glyph.frame.unwrap_or(0));
267            glyphs.push((
268                glyph.id,
269                Glyph {
270                    frame: glyph.frame,
271                    offset: IVec2::new(glyph.x, glyph.y),
272                    advance: glyph.advance,
273                },
274            ));
275        }
276        let fallback = &file.fallback;
277        metrics(
278            "the fallback".to_string(),
279            fallback.x,
280            fallback.y,
281            fallback.advance,
282        )?;
283        let mut kerning = Vec::with_capacity(file.kerning.len());
284        for pair in &file.kerning {
285            if !within(pair.amount) {
286                return Err(AssetError::Invalid(format!(
287                    "the kerning of {:?} and {:?}, {}, is past {METRIC} pixels",
288                    pair.first, pair.second, pair.amount
289                )));
290            }
291            kerning.push((pair.first, pair.second, pair.amount));
292        }
293        Ok(Font {
294            face: file.face,
295            size: file.size,
296            line_height: line_height as u32,
297            base: file.base,
298            atlas: file.atlas,
299            sprite: file.sprite,
300            glyphs,
301            kerning,
302            fallback: Glyph {
303                frame: Some(fallback.frame),
304                offset: IVec2::new(fallback.x, fallback.y),
305                advance: fallback.advance,
306            },
307            last_frame,
308        })
309    }
310
311    fn finalize(decoded: Font, _: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
312        Ok(decoded)
313    }
314}
315
316#[cfg(test)]
317pub(crate) mod tests {
318    use super::*;
319    use nadir_codec::{Limits, json, kbj};
320
321    /// The bytes of the KBJ file `text` describes, in JSON.
322    pub(crate) fn kbj(text: &str) -> Vec<u8> {
323        let value = json::parse(text, Limits::default()).expect("the test's JSON");
324        kbj::encode(&value, Limits::default()).expect("encodable")
325    }
326
327    /// The font `text` describes, in JSON.
328    pub(crate) fn decoded(text: &str) -> Result<Font, AssetError> {
329        Font::decode(
330            &kbj(text),
331            &DecodeCtx::new("atlas/fonts/tiny.font.kbj", Limits::default()),
332        )
333    }
334
335    /// A font of glyphs 3 wide on lines 6 high, with a space, kerning and a
336    /// fallback of its own. It kerns B, which it lacks, as BMFont may.
337    pub(crate) const FONT: &str = r#"{ "version": 1,
338        "face": "Tiny", "size": -6, "line_height": 6, "base": 5,
339        "atlas": "atlas/fonts.kbj", "sprite": "fonts/tiny",
340        "glyphs": [
341          { "id": 32, "x": 0, "y": 0, "advance": 2 },
342          { "id": 65, "frame": 0, "x": 0, "y": 1, "advance": 4 },
343          { "id": 86, "frame": 1, "x": 0, "y": 1, "advance": 4 },
344          { "id": 105, "frame": 2, "x": 1, "y": 1, "advance": 3 } ],
345        "kerning": [ [65, 66, -1], [65, 86, -1], [66, 86, -1], [86, 65, -1] ],
346        "fallback": { "frame": 3, "x": 0, "y": 0, "advance": 4 } }"#;
347
348    #[test]
349    fn its_glyphs_and_kerning_are_found_by_character() {
350        let font = decoded(FONT).expect("a font");
351        assert_eq!(
352            (font.face(), font.size(), font.line_height(), font.base()),
353            ("Tiny", -6, 6, 5)
354        );
355        assert_eq!(
356            (font.atlas(), font.sprite()),
357            ("atlas/fonts.kbj", "fonts/tiny")
358        );
359        let a = font.glyph('A').expect("A");
360        assert_eq!(
361            (a.frame(), a.offset(), a.advance()),
362            (Some(0), IVec2::new(0, 1), 4)
363        );
364        let space = font.glyph(' ').expect("a space");
365        assert_eq!((space.frame(), space.advance()), (None, 2));
366        assert_eq!(font.glyph('i').expect("i").offset(), IVec2::new(1, 1));
367        assert!(font.glyph('B').is_none());
368        assert!(font.glyph('\0').is_none());
369        assert_eq!(font.fallback().frame(), Some(3));
370        assert_eq!(font.kerning('A', 'V'), -1);
371        assert_eq!(font.kerning('A', 'B'), -1, "a character it lacks");
372        assert_eq!(font.kerning('V', 'A'), -1);
373        assert_eq!(font.kerning('A', 'A'), 0);
374        assert_eq!(font.kerning('V', 'i'), 0);
375        assert_eq!(font.last_frame, 3);
376    }
377
378    #[test]
379    fn an_atlas_that_is_not_an_atlas_file_s_path_is_refused() {
380        for path in [
381            "atlas/../fonts.kbj",
382            "atlas/fonts.qoi",
383            "Atlas/fonts.kbj",
384            "/atlas/fonts.kbj",
385        ] {
386            let text = FONT.replacen("atlas/fonts.kbj", path, 1);
387            assert_eq!(
388                decoded(&text),
389                Err(AssetError::Invalid(format!(
390                    "its atlas, `{path}`, is not the path of an atlas file"
391                ))),
392                "{path}"
393            );
394        }
395        // And the file itself is checked by the codec.
396        let text = FONT.replacen(r#""version": 1"#, r#""version": 2"#, 1);
397        assert!(matches!(
398            decoded(&text),
399            Err(AssetError::Decode(nadir_codec::CodecError::Font { ref at, .. })) if at == "version"
400        ));
401    }
402
403    #[test]
404    fn metrics_past_32767_either_way_are_refused_and_up_to_it_taken() {
405        let cases = [
406            (r#""advance": 4 },"#, r#""advance": 32768 },"#),
407            (r#""x": 1, "y": 1"#, r#""x": -32768, "y": 1"#),
408            (
409                r#""x": 0, "y": 0, "advance": 4 }"#,
410                r#""x": 0, "y": 40000, "advance": 4 }"#,
411            ),
412            ("[65, 86, -1]", "[65, 86, -32768]"),
413            (r#""line_height": 6"#, r#""line_height": 32768"#),
414        ];
415        for (from, to) in cases {
416            let text = FONT.replacen(from, to, 1);
417            assert_ne!(text, FONT, "{from}");
418            assert!(
419                matches!(decoded(&text), Err(AssetError::Invalid(_))),
420                "{to}: {:?}",
421                decoded(&text)
422            );
423            let edge = text.replace("32768", "32767").replace("40000", "-32767");
424            assert!(decoded(&edge).is_ok(), "{edge}");
425        }
426    }
427
428    /// An atlas file whose sprite `fonts/tiny` has `frames` frames.
429    pub(crate) fn atlas(frames: usize) -> Atlas {
430        let frame =
431            r#"{ "page": 0, "x": 0, "y": 0, "w": 3, "h": 4, "ox": 0, "oy": 0, "sw": 3, "sh": 4 }"#;
432        let frames = vec![frame; frames].join(", ");
433        let text = format!(
434            r#"{{ "version": 2,
435                "pages": [ {{ "path": "atlas/fonts_0.qoi", "w": 16, "h": 8 }} ],
436                "sprites": [ {{ "name": "fonts/tiny", "frames": [ {frames} ], "pivot": [0.0, 0.0] }} ] }}"#
437        );
438        Atlas::decode(
439            &kbj(&text),
440            &DecodeCtx::new("atlas/fonts.kbj", Limits::default()),
441        )
442        .expect("an atlas")
443    }
444
445    #[test]
446    fn the_atlas_must_have_its_sprite_with_every_frame_its_glyphs_name() {
447        let font = decoded(FONT).expect("a font");
448        assert!(font.sprite_in(&atlas(4)).is_ok());
449        assert_eq!(font.sprite_in(&atlas(3)), Err(Misfit::TooFewFrames(3)));
450        assert_eq!(
451            font.misfit(Misfit::TooFewFrames(3)),
452            "its glyphs name frame 3 of the sprite `fonts/tiny`, which has 3"
453        );
454        let other = decoded(&FONT.replacen("fonts/tiny", "fonts/big", 1)).expect("a font");
455        assert_eq!(other.sprite_in(&atlas(4)), Err(Misfit::NoSprite));
456        assert_eq!(
457            other.misfit(Misfit::NoSprite),
458            "its atlas has no sprite `fonts/big`"
459        );
460    }
461
462    #[test]
463    fn it_is_made_with_nothing_in_its_context() {
464        let font = decoded(FONT).expect("a font");
465        assert_eq!(
466            Font::finalize(font.clone(), &mut FinalizeCtx::new()),
467            Ok(font)
468        );
469    }
470}