Skip to content

Bitmap Font Generator — C source

Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/* bitmap-font-generator — charset parser + BMFont TEXT emitter. C port of
 * the pure half of src/lib/bitmap-font.ts: preset names, decimal and U+HEX
 * range specs in, sorted codepoints out; BMFont TEXT documents out. The
 * rasterizing half (opentype.js) has no C browser story and the island owns
 * it anyway — pure charset/font-geometry only. Caller frees CharsetResult
 * fields and the fnt_text return value. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

/* Max valid Unicode scalar value. */
enum { MAX_CODEPOINT = 0x10ffff };

/* ---- error helpers (the TS FontError twin; 'invalid' is the only code) ---- */

static char *errorf(const char *fmt, const char *token) {
    char *msg = malloc(strlen(fmt) + strlen(token) + 1);
    sprintf(msg, fmt, token);
    return msg;
}

/* ---- small growable string ---- */

typedef struct { char *buf; size_t len, cap; } Str;

static void str_reserve(Str *s, size_t need) {
    if (need >= s->cap) {
        size_t cap = s->cap ? s->cap : 64;
        while (need >= cap) cap *= 2;
        s->buf = realloc(s->buf, cap);
        s->cap = cap;
    }
}

static void str_app(Str *s, const char *t) {
    size_t tl = strlen(t);
    str_reserve(s, s->len + tl);
    memcpy(s->buf + s->len, t, tl + 1);
    s->len += tl;
}

/* ---- charset parsing ---- */

/* Inclusive [lo, hi] codepoint bounds from one comma item. */
typedef struct { unsigned long long lo, hi; } Bounds;

/* Digits only, in the given radix, saturating at ULLONG_MAX so oversized
 * digit strings still land in the "outside Unicode" branch (the TS parseInt
 * overflows to Infinity, which trips the same check). */
static int parse_u64(const char *s, size_t n, int radix, unsigned long long *out) {
    if (n == 0) return 0;
    unsigned long long v = 0;
    for (size_t i = 0; i < n; i++) {
        unsigned d;
        char c = s[i];
        if (c >= '0' && c <= '9') d = (unsigned)(c - '0');
        else if (radix == 16 && c >= 'a' && c <= 'f') d = (unsigned)(c - 'a') + 10;
        else if (radix == 16 && c >= 'A' && c <= 'F') d = (unsigned)(c - 'A') + 10;
        else return 0;
        if (v > (0xffffffffffffffffULL - d) / (unsigned)radix) v = 0xffffffffffffffffULL;
        else v = v * (unsigned)radix + d;
    }
    *out = v;
    return 1;
}

/* One comma item → inclusive bounds, or 0 with a malloc'd error message.
 * The TS lib anchors two regexes here; this is the same grammar hand-rolled:
 * hex form U+HEX or U+HEX-HEX (end may drop the U+ prefix), decimal N or
 * N-N. Neither radix allows '-' inside a number, so the split is safe. */
static int parse_token(const char *token, Bounds *out, char **err) {
    int hex = 0;
    const char *body = token;
    if ((body[0] == 'u' || body[0] == 'U') && body[1] == '+') { hex = 1; body += 2; }
    const char *dash = strchr(body, '-');
    size_t lo_len = dash ? (size_t)(dash - body) : strlen(body);
    unsigned long long lo, hi;
    if (!parse_u64(body, lo_len, hex ? 16 : 10, &lo)) {
        *err = errorf("\"%s\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.", token);
        return 0;
    }
    if (dash) {
        const char *hi_raw = dash + 1;
        if (!parse_u64(hi_raw, strlen(hi_raw), hex ? 16 : 10, &hi)) {
            *err = errorf("\"%s\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.", token);
            return 0;
        }
    } else {
        hi = lo;
    }
    if (lo > MAX_CODEPOINT || hi > MAX_CODEPOINT) {
        *err = errorf("\"%s\" is outside Unicode (max U+10FFFF).", token);
        return 0;
    }
    if (lo > hi) {
        *err = errorf("\"%s\" runs backwards — put the smaller codepoint first.", token);
        return 0;
    }
    out->lo = lo;
    out->hi = hi;
    return 1;
}

static int bounds_cmp(const void *a, const void *b) {
    const Bounds *x = a, *y = b;
    if (x->lo != y->lo) return x->lo < y->lo ? -1 : 1;
    return 0;
}

/* Result of parse_charset: sorted, deduped codepoints, or an error message. */
typedef struct {
    int ok;
    unsigned int *cps;  /* malloc'd; free() when ok */
    size_t n;
    char *error;        /* malloc'd; free() when !ok */
} CharsetResult;

/* Expand sorted bounds into a deduped codepoint list (overlapping and
 * duplicate items merge because the bounds are processed in lo order). */
static void push_cp(CharsetResult *res, unsigned long long cp) {
    if (res->n == 0 || res->cps[res->n - 1] != cp) {
        res->cps = realloc(res->cps, (res->n + 1) * sizeof(unsigned int));
        res->cps[res->n++] = (unsigned int)cp;
    }
}

/* Parse a charset spec into a deduped, sorted codepoint list.
 *
 * Grammar (whitespace-tolerant, comma-separated items): `ascii`, `latin1`,
 * `digits` presets; or items `A` / `A-B` where each side is decimal (`65`,
 * `65-90`) or `U+HEX` (`U+41`, `U+4E00-9FFF`; the range end may drop the
 * `U+` prefix when the start carries it). */
CharsetResult parse_charset(const char *spec) {
    CharsetResult res = {0};
    const char *p = spec;
    while (*p && isspace((unsigned char)*p)) p++;
    size_t len = strlen(p);
    while (len && isspace((unsigned char)p[len - 1])) len--;
    if (len == 0) {
        res.error = errorf("Charset is empty — name a preset or list codepoint ranges.", "");
        return res;
    }
    char *trimmed = malloc(len + 1);
    memcpy(trimmed, p, len);
    trimmed[len] = '\0';

    /* Named charsets, as documented in the tool docs. */
    if (strcasecmp(trimmed, "ascii") == 0) {
        res.ok = 1;
        for (unsigned long long cp = 32; cp <= 126; cp++) push_cp(&res, cp);
    } else if (strcasecmp(trimmed, "latin1") == 0) {
        res.ok = 1;
        for (unsigned long long cp = 32; cp <= 126; cp++) push_cp(&res, cp);
        for (unsigned long long cp = 160; cp <= 255; cp++) push_cp(&res, cp);
    } else if (strcasecmp(trimmed, "digits") == 0) {
        res.ok = 1;
        for (unsigned long long cp = 48; cp <= 57; cp++) push_cp(&res, cp);
    } else {
        Bounds *bnds = NULL;
        size_t nb = 0, cap = 0;
        int bad = 0;
        for (char *cursor = trimmed; cursor && !bad; ) {
            char *comma = strchr(cursor, ',');
            size_t tl = comma ? (size_t)(comma - cursor) : strlen(cursor);
            char *token = malloc(tl + 1);
            size_t tn = 0;
            for (size_t i = 0; i < tl; i++)
                if (!isspace((unsigned char)cursor[i])) token[tn++] = cursor[i];
            token[tn] = '\0';
            Bounds b;
            char *err = NULL;
            if (parse_token(token, &b, &err)) {
                if (nb == cap) { cap = cap ? cap * 2 : 8; bnds = realloc(bnds, cap * sizeof(Bounds)); }
                bnds[nb++] = b;
            } else {
                res.error = err;
                bad = 1;
            }
            free(token);
            cursor = comma ? comma + 1 : NULL;
        }
        if (!bad) {
            qsort(bnds, nb, sizeof(Bounds), bounds_cmp);
            res.ok = 1;
            unsigned long long covered = 0;
            for (size_t i = 0; i < nb; i++) {
                unsigned long long lo = bnds[i].lo;
                if (i > 0 && lo <= covered) lo = covered + 1;
                for (unsigned long long cp = lo; cp <= bnds[i].hi; cp++) push_cp(&res, cp);
                if (bnds[i].hi > covered || i == 0) covered = bnds[i].hi;
            }
        }
        free(bnds);
    }
    free(trimmed);
    return res;
}

/* ---- BMFont TEXT emitter ---- */

/* One char entry in the emitted .fnt (geometry already scaled to pixels). */
typedef struct {
    int codepoint, x, y, w, h, xoffset, yoffset, xadvance;
} FntChar;

/* One kerning pair in the emitted .fnt (pixel amount, may be negative). */
typedef struct { int first, second, amount; } FntKerning;

/* Mirrors the TS info block: padding is broadcast to all four sides. */
typedef struct { const char *face; int size, padding; } FntInfo;

/* Mirrors the TS common block. */
typedef struct { int line_height, base, scale_w, scale_h; } FntCommon;

/* Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
 * Returns a malloc'd string the caller frees. */
char *fnt_text(const FntInfo *info, const FntCommon *common,
               const FntChar *chars, size_t n_chars,
               const FntKerning *kernings, size_t n_kernings) {
    Str s = {0};
    char buf[512];
    int pad = info->padding;
    snprintf(buf, sizeof buf,
             "info face=\"%s\" size=%d bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1"
             " padding=%d,%d,%d,%d spacing=1,1 outline=0",
             info->face, info->size, pad, pad, pad, pad);
    str_app(&s, buf);
    snprintf(buf, sizeof buf,
             "\ncommon lineHeight=%d base=%d scaleW=%d scaleH=%d pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
             common->line_height, common->base, common->scale_w, common->scale_h);
    str_app(&s, buf);
    str_app(&s, "\npage id=0 file=\"sheet.png\"");
    snprintf(buf, sizeof buf, "\nchars count=%zu", n_chars);
    str_app(&s, buf);
    for (size_t i = 0; i < n_chars; i++) {
        const FntChar *c = &chars[i];
        snprintf(buf, sizeof buf,
                 "\nchar id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d page=0 chnl=15",
                 c->codepoint, c->x, c->y, c->w, c->h, c->xoffset, c->yoffset, c->xadvance);
        str_app(&s, buf);
    }
    snprintf(buf, sizeof buf, "\nkernings count=%zu", n_kernings);
    str_app(&s, buf);
    for (size_t i = 0; i < n_kernings; i++) {
        const FntKerning *k = &kernings[i];
        snprintf(buf, sizeof buf, "\nkerning first=%d second=%d amount=%d", k->first, k->second, k->amount);
        str_app(&s, buf);
    }
    return s.buf;
}

/* Example:
 *   FntInfo info = {"TestFace", 32, 1};
 *   FntCommon common = {38, 29, 128, 128};
 *   FntChar chars[] = {{65, 0, 0, 34, 36, 0, 0, 36}};
 *   char *fnt = fnt_text(&info, &common, chars, 1, NULL, 0);
 *   printf("%s\n", fnt);
 *   // info face="TestFace" size=32 ... padding=1,1,1,1 spacing=1,1 outline=0
 *   // common lineHeight=38 base=29 scaleW=128 scaleH=128 pages=1 ...
 *   // page id=0 file="sheet.png"
 *   // chars count=1
 *   // char id=65 x=0 y=0 width=34 height=36 xoffset=0 yoffset=0 xadvance=36 page=0 chnl=15
 *   // kernings count=0
 *   free(fnt); */

/* ---- demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts) ---- */

static void print_list(const char *label, CharsetResult r) {
    printf("%s len=%zu", label, r.n);
    for (size_t i = 0; i < r.n; i++) printf(" %u", r.cps[i]);
    printf("\n");
    free(r.cps);
}

static void print_shape(const char *label, CharsetResult r, size_t i0, size_t i94, size_t i95, size_t i190) {
    printf("%s len=%zu c0=%u c94=%u c95=%u c190=%u\n", label, r.n, r.cps[i0], r.cps[i94], r.cps[i95], r.cps[i190]);
    free(r.cps);
}

static void print_ends(const char *label, CharsetResult r) {
    printf("%s first=%u last=%u len=%zu\n", label, r.cps[0], r.cps[r.n - 1], r.n);
    free(r.cps);
}

static void print_spec(const char *spec, CharsetResult r) {
    if (!r.ok) {
        printf("ERR %s : invalid\n", spec);
        free(r.error);
        return;
    }
    print_list(spec, r);
}

/* Pointer to the start of line `n` (0-based) of a '\n'-joined document. */
static const char *nth_line(const char *s, size_t n) {
    while (n-- > 0) {
        s = strchr(s, '\n');
        if (!s) return "";
        s++;
    }
    return s;
}

int main(void) {
    print_list("ascii", parse_charset("ascii"));
    print_shape("latin1", parse_charset("latin1"), 0, 94, 95, 190);
    print_ends("digits", parse_charset("digits"));
    {
        CharsetResult r = parse_charset("  ASCII ");
        printf("ascii-ws len=%zu\n", r.n);
        free(r.cps);
    }
    {
        CharsetResult r = parse_charset("Latin1");
        printf("latin1-case c95=%u\n", r.cps[95]);
        free(r.cps);
    }
    {
        CharsetResult r = parse_charset("\tDigits\n");
        printf("digits-ws len=%zu\n", r.n);
        free(r.cps);
    }
    {
        CharsetResult r = parse_charset("65-90,97-122");
        printf("dec-ranges first=%u last=%u len=%zu\n", r.cps[0], r.cps[r.n - 1], r.n);
        free(r.cps);
    }
    print_spec("122,65,97", parse_charset("122,65,97"));
    print_spec("65-70,68,65", parse_charset("65-70,68,65"));
    print_spec("U+41", parse_charset("U+41"));
    print_spec("u+41", parse_charset("u+41"));
    print_ends("U+4E00-9FFF", parse_charset("U+4E00-9FFF"));
    print_spec("65,U+42,67-68", parse_charset("65,U+42,67-68"));
    print_spec(" 65 - 67 , U+0041 ", parse_charset(" 65 - 67 , U+0041 "));
    print_spec("0", parse_charset("0"));
    print_spec("U+10FFFF", parse_charset("U+10FFFF"));

    const char *bad[] = {"", "   ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
                         "1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF"};
    for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
        CharsetResult r = parse_charset(bad[i]);
        printf("ERR %s : %s\n", bad[i], r.ok ? "NO-ERROR" : "invalid");
        if (r.ok) free(r.cps); else free(r.error);
    }

    FntInfo info = {"TestFace", 32, 1};
    FntCommon common = {38, 29, 128, 128};
    FntChar chars[] = {
        {65, 0, 0, 34, 36, 0, 0, 36},
        {66, 36, 0, 32, 36, 1, 2, 35},
    };
    FntKerning kernings[] = {{65, 66, -1}};
    printf("fntText\n");
    char *fnt = fnt_text(&info, &common, chars, 2, kernings, 1);
    printf("%s\n", fnt);
    free(fnt);
    FntInfo padded = {"TestFace", 32, 4};
    fnt = fnt_text(&padded, &common, chars, 2, kernings, 1);
    printf("pad %.*s\n", (int)strcspn(fnt, "\n"), fnt);
    free(fnt);
    fnt = fnt_text(&info, &common, chars, 2, NULL, 0);
    size_t lines = 1;
    for (const char *q = fnt; *q; q++) if (*q == '\n') lines++;
    printf("kern0 %s lines=%zu\n", nth_line(fnt, 6), lines);
    free(fnt);
    fnt = fnt_text(&info, &common, NULL, 0, NULL, 0);
    lines = 1;
    for (const char *q = fnt; *q; q++) if (*q == '\n') lines++;
    printf("zerochars lines=%zu\n", lines);
    free(fnt);
    FntChar big[] = {{19968, 0, 0, 32, 32, 0, 0, 32}};
    fnt = fnt_text(&info, &common, big, 1, NULL, 0);
    const char *big_line = nth_line(fnt, 4);
    printf("bigcp %.*s\n", (int)strcspn(big_line, "\n"), big_line);
    free(fnt);
    return 0;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →