gsfnt 0.2.0

Pack a folder of images into BMFont (.fnt) and a merged PNG atlas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use clap::{Parser, ValueEnum};
use image::{open, ImageFormat, Rgba, RgbaImage};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "webp", "gif", "bmp"];

#[derive(Debug, Clone, Copy, ValueEnum)]
enum Align {
    /// Top-aligned within the line box
    Top,
    /// Vertically centered within the line box
    Center,
    /// Bottom-aligned within the line box
    Bottom,
}

impl Align {
    fn box_yoffset(self, line_height: i32, height: i32) -> i32 {
        match self {
            Align::Top => 0,
            Align::Center => (line_height - height) / 2,
            Align::Bottom => line_height - height,
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Align::Top => "top",
            Align::Center => "center",
            Align::Bottom => "bottom",
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum AlignBy {
    /// Align ink when source heights differ (trimmed art), image boxes otherwise
    Auto,
    /// Always align the image boxes
    Box,
    /// Always align the visible ink, ignoring near-transparent edges
    Ink,
}

#[derive(Debug, thiserror::Error)]
enum AppError {
    #[error("input path is not a directory or is unreadable: {0}")]
    InputDir(PathBuf),
    #[error("{0}")]
    Io(#[from] std::io::Error),
    #[error("failed to decode image ({path}): {source}")]
    ImageDecode {
        path: PathBuf,
        source: image::ImageError,
    },
    #[error("failed to encode image: {0}")]
    ImageEncode(#[from] image::ImageError),
    #[error("filename stem `{stem}` has no usable character: {path}")]
    NoChar { stem: String, path: PathBuf },
    #[error("duplicate character U+{id:04X} ({ch}):\n  {a}\n  {b}")]
    DuplicateChar {
        id: u32,
        ch: char,
        a: PathBuf,
        b: PathBuf,
    },
    #[error("no supported images in directory (supported: {exts})")]
    NoImages { exts: String },
    #[error("image width {w} exceeds --max-width {max}: {path}")]
    TooWide {
        path: PathBuf,
        w: u32,
        max: u32,
    },
    #[error("packing failed: glyph width {w} exceeds --max-width {max}")]
    PackTooWide { w: u32, max: u32 },
}

#[derive(Parser, Debug)]
#[command(
    name = "gsfnt",
    about = "Pack images in a directory into a BMFont (.fnt + merged PNG); glyph code point from the first character of each filename stem"
)]
struct Cli {
    /// Directory containing source images
    #[arg(short, long)]
    input: PathBuf,

    /// Output path prefix (no extension); writes <prefix>.fnt and <prefix>.png
    #[arg(short, long)]
    output: PathBuf,

    /// Maximum atlas row width in pixels (shelf packing)
    #[arg(long, default_value_t = 4096)]
    max_width: u32,

    /// Vertical glyph alignment within the line box (top / center / bottom)
    #[arg(long, value_enum, default_value_t = Align::Bottom)]
    align: Align,

    /// What the alignment is measured against (auto / box / ink)
    #[arg(long, value_enum, default_value_t = AlignBy::Auto)]
    align_by: AlignBy,

    /// Alpha value at or above which a pixel counts as ink (1-255)
    #[arg(long, default_value_t = 128)]
    ink_threshold: u8,

    /// Transparent gap in pixels between glyphs in the atlas
    #[arg(long, default_value_t = 1)]
    padding: u32,
}

struct GlyphEntry {
    path: PathBuf,
    id: u32,
    ch: char,
    width: u32,
    height: u32,
    /// First and last row (inclusive) holding ink, measured with `--ink-threshold`
    ink_top: u32,
    ink_bottom: u32,
    rgba: RgbaImage,
}

struct Placed {
    glyph: GlyphEntry,
    x: u32,
    y: u32,
    yoffset: i32,
}

fn is_image_file(path: &Path) -> bool {
    path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| {
            let e = e.to_ascii_lowercase();
            IMAGE_EXTS.iter().any(|&ext| ext == e)
        })
        .unwrap_or(false)
}

fn collect_images(dir: &Path) -> Result<Vec<PathBuf>, AppError> {
    if !dir.is_dir() {
        return Err(AppError::InputDir(dir.to_path_buf()));
    }
    let mut paths: Vec<PathBuf> = fs::read_dir(dir)?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.is_file() && is_image_file(p))
        .collect();
    paths.sort_by(|a, b| {
        a.file_name()
            .unwrap_or_default()
            .cmp(b.file_name().unwrap_or_default())
    });
    Ok(paths)
}

/// Maps the first Unicode scalar in the filename stem (without extension) to the glyph id.
fn stem_char(path: &Path) -> Result<(char, u32), AppError> {
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    let ch = stem.chars().next().ok_or_else(|| AppError::NoChar {
        stem: stem.to_string(),
        path: path.to_path_buf(),
    })?;
    Ok((ch, ch as u32))
}

/// First and last row holding a pixel with alpha >= `threshold`.
fn ink_rows(img: &RgbaImage, threshold: u8) -> Option<(u32, u32)> {
    let (w, h) = img.dimensions();
    let mut top = None;
    let mut bottom = 0u32;
    for y in 0..h {
        let inked = (0..w).any(|x| img.get_pixel(x, y)[3] >= threshold);
        if inked {
            top.get_or_insert(y);
            bottom = y;
        }
    }
    top.map(|t| (t, bottom))
}

/// Falls back to any non-transparent pixel, then to the whole box, so a faint or
/// blank glyph never collapses the metrics.
fn glyph_ink(img: &RgbaImage, threshold: u8) -> (u32, u32) {
    ink_rows(img, threshold)
        .or_else(|| ink_rows(img, 1))
        .unwrap_or((0, img.height().saturating_sub(1)))
}

fn load_glyph(path: &Path, ink_threshold: u8) -> Result<GlyphEntry, AppError> {
    let (ch, id) = stem_char(path)?;
    let img = open(path).map_err(|source| AppError::ImageDecode {
        path: path.to_path_buf(),
        source,
    })?;
    let rgba = img.to_rgba8();
    let (width, height) = rgba.dimensions();
    let (ink_top, ink_bottom) = glyph_ink(&rgba, ink_threshold);
    Ok(GlyphEntry {
        path: path.to_path_buf(),
        id,
        ch,
        width,
        height,
        ink_top,
        ink_bottom,
        rgba,
    })
}

/// Shifts every glyph so their ink lines up, instead of their image boxes. The
/// maximum is used as the anchor so no offset comes out negative.
fn ink_yoffsets(entries: &[GlyphEntry], align: Align) -> Vec<i32> {
    match align {
        Align::Top => {
            let anchor = entries.iter().map(|e| e.ink_top).max().unwrap_or(0) as i32;
            entries.iter().map(|e| anchor - e.ink_top as i32).collect()
        }
        Align::Bottom => {
            let anchor = entries.iter().map(|e| e.ink_bottom).max().unwrap_or(0) as i32;
            entries
                .iter()
                .map(|e| anchor - e.ink_bottom as i32)
                .collect()
        }
        Align::Center => {
            // Doubled centers keep the halving down to a single rounding step.
            let center = |e: &GlyphEntry| (e.ink_top + e.ink_bottom) as i32;
            let anchor = entries.iter().map(center).max().unwrap_or(0);
            entries
                .iter()
                .map(|e| ((anchor - center(e)) as f32 / 2.0).round() as i32)
                .collect()
        }
    }
}

/// Shelf packing: returns each rect's (x, y) in atlas space and the atlas size.
/// `padding` transparent pixels are left between neighbours so that scaled
/// sampling cannot bleed one glyph into the next.
fn shelf_pack(
    sizes: &[(u32, u32)],
    max_width: u32,
    padding: u32,
) -> Result<(Vec<(u32, u32)>, u32, u32), AppError> {
    let mut placements = Vec::with_capacity(sizes.len());
    let mut x = 0u32;
    let mut y = 0u32;
    let mut row_h = 0u32;
    let mut atlas_w = 0u32;
    let mut atlas_h = 0u32;

    for &(w, h) in sizes {
        if w > max_width {
            return Err(AppError::PackTooWide { w, max: max_width });
        }
        if x > 0 && x + w > max_width {
            y += row_h + padding;
            row_h = 0;
            x = 0;
        }
        placements.push((x, y));
        row_h = row_h.max(h);
        atlas_w = atlas_w.max(x + w);
        atlas_h = atlas_h.max(y + h);
        x += w + padding;
    }
    atlas_h = atlas_h.max(y + row_h);
    Ok((placements, atlas_w, atlas_h))
}

fn blit(dst: &mut RgbaImage, src: &RgbaImage, dx: u32, dy: u32) {
    for (sx, sy, p) in src.enumerate_pixels() {
        dst.put_pixel(dx + sx, dy + sy, *p);
    }
}

fn write_fnt(
    path: &Path,
    face: &str,
    png_file_name: &str,
    line_height: i32,
    base: i32,
    atlas_w: u32,
    atlas_h: u32,
    padding: u32,
    glyphs: &[Placed],
) -> Result<(), AppError> {
    let mut lines = String::new();
    lines.push_str(&format!(
        "info face=\"{face}\" size={line_height} bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing={padding},{padding} outline=0\n"
    ));
    // All four channels must be 0 ("channel holds glyph data") or Godot treats the
    // atlas as monochrome-plus-outline and rebuilds it from the red channel alone,
    // which turns every colored font white.
    lines.push_str(&format!(
        "common lineHeight={line_height} base={base} scaleW={atlas_w} scaleH={atlas_h} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0\n"
    ));
    lines.push_str(&format!("page id=0 file=\"{png_file_name}\"\n"));
    lines.push_str(&format!("chars count={}\n", glyphs.len()));

    for p in glyphs {
        let g = &p.glyph;
        let xo = 0i32;
        let xa = g.width as i32;
        lines.push_str(&format!(
            "char id={} x={} y={} width={} height={} xoffset={} yoffset={} xadvance={} page=0 chnl=15\n",
            g.id, p.x, p.y, g.width, g.height, xo, p.yoffset, xa
        ));
    }
    lines.push_str("kernings count=0\n");
    fs::write(path, lines)?;
    Ok(())
}

fn main() -> Result<(), AppError> {
    let cli = Cli::parse();
    let paths = collect_images(&cli.input)?;
    if paths.is_empty() {
        return Err(AppError::NoImages {
            exts: IMAGE_EXTS.join(", "),
        });
    }

    let ink_threshold = cli.ink_threshold.max(1);
    let mut seen: HashMap<u32, PathBuf> = HashMap::new();
    let mut entries = Vec::new();
    for p in &paths {
        let g = load_glyph(p, ink_threshold)?;
        if let Some(prev) = seen.insert(g.id, p.clone()) {
            return Err(AppError::DuplicateChar {
                id: g.id,
                ch: g.ch,
                a: prev,
                b: p.clone(),
            });
        }
        if g.width > cli.max_width {
            return Err(AppError::TooWide {
                path: g.path.clone(),
                w: g.width,
                max: cli.max_width,
            });
        }
        entries.push(g);
    }

    let sizes: Vec<(u32, u32)> = entries.iter().map(|e| (e.width, e.height)).collect();
    let (placements, atlas_w, atlas_h) = shelf_pack(&sizes, cli.max_width, cli.padding)?;

    let line_height = entries.iter().map(|e| e.height).max().unwrap_or(1);
    let base = line_height;

    // Differing source heights mean the art was trimmed to its alpha bounds, and a
    // single near-invisible antialiased row is then enough to throw the box-based
    // offset off by a pixel. Measuring the ink avoids that.
    let uniform_height = entries.iter().all(|e| e.height == line_height);
    let use_ink = match cli.align_by {
        AlignBy::Box => false,
        AlignBy::Ink => true,
        AlignBy::Auto => !uniform_height,
    };
    let yoffsets: Vec<i32> = if use_ink {
        ink_yoffsets(&entries, cli.align)
    } else {
        entries
            .iter()
            .map(|e| cli.align.box_yoffset(line_height as i32, e.height as i32))
            .collect()
    };
    eprintln!(
        "Aligning glyph {} to the {} (source heights {})",
        if use_ink { "ink" } else { "boxes" },
        cli.align.as_str(),
        if uniform_height {
            "all equal"
        } else {
            "differ"
        }
    );

    let mut atlas = RgbaImage::from_pixel(atlas_w, atlas_h, Rgba([0, 0, 0, 0]));
    let mut placed: Vec<Placed> = Vec::new();
    for ((mut g, &(px, py)), yoffset) in entries
        .into_iter()
        .zip(placements.iter())
        .zip(yoffsets.into_iter())
    {
        blit(&mut atlas, &g.rgba, px, py);
        g.rgba = RgbaImage::new(1, 1);
        placed.push(Placed {
            glyph: g,
            x: px,
            y: py,
            yoffset,
        });
    }

    let out_fnt = if cli.output.extension().is_some_and(|e| e.eq_ignore_ascii_case("fnt")) {
        cli.output.clone()
    } else {
        cli.output.with_extension("fnt")
    };
    let out_png = out_fnt.with_extension("png");
    let png_file_name = out_png
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("atlas.png")
        .to_string();

    if let Some(parent) = out_fnt.parent() {
        fs::create_dir_all(parent)?;
    }

    atlas.save_with_format(&out_png, ImageFormat::Png)?;

    let face = out_fnt
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("font");

    write_fnt(
        &out_fnt,
        face,
        &png_file_name,
        line_height as i32,
        base as i32,
        atlas_w,
        atlas_h,
        cli.padding,
        &placed,
    )?;

    eprintln!("Wrote {}", out_fnt.display());
    eprintln!("Wrote {}", out_png.display());
    Ok(())
}