Skip to content

Bitmap Font Generator — Kotlin source

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

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

// bitmap-font-generator — charset parser + BMFont TEXT emitter. Kotlin 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 Kotlin browser story and the
// island owns it anyway — pure charset/font-geometry only.

// Max valid Unicode scalar value.
const val MAX_CODEPOINT = 0x10ffff

// The Kotlin twin of the TS FontError class ('invalid' is the only code).
class FontError(message: String) : RuntimeException(message) {
    val code = "invalid"
}

// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
private val RE_HEX = Regex("""^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$""", RegexOption.IGNORE_CASE)
// Decimal form: N or N-N.
private val RE_DEC = Regex("""^(\d+)(?:-(\d+))?$""")

/** Inclusive [lo, hi] codepoint range expanded to a sorted list. */
private fun codepointRange(lo: Int, hi: Int): List<Int> = (lo..hi).toList()

/** 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). */
fun parseCharset(spec: String): List<Int> {
    val trimmed = spec.trim()
    if (trimmed.isEmpty()) {
        throw FontError("Charset is empty — name a preset or list codepoint ranges.")
    }
    when (trimmed.lowercase()) {
        "ascii" -> return codepointRange(32, 126)
        "latin1" -> return codepointRange(32, 126) + codepointRange(160, 255)
        "digits" -> return codepointRange(48, 57)
    }

    val seen = sortedSetOf<Int>()
    for (raw in trimmed.split(',')) {
        val token = raw.trim().replace(Regex("""\s+"""), "")
        val (lo, hi) = parseToken(token)
        seen.addAll(lo.toInt()..hi.toInt())
    }
    return seen.toList()
}

/** One comma item → inclusive bounds, or FontError when garbage. The TS lib
 *  anchors two regexes here; the same two regexes run in this port. */
private fun parseToken(token: String): Pair<Long, Long> {
    val hex = RE_HEX.matchEntire(token)
    val dec = RE_DEC.matchEntire(token)
    val m = hex ?: dec
        ?: throw FontError("\"$token\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.")
    val radix = if (hex != null) 16 else 10
    // The regex validated plain digits, so a NumberFormatException here can
    // only be an overflow — the TS parseInt's Infinity, i.e. outside Unicode.
    val lo = parseLongOrMax(m.groupValues[1], radix)
    val hi = if (m.groupValues[2].isNotEmpty()) parseLongOrMax(m.groupValues[2], radix) else lo
    if (lo > MAX_CODEPOINT || hi > MAX_CODEPOINT) {
        throw FontError("\"$token\" is outside Unicode (max U+10FFFF).")
    }
    if (lo > hi) {
        throw FontError("\"$token\" runs backwards — put the smaller codepoint first.")
    }
    return lo to hi
}

private fun parseLongOrMax(digits: String, radix: Int): Long =
    try {
        digits.toLong(radix)
    } catch (e: NumberFormatException) {
        Long.MAX_VALUE
    }

/** One char entry in the emitted .fnt (geometry already scaled to pixels). */
data class FntChar(
    val codepoint: Int,
    val x: Int,
    val y: Int,
    val w: Int,
    val h: Int,
    val xoffset: Int,
    val yoffset: Int,
    val xadvance: Int,
)

/** One kerning pair in the emitted .fnt (pixel amount, may be negative). */
data class FntKerning(val first: Int, val second: Int, val amount: Int)

/** Mirrors the TS info block: padding is broadcast to all four sides. */
data class FntInfo(val face: String, val size: Int, val padding: Int)

/** Mirrors the TS common block. */
data class FntCommon(val lineHeight: Int, val base: Int, val scaleW: Int, val scaleH: Int)

/** Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png"). */
fun fntText(
    info: FntInfo,
    common: FntCommon,
    chars: List<FntChar>,
    kernings: List<FntKerning>,
): String {
    val p = info.padding
    val lines = mutableListOf(
        "info face=\"${info.face}\" size=${info.size} bold=0 italic=0 charset=\"\" unicode=1" +
            " stretchH=100 smooth=1 aa=1 padding=$p,$p,$p,$p spacing=1,1 outline=0",
        "common lineHeight=${common.lineHeight} base=${common.base} scaleW=${common.scaleW}" +
            " scaleH=${common.scaleH} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
        "page id=0 file=\"sheet.png\"",
        "chars count=${chars.size}",
    )
    for (c in chars) {
        lines +=
            "char id=${c.codepoint} x=${c.x} y=${c.y} width=${c.w} height=${c.h}" +
                " xoffset=${c.xoffset} yoffset=${c.yoffset} xadvance=${c.xadvance} page=0 chnl=15"
    }
    lines += "kernings count=${kernings.size}"
    for (k in kernings) lines += "kerning first=${k.first} second=${k.second} amount=${k.amount}"
    return lines.joinToString("\n")
}

// Example:
//   val info = FntInfo("TestFace", 32, 1)
//   val common = FntCommon(38, 29, 128, 128)
//   println(fntText(info, common, emptyList(), emptyList()))
//   // 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=0
//   // kernings count=0

private fun joinCps(label: String, cps: List<Int>): String = buildString {
    append(label); append(" len="); append(cps.size)
    for (cp in cps) { append(' '); append(cp) }
}

private fun printSpec(spec: String) = println(joinCps(spec, parseCharset(spec)))

/** Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts). */
fun main() {
    println(joinCps("ascii", parseCharset("ascii")))
    val latin1 = parseCharset("latin1")
    println("latin1 len=${latin1.size} c0=${latin1[0]} c94=${latin1[94]} c95=${latin1[95]} c190=${latin1[190]}")
    val digits = parseCharset("digits")
    println("digits first=${digits.first()} last=${digits.last()} len=${digits.size}")
    println("ascii-ws len=${parseCharset("  ASCII ").size}")
    println("latin1-case c95=${parseCharset("Latin1")[95]}")
    println("digits-ws len=${parseCharset("\tDigits\n").size}")
    val decRanges = parseCharset("65-90,97-122")
    println("dec-ranges first=${decRanges.first()} last=${decRanges.last()} len=${decRanges.size}")
    printSpec("122,65,97")
    printSpec("65-70,68,65")
    printSpec("U+41")
    printSpec("u+41")
    val hexRange = parseCharset("U+4E00-9FFF")
    println("U+4E00-9FFF first=${hexRange.first()} last=${hexRange.last()} len=${hexRange.size}")
    printSpec("65,U+42,67-68")
    printSpec(" 65 - 67 , U+0041 ")
    printSpec("0")
    printSpec("U+10FFFF")

    for (spec in listOf("", "   ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
            "1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF")) {
        try {
            printSpec(spec)
            println("ERR $spec : NO-ERROR")
        } catch (e: FontError) {
            println("ERR $spec : ${e.code}")
        }
    }

    val info = FntInfo("TestFace", 32, 1)
    val common = FntCommon(38, 29, 128, 128)
    val chars = listOf(
        FntChar(65, 0, 0, 34, 36, 0, 0, 36),
        FntChar(66, 36, 0, 32, 36, 1, 2, 35),
    )
    val kernings = listOf(FntKerning(65, 66, -1))

    println("fntText")
    println(fntText(info, common, chars, kernings))
    println("pad " + fntText(FntInfo("TestFace", 32, 4), common, chars, kernings).split("\n")[0])
    val noKern = fntText(info, common, chars, emptyList()).split("\n")
    println("kern0 ${noKern[6]} lines=${noKern.size}")
    println("zerochars lines=${fntText(info, common, emptyList(), emptyList()).split("\n").size}")
    println("bigcp " + fntText(info, common, listOf(FntChar(19968, 0, 0, 32, 32, 0, 0, 32)), emptyList()).split("\n")[4])
}

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 →