Bitmap Font Generator — Ruby source
Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.
This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# bitmap-font-generator — charset parser + BMFont TEXT emitter. Ruby 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 Ruby browser story and the island
# owns it anyway — pure charset/font-geometry only.
# Max valid Unicode scalar value.
MAX_CODEPOINT = 0x10FFFF
# The Ruby twin of the TS FontError class ('invalid' is the only code).
class FontError < StandardError
attr_reader :code
def initialize(message)
super
@code = 'invalid'
end
end
# Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
RE_HEX = /\Au\+([0-9a-f]+)(?:-([0-9a-f]+))?\z/i
# Decimal form: N or N-N.
RE_DEC = /\A(\d+)(?:-(\d+))?\z/
# Inclusive [lo, hi] codepoint range expanded to a sorted list.
def codepoint_range(lo, hi)
(lo..hi).to_a
end
# 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).
def parse_charset(spec)
trimmed = spec.strip
raise FontError, 'Charset is empty — name a preset or list codepoint ranges.' if trimmed.empty?
# Named charsets, as documented in the tool docs.
case trimmed.downcase
when 'ascii' then return codepoint_range(32, 126)
when 'latin1' then return codepoint_range(32, 126) + codepoint_range(160, 255)
when 'digits' then return codepoint_range(48, 57)
end
seen = []
trimmed.split(',').each do |raw|
token = raw.strip.gsub(/\s+/, '')
lo, hi = parse_token(token)
seen.concat(lo.upto(hi).to_a)
end
seen.uniq.sort
end
# One comma item → inclusive bounds, or FontError when garbage. The TS lib
# anchors two regexes here; the same two regexes run in this port. Ruby ints
# are arbitrary-precision, so an oversized digit string simply lands in the
# "outside Unicode" branch like the TS parseInt's Infinity does.
def parse_token(token)
m = RE_HEX.match(token) || RE_DEC.match(token)
raise FontError, "\"#{token}\" is not a codepoint or range — use 65-90 or U+4E00-9FFF." unless m
radix = RE_HEX.match?(token) ? 16 : 10
lo = m[1].to_i(radix)
hi = m[2] ? m[2].to_i(radix) : lo
raise FontError, "\"#{token}\" is outside Unicode (max U+10FFFF)." if lo > MAX_CODEPOINT || hi > MAX_CODEPOINT
raise FontError, "\"#{token}\" runs backwards — put the smaller codepoint first." if lo > hi
[lo, hi]
end
# One char entry in the emitted .fnt (geometry already scaled to pixels).
FntChar = Struct.new(:codepoint, :x, :y, :w, :h, :xoffset, :yoffset, :xadvance)
# One kerning pair in the emitted .fnt (pixel amount, may be negative).
FntKerning = Struct.new(:first, :second, :amount)
# Mirrors the TS info block: padding is broadcast to all four sides.
FntInfo = Struct.new(:face, :size, :padding)
# Mirrors the TS common block.
FntCommon = Struct.new(:line_height, :base, :scale_w, :scale_h)
# Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
def fnt_text(info, common, chars, kernings)
p = info.padding
lines = [
%(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.line_height} base=#{common.base} scaleW=#{common.scale_w}" \
" scaleH=#{common.scale_h} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
'page id=0 file="sheet.png"',
"chars count=#{chars.length}",
]
lines += chars.map do |c|
"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"
end
lines << "kernings count=#{kernings.length}"
lines += kernings.map { |k| "kerning first=#{k.first} second=#{k.second} amount=#{k.amount}" }
lines.join("\n")
end
# Example:
# info = FntInfo.new('TestFace', 32, 1)
# common = FntCommon.new(38, 29, 128, 128)
# puts fnt_text(info, common, [], [])
# # 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
def join_cps(label, cps)
"#{label} len=#{cps.length} #{cps.join(' ')}"
end
def print_spec(spec)
puts join_cps(spec, parse_charset(spec))
end
if __FILE__ == $PROGRAM_NAME
# Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts).
puts join_cps('ascii', parse_charset('ascii'))
l1 = parse_charset('latin1')
puts "latin1 len=#{l1.length} c0=#{l1[0]} c94=#{l1[94]} c95=#{l1[95]} c190=#{l1[190]}"
d = parse_charset('digits')
puts "digits first=#{d.first} last=#{d.last} len=#{d.length}"
puts "ascii-ws len=#{parse_charset(' ASCII ').length}"
puts "latin1-case c95=#{parse_charset('Latin1')[95]}"
puts "digits-ws len=#{parse_charset("\tDigits\n").length}"
dr = parse_charset('65-90,97-122')
puts "dec-ranges first=#{dr.first} last=#{dr.last} len=#{dr.length}"
print_spec('122,65,97')
print_spec('65-70,68,65')
print_spec('U+41')
print_spec('u+41')
hr = parse_charset('U+4E00-9FFF')
puts "U+4E00-9FFF first=#{hr.first} last=#{hr.last} len=#{hr.length}"
print_spec('65,U+42,67-68')
print_spec(' 65 - 67 , U+0041 ')
print_spec('0')
print_spec('U+10FFFF')
['', ' ', 'abc', '65-,90', '-5', '65,zz', 'U+', 'U+ZZ', 'zz',
'1114112', 'U+110000', '65-2000000', '90-65', 'U+9FFF-4E00', '0-0x10FFFF'].each do |spec|
begin
print_spec(spec)
puts "ERR #{spec} : NO-ERROR"
rescue FontError
puts "ERR #{spec} : #{$!.code}"
end
end
info = FntInfo.new('TestFace', 32, 1)
common = FntCommon.new(38, 29, 128, 128)
chars = [
FntChar.new(65, 0, 0, 34, 36, 0, 0, 36),
FntChar.new(66, 36, 0, 32, 36, 1, 2, 35),
]
kernings = [FntKerning.new(65, 66, -1)]
puts 'fntText'
puts fnt_text(info, common, chars, kernings)
puts "pad #{fnt_text(FntInfo.new('TestFace', 32, 4), common, chars, kernings).split("\n")[0]}"
no_kern = fnt_text(info, common, chars, []).split("\n")
puts "kern0 #{no_kern[6]} lines=#{no_kern.length}"
puts "zerochars lines=#{fnt_text(info, common, [], []).split("\n").length}"
big = fnt_text(info, common, [FntChar.new(19968, 0, 0, 32, 32, 0, 0, 32)], []).split("\n")
puts "bigcp #{big[4]}"
end
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 →