ws-arch: font/bmfont (text / XML / binary read + write, lazy pages, bake from outline fonts); api: lazy page loader for bitmap fonts (opts.loadPage or sibling files)

This commit is contained in:
4DBug committed 2026-10-31 08:47:27 -05:00
1 parent ef6c658d78
commit 945abe6d94
7 files changed
+1181

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "bmfont",
category = "font",
path = "font/bmfont",
extensions = { "fnt" },
mime = { "application/x-bmfont" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
load = function()
return require("@formats/font/bmfont")
end,
},
{
name = "ttf",
category = "font",
+457
View File
@@ -0,0 +1,457 @@
--!strict
-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
-- descriptor has no nesting that matters, no text content).
--
-- Never throws on bad input: parse functions return nil, message.
local Bytes = require("@formats/core/Bytes")
local Parse = {}
export type Char = {
id: number,
x: number,
y: number,
width: number,
height: number,
xoffset: number,
yoffset: number,
xadvance: number,
page: number,
chnl: number,
}
export type Desc = {
info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
chars: { Char },
kernings: { { number } }, -- { first, second, amount }
}
local LIMIT = 1000000 -- chars / kernings
local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
local function list(s: string?, n: number): { number }
local out = table.create(n, 0)
if s then
local i = 1
for v in string.gmatch(s, "-?%d+") do
if i > n then
break
end
out[i] = tonumber(v) or 0
i += 1
end
end
return out
end
local function new(): Desc
return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
end
-- one tag's attributes (already split into key -> string) into the description
local function apply(d: Desc, tag: string, a: { [string]: string }): string?
if tag == "info" then
d.info.face = a.face or ""
d.info.charset = a.charset or ""
for _, k in INFO_NUM do
d.info[k] = tonumber(a[k]) or 0
end
d.info.padding = list(a.padding, 4)
d.info.spacing = list(a.spacing, 2)
elseif tag == "common" then
for _, k in COMMON_NUM do
d.common[k] = tonumber(a[k]) or 0
end
elseif tag == "page" then
local id = tonumber(a.id)
if not id or id < 0 or id > 4096 or id % 1 ~= 0 then
return "bad page id"
end
d.pages[id + 1] = a.file or ""
elseif tag == "char" then
if #d.chars >= LIMIT then
return "too many chars"
end
local c: any = {}
for _, k in CHAR_NUM do
c[k] = tonumber(a[k]) or 0
end
table.insert(d.chars, c)
elseif tag == "kerning" then
if #d.kernings >= LIMIT then
return "too many kerning pairs"
end
table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 })
end
return nil
end
local function fill(d: Desc)
for i = 1, #d.pages do
d.pages[i] = d.pages[i] or ""
end
end
-- ------------------------------------------------------------------------------------------------ text
function Parse.text(s: string): (Desc?, string?)
local d = new()
for line in string.gmatch(s, "[^\r\n]+") do
local tag, rest = string.match(line, "^%s*(%a+)(.*)$")
if tag then
local a: { [string]: string } = {}
-- key=value, key="quoted value"
local i = 1
while i <= #rest do
local k, q, e = string.match(rest, '^%s*([%w_]+)="([^"]*)"()', i)
if k then
a[k] = q
i = e
else
local k2, v2, e2 = string.match(rest, "^%s*([%w_]+)=(%S*)()", i)
if not k2 then
break
end
a[k2] = v2
i = e2
end
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
end
if not d.common.lineHeight then
return nil, "no common line"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ XML
local ENTITIES = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" }
local function unescape(s: string): string
return (
string.gsub(s, "&(#?x?%w+);", function(e: string): string?
if ENTITIES[e] then
return ENTITIES[e]
end
local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil
if n and n >= 0 and n <= 0x10FFFF then
return utf8.char(n)
end
return nil
end)
)
end
function Parse.xml(s: string): (Desc?, string?)
local d = new()
local seenFont = false
for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do
if tag == "font" then
seenFont = true
end
local a: { [string]: string } = {}
for k, q, v in string.gmatch(attrs, "([%w_]+)%s*=%s*([\"'])(.-)%2") do
a[k] = unescape(v)
local _ = q
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
if not seenFont or not d.common.lineHeight then
return nil, "not a BMFont XML descriptor"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ binary
function Parse.binary(r: Bytes.Reader): (Desc?, string?)
if not r:match("BMF") then
return nil, "bad signature"
end
local version = r:u8()
if version ~= 3 then
return nil, "unsupported binary version " .. version
end
local d = new()
while not r:eof() do
local kind = r:u8()
local size = r:u32le()
if r.err then
return nil, "truncated block header"
end
local b = r:slice(size)
if r.err then
return nil, "block past the end"
end
if kind == 1 then
d.info.size = b:i16le()
local bits = b:u8()
d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0
d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0
d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0
d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0
d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0
d.info.charsetId = b:u8()
d.info.charset = ""
d.info.stretchH = b:u16le()
d.info.aa = b:u8()
d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() }
d.info.spacing = { b:u8(), b:u8() }
d.info.outline = b:u8()
d.info.face = b:cstring()
elseif kind == 2 then
d.common.lineHeight = b:u16le()
d.common.base = b:u16le()
d.common.scaleW = b:u16le()
d.common.scaleH = b:u16le()
d.common.pages = b:u16le()
d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0
d.common.alphaChnl = b:u8()
d.common.redChnl = b:u8()
d.common.greenChnl = b:u8()
d.common.blueChnl = b:u8()
elseif kind == 3 then
while not b:eof() and #d.pages < 4096 do
table.insert(d.pages, b:cstring())
end
elseif kind == 4 then
local n = size // 20
if n > LIMIT then
return nil, "too many chars"
end
for _ = 1, n do
table.insert(d.chars, {
id = b:u32le(),
x = b:u16le(),
y = b:u16le(),
width = b:u16le(),
height = b:u16le(),
xoffset = b:i16le(),
yoffset = b:i16le(),
xadvance = b:i16le(),
page = b:u8(),
chnl = b:u8(),
})
end
elseif kind == 5 then
local n = size // 10
if n > LIMIT then
return nil, "too many kerning pairs"
end
for _ = 1, n do
table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() })
end
end
if b.err then
return nil, "truncated block " .. kind
end
end
if not d.common.lineHeight then
return nil, "no common block"
end
return d, nil
end
-- ------------------------------------------------------------------------------------------------ writers
local function num(v: any): string
return string.format("%d", math.floor(tonumber(v) or 0))
end
local function textLines(d: Desc, quote: (string) -> string): { { any } }
local i, c = d.info, d.common
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
local lines: { { any } } = {
{
"info",
{
{ "face", quote(i.face or "") },
{ "size", num(i.size) },
{ "bold", num(i.bold) },
{ "italic", num(i.italic) },
{ "charset", quote(i.charset or "") },
{ "unicode", num(i.unicode) },
{ "stretchH", num(i.stretchH or 100) },
{ "smooth", num(i.smooth) },
{ "aa", num(i.aa) },
{ "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") },
{ "spacing", num(sp[1]) .. "," .. num(sp[2]) },
{ "outline", num(i.outline) },
},
},
}
local cf = {}
for _, k in COMMON_NUM do
table.insert(cf, { k, num(c[k]) })
end
table.insert(lines, { "common", cf })
return lines
end
function Parse.writeText(d: Desc): string
local out = {}
local function q(s: string): string
return '"' .. string.gsub(s, '"', "") .. '"'
end
for _, l in textLines(d, q) do
local parts = { l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. "=" .. kv[2])
end
table.insert(out, table.concat(parts, " "))
end
for id, file in d.pages do
table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', ""))))
end
table.insert(out, "chars count=" .. #d.chars)
for _, c in d.chars do
local parts = { "char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. "=" .. num((c :: any)[k]))
end
table.insert(out, table.concat(parts, " "))
end
if #d.kernings > 0 then
table.insert(out, "kernings count=" .. #d.kernings)
for _, k in d.kernings do
table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3])))
end
end
return table.concat(out, "\n") .. "\n"
end
local function esc(s: string): string
return (string.gsub(s, '[&<>"]', { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;" }))
end
function Parse.writeXml(d: Desc): string
local out = { '<?xml version="1.0"?>', "<font>" }
for _, l in textLines(d, function(s: string): string
return s
end) do
local parts = { " <" .. l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " <pages>")
for id, file in d.pages do
table.insert(out, string.format(' <page id="%d" file="%s"/>', id - 1, esc(file)))
end
table.insert(out, " </pages>")
table.insert(out, string.format(' <chars count="%d">', #d.chars))
for _, c in d.chars do
local parts = { " <char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. '="' .. num((c :: any)[k]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " </chars>")
if #d.kernings > 0 then
table.insert(out, string.format(' <kernings count="%d">', #d.kernings))
for _, k in d.kernings do
table.insert(out, string.format(' <kerning first="%s" second="%s" amount="%s"/>', num(k[1]), num(k[2]), num(k[3])))
end
table.insert(out, " </kernings>")
end
table.insert(out, "</font>")
return table.concat(out, "\n") .. "\n"
end
function Parse.writeBinary(d: Desc): buffer
local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10)
w:string("BMF")
w:u8(3)
local i, c = d.info, d.common
local face = i.face or ""
w:u8(1)
w:u32le(14 + #face + 1)
w:u16le((tonumber(i.size) or 0) % 65536)
local bits = 0
if (tonumber(i.smooth) or 0) ~= 0 then
bits += 0x80
end
if (tonumber(i.unicode) or 0) ~= 0 then
bits += 0x40
end
if (tonumber(i.italic) or 0) ~= 0 then
bits += 0x20
end
if (tonumber(i.bold) or 0) ~= 0 then
bits += 0x10
end
if (tonumber(i.fixedHeight) or 0) ~= 0 then
bits += 0x08
end
w:u8(bits)
w:u8(tonumber(i.charsetId) or 0)
w:u16le(tonumber(i.stretchH) or 100)
w:u8(tonumber(i.aa) or 1)
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
for k = 1, 4 do
w:u8(pad[k] or 0)
end
w:u8(sp[1] or 0)
w:u8(sp[2] or 0)
w:u8(tonumber(i.outline) or 0)
w:cstring(face)
w:u8(2)
w:u32le(15)
for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do
w:u16le((tonumber(c[k]) or 0) % 65536)
end
w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0)
for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do
w:u8(tonumber(c[k]) or 0)
end
if #d.pages > 0 then
local len = 0
for _, p in d.pages do
len += #p + 1
end
w:u8(3)
w:u32le(len)
for _, p in d.pages do
w:cstring(p)
end
end
w:u8(4)
w:u32le(#d.chars * 20)
for _, ch in d.chars do
w:u32le(ch.id)
w:u16le(ch.x)
w:u16le(ch.y)
w:u16le(ch.width)
w:u16le(ch.height)
w:u16le(ch.xoffset % 65536)
w:u16le(ch.yoffset % 65536)
w:u16le(ch.xadvance % 65536)
w:u8(ch.page)
w:u8(ch.chnl)
end
if #d.kernings > 0 then
w:u8(5)
w:u32le(#d.kernings * 10)
for _, k in d.kernings do
w:u32le(k[1])
w:u32le(k[2])
w:u16le(k[3] % 65536)
end
end
return w:finish()
end
return Parse
+408
View File
@@ -0,0 +1,408 @@
--!strict
-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and
-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize
-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are
-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the
-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf /
-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation.
-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Parse = require("@formats/font/bmfont/Parse")
-- ------------------------------------------------------------------------------------------------ contract
local Bmfont = {
name = "bmfont",
category = "font",
extensions = { "fnt" },
mime = { "application/x-bmfont" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
}
export type DecodeOptions = {
pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first)
loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one)
}
export type EncodeOptions = {
variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
px: number?, -- fonts without a BMFont description are baked first (see bake)
chars: (string | { number })?,
}
export type BakeOptions = {
px: number?, -- pixels per em (default 32)
chars: (string | { number })?, -- code points to include (default printable ASCII 32..126)
pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096)
padding: number?, -- empty pixels around each glyph (default 1)
file: string?, -- page file name prefix (default "font"): pages are <file>_<n>.png
}
-- ------------------------------------------------------------------------------------------------ sniff
function Bmfont.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 4) == "BMF\3" then
return 1
end
if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then
return 0.9
end
if string.find(head, "<font>", 1, true) or (string.find(head, "<?xml", 1, true) and string.find(r:peek(512), "<font>", 1, true)) then
return if string.find(r:peek(512), "<info", 1, true) then 0.9 else 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the Font value
local Face = {}
Face.__index = Face
function Face.glyphIndex(self: any, cp: number): number
return self._index[cp] or 0
end
function Face.advance(self: any, g: number): number
local c = self._chars[g]
return if c then c.xadvance else 0
end
function Face.kern(self: any, a: number, b: number): number
local ca, cb = self._chars[a], self._chars[b]
if not ca or not cb then
return 0
end
return self._kern[ca.id * 2097152 + cb.id] or 0
end
function Face.outline(_self: any, _g: number): { any }?
return nil -- bitmap font
end
-- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil
function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
local load = loader or self.meta.pageLoader
if type(load) ~= "function" then
return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))")
end
local pages = {}
for i, file in self.meta.pageFiles do
local ok, img, err = pcall(load, file, i - 1)
if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img))
end
pages[i] = img
end
self.pages = pages
return true
end
local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size;
-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available.
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
local c = self._chars[g]
if not c then
return nil
end
if not self.pages and self.meta.pageLoader then
self:loadPages()
end
local page = self.pages and self.pages[c.page + 1]
local img = Types.Image.new(c.width, c.height, "alpha8")
img.meta.left = c.xoffset
img.meta.top = (self.meta.base or 0) - c.yoffset
img.meta.advance = c.xadvance
img.meta.glyph = g
img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1
if not page then
return nil
end
local pw, ph = page.width, page.height
local bpp = Types.Image.bpp(page.format) or 4
local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0
if page.format == "graya8" then
ch = 1
end
for y = 0, c.height - 1 do
local sy = c.y + y
for x = 0, c.width - 1 do
local sx = c.x + x
if sx >= 0 and sy >= 0 and sx < pw and sy < ph then
buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1)))
end
end
end
return img
end
-- the Font value of a description
local function face(d: Parse.Desc, variant: string): any
local f: any = setmetatable({
kind = "font",
info = {
family = d.info.face,
style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular",
fullName = d.info.face,
},
unitsPerEm = math.abs(d.info.size or 0),
ascent = d.common.base or 0,
descent = (d.common.base or 0) - (d.common.lineHeight or 0),
lineGap = 0,
numGlyphs = #d.chars + 1,
pages = nil,
meta = {
bmfont = d,
variant = variant,
pageFiles = d.pages,
lineHeight = d.common.lineHeight,
base = d.common.base,
source = { format = "bmfont", variant = variant },
},
_chars = {},
_index = {},
_kern = {},
}, Face)
for i, c in d.chars do
f._chars[i] = c
if f._index[c.id] == nil then
f._index[c.id] = i
end
end
for _, k in d.kernings do
f._kern[k[1] * 2097152 + k[2]] = k[3]
end
return f
end
function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local d, err, variant
if r:peek(3) == "BMF" then
d, err = Parse.binary(r:sub(0))
variant = "binary"
else
local s = r:peek(r:size())
if string.find(string.sub(s, 1, 512), "<font", 1, true) then
d, err = Parse.xml(s)
variant = "xml"
else
d, err = Parse.text(s)
variant = "text"
end
end
if not d then
local code = if err and (string.find(err, "truncated", 1, true) or string.find(err, "past the end", 1, true)) then Err.TRUNCATED elseif err and string.find(err, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT
return nil, Err.new(code, err or "bad descriptor", r.base)
end
local f = face(d, variant)
if opts and type(opts.pages) == "table" then
f.pages = opts.pages
end
if opts and type(opts.loadPage) == "function" then
f.meta.pageLoader = opts.loadPage
end
return f, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function validDesc(d: any): boolean
if type(d) ~= "table" or type(d.info) ~= "table" or type(d.common) ~= "table" or type(d.pages) ~= "table" or type(d.chars) ~= "table" or type(d.kernings) ~= "table" then
return false
end
for _, c in d.chars do
for _, k in { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } do
local v = c[k]
if type(v) ~= "number" or v % 1 ~= 0 then
return false
end
end
if c.id < 0 or c.x < 0 or c.y < 0 or c.width < 0 or c.height < 0 or c.page < 0 or c.page > 255 or c.chnl < 0 or c.chnl > 255 then
return false
end
end
for _, k in d.kernings do
if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then
return false
end
end
for _, p in d.pages do
if type(p) ~= "string" then
return false
end
end
return true
end
function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(font) ~= "table" or font.kind ~= "font" then
return nil, Err.new(Err.ARG, "expected a Font")
end
local d = type(font.meta) == "table" and font.meta.bmfont or nil
if d == nil then
local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars })
if not baked then
return nil, err
end
d = baked.meta.bmfont
end
if not validDesc(d) then
return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
end
local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text"
if variant == "text" then
return buffer.fromstring(Parse.writeText(d)), nil
elseif variant == "xml" then
return buffer.fromstring(Parse.writeXml(d)), nil
elseif variant == "binary" then
return Parse.writeBinary(d), nil
end
return nil, Err.new(Err.ARG, "variant must be text, xml or binary")
end
-- ------------------------------------------------------------------------------------------------ extras
local function codepoints(chars: any): { number }
local out = {}
if type(chars) == "string" then
for _, c in utf8.codes(chars) do
table.insert(out, c)
end
elseif type(chars) == "table" then
for _, c in chars do
if type(c) == "number" then
table.insert(out, c)
end
end
else
for c = 32, 126 do
table.insert(out, c)
end
end
return out
end
-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are
-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are
-- kept (rounded to pixels).
function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?)
if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
return nil, Err.new(Err.ARG, "bake: expected an outline Font")
end
local o = opts or {}
local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32
local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1
local scale = px / font.unitsPerEm
local glyphs = {}
local area = 0
local seen = {}
for _, cp in codepoints(o.chars) do
local g = font:glyphIndex(cp)
if (g ~= 0 or cp == 0) and not seen[cp] then
seen[cp] = true
local img = font:rasterize(g, px)
if img then
table.insert(glyphs, { cp = cp, g = g, img = img })
area += (img.width + pad) * (img.height + pad)
end
end
end
local size = o.pageSize
if type(size) ~= "number" then
size = 64
while size * size < area * 1.3 and size < 4096 do
size *= 2
end
end
local order = table.clone(glyphs)
table.sort(order, function(a: any, b: any): boolean
if a.img.height ~= b.img.height then
return a.img.height > b.img.height
end
return a.cp < b.cp
end)
local ascent = math.ceil(font.ascent * scale)
local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale)
local prefix = o.file or "font"
local d: Parse.Desc = {
info = {
face = font.info and font.info.family or "font",
size = px,
bold = 0,
italic = 0,
charset = "",
unicode = 1,
stretchH = 100,
smooth = 1,
aa = 1,
padding = { 0, 0, 0, 0 },
spacing = { pad, pad },
outline = 0,
},
common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 },
pages = {},
chars = {},
kernings = {},
}
local pages: { Types.Image } = {}
local page: Types.Image? = nil
local x, y, rowH = pad, pad, 0
local placed: { [number]: Parse.Char } = {}
for _, gl in order do
local w, h = gl.img.width, gl.img.height
if w + 2 * pad > size or h + 2 * pad > size then
return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page")
end
if x + w + pad > size then
x, y, rowH = pad, y + rowH + pad, 0
end
if not page or y + h + pad > size then
page = Types.Image.new(size, size)
table.insert(pages, page :: Types.Image)
table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1))
x, y, rowH = pad, pad, 0
end
local pg = page :: Types.Image
for yy = 0, h - 1 do
for xx = 0, w - 1 do
local a = buffer.readu8(gl.img.pixels, yy * w + xx)
buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216)
end
end
local c: Parse.Char = {
id = gl.cp,
x = x,
y = y,
width = w,
height = h,
xoffset = gl.img.meta.left,
yoffset = ascent - gl.img.meta.top,
xadvance = math.floor(gl.img.meta.advance + 0.5),
page = #pages - 1,
chnl = 15,
}
placed[gl.cp] = c
x += w + pad
rowH = math.max(rowH, h)
end
for _, gl in glyphs do
table.insert(d.chars, placed[gl.cp])
end
d.common.pages = #pages
if type(font.kern) == "function" then
for _, a in glyphs do
for _, b in glyphs do
local k = font:kern(a.g, b.g)
if k ~= 0 then
local v = math.floor(k * scale + 0.5)
if v ~= 0 then
table.insert(d.kernings, { a.cp, b.cp, v })
end
end
end
end
end
local f = face(d, "text")
f.pages = pages
return f, nil
end
return Bmfont
+32
View File
@@ -166,6 +166,37 @@ export type Options = { [string]: any } -- format (name or extension), category,
local load: (src: any, opts: Options?) -> (any, Err.Err?)
-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer
-- | string, else the files next to the descriptor on hosts with a file system
local function pageLoader(value: any, name: string?, o: Options)
if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then
return
end
local user = o.loadPage
if value.pages or (value.meta.pageLoader and type(user) ~= "function") then
return
end
local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil
if type(user) ~= "function" and not (dir and host.hasFiles) then
return
end
value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?)
local src: any
if type(user) == "function" then
src = user(file, page)
else
src = (dir :: string) .. file
end
if type(src) == "table" then
return src -- already an Image
end
if src == nil then
return nil, Err.new(Err.IO, "no data for page " .. file)
end
return load(src, { category = "image", name = file, path = type(user) ~= "function" })
end
end
-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a
-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer
-- one; an explicit opts.format also does.
@@ -242,6 +273,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name)
end
tag(value, entry.name)
pageLoader(value, name, o)
return unwrap(value, entry.name, o)
end
load = F.load
+166
View File
@@ -0,0 +1,166 @@
-- font/bmfont tests: the text, XML and binary descriptors (an independent Python writer, glyphs rendered by FreeType)
-- decode to the reference description; each variant re-encodes to every variant and decodes back unchanged (binary:
-- byte-identical to the Python writer); Font methods (glyphIndex / advance / kern); lazy pages through opts.loadPage
-- and the page PNG (glyph crops against FreeType's bitmaps); bake() from a TrueType font; errors; the fuzz pass.
-- Fixtures: tools/fixtures/bmfont.py.
local T = require("@tests/T")
local F = require("@formats")
local Bmfont = require("@formats/font/bmfont")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/bmfont")
local t = T.suite("bmfont")
t:eq(Bmfont.name, "bmfont", "name")
local CHAR_KEYS = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
local function sameDesc(got: any, want: any, label: string, faceQuotes: boolean)
local face = want.info.face
if not faceQuotes then
face = string.gsub(face, '"', "")
end
t:eq(got.info.face, face, label .. ": face")
for _, k in { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } do
t:eq(got.info[k], want.info[k], label .. ": info." .. k)
end
for i = 1, 4 do
t:eq(got.info.padding[i], want.info.padding[i], label .. ": padding")
end
t:eq(got.info.spacing[1] .. "," .. got.info.spacing[2], want.info.spacing[1] .. "," .. want.info.spacing[2], label .. ": spacing")
for k, v in want.common do
t:eq(got.common[k], v, label .. ": common." .. k)
end
t:eq(#got.pages, #want.pages, label .. ": pages")
t:eq(got.pages[1], want.pages[1], label .. ": page file")
t:eq(#got.chars, #want.chars, label .. ": char count")
for i, c in want.chars do
for _, k in CHAR_KEYS do
t:eq(got.chars[i][k], c[k], string.format("%s: char %d %s", label, c.id, k))
end
end
t:eq(#got.kernings, #want.kernings, label .. ": kerning count")
for i, k in want.kernings do
local g = got.kernings[i]
t:check(g[1] == k[1] and g[2] == k[2] and g[3] == k[3], label .. ": kerning " .. i)
end
end
-- 1. the three encodings
local fonts = {}
for _, v in { "text", "xml", "binary" } do
local f, err = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx[v])))
t:check(f, v .. ": " .. tostring(err))
t:eq(f.meta.variant, v, v .. ": variant")
sameDesc(f.meta.bmfont, Fx.desc, v, v ~= "text")
fonts[v] = f
t:eq(F.detect(Fx[v]), "bmfont", v .. ": F.detect")
end
-- 2. re-encode every variant to every variant
for from, f in fonts do
for _, to in { "text", "xml", "binary" } do
local b, err = Bmfont.encode(f, { variant = to :: any })
t:check(b, from .. " -> " .. to .. ": " .. tostring(err))
local back = Bmfont.decode(Bytes.reader(b :: buffer))
t:check(back and back.meta.variant == to, from .. " -> " .. to .. ": decodes")
sameDesc(back.meta.bmfont, Fx.desc, from .. " -> " .. to, from ~= "text" and to ~= "text")
if from == "binary" and to == "binary" then
t:eq(buffer.tostring(b :: buffer), Fx.binary, "binary re-encode is byte-identical to the reference writer")
end
end
end
t:eq(buffer.tostring(F.save(fonts.xml, nil, { format = "fnt" })):sub(1, 5), "<?xml", "F.save keeps the variant")
-- 3. Font methods
do
local f = fonts.text
local gA, gV = f:glyphIndex(65), f:glyphIndex(86)
t:check(gA > 0 and gV > 0, "glyphIndex")
t:eq(f:glyphIndex(0x1F600), 0, "missing glyph")
t:eq(f:advance(gA), Fx.desc.chars[gA].xadvance, "advance")
t:eq(f:kern(gA, gV), Fx.desc.kernings[2][3], "kern A V")
t:eq(f:kern(gV, gA), Fx.desc.kernings[9][3], "kern V A")
t:eq(f.unitsPerEm, 24, "size")
t:check(f:outline(gA) == nil, "bitmap fonts have no outline")
t:check(f:rasterize(gA, 24) == nil, "no pages loaded yet")
local ok, e = f:loadPages()
t:check(not ok and e and e.code == Err.ARG, "loadPages without a loader")
end
-- 4. lazy pages: the api attaches opts.loadPage; the PNG goes through F.load
do
local asked = {}
local f = F.load(Fx.binary, {
loadPage = function(file: string)
table.insert(asked, file)
return Fx.page
end,
})
t:check(f and f.pages == nil and #asked == 0, "pages are lazy")
local crcs = {}
for _, c in Fx.crops do
crcs[c.id] = c.crc
end
local n = 0
for _, c in Fx.desc.chars do
local img = f:rasterize(f:glyphIndex(c.id), 24)
t:check(img and img.format == "alpha8" and img.width == c.width, "rasterize " .. c.id)
t:eq(Crc32.of(img.pixels), crcs[c.id], "glyph crop " .. c.id .. " = FreeType's bitmap")
t:eq(img.meta.left, c.xoffset, "left")
n += 1
end
t:eq(#asked, 1, "page loaded once")
t:eq(asked[1], "karla_0.png", "page file name")
t:note("%d glyph crops from the lazily loaded page match FreeType", n)
end
-- 5. bake from a TrueType font
do
local ttf = F.font.load(Fx.ttf)
t:check(ttf, "ttf loads")
local baked, err = Bmfont.bake(ttf, { px = 20, chars = "Hello, wörld! AV" })
t:check(baked, "bake: " .. tostring(err))
t:eq(#baked.meta.bmfont.chars, 13, "unique characters baked")
t:check(baked.pages and #baked.pages == 1, "one page")
local g = baked:glyphIndex(string.byte("H"))
local a = baked:rasterize(g, 20)
local b = ttf:rasterize(ttf:glyphIndex(string.byte("H")), 20)
t:check(a and b and a.width == b.width and a.height == b.height, "baked glyph size")
t:eq(Crc32.of(a.pixels), Crc32.of(b.pixels), "baked glyph pixels = rasterize")
t:eq(a.meta.left, b.meta.left, "baked left")
t:eq(a.meta.top, b.meta.top, "baked top")
local enc = F.save(baked, nil, { format = "bmfont", variant = "binary" })
local back = F.load(enc)
t:check(back and #back.meta.bmfont.chars == 13, "baked font round trip")
-- an outline font saved as fnt is baked on the way
local fnt = F.convert(Fx.ttf, "fnt", { px = 16 })
t:check(fnt and string.sub(buffer.tostring(fnt), 1, 9) == "info face", "F.convert ttf -> fnt (text)")
end
-- 6. errors and validation
do
local _, e1 = Bmfont.decode(Bytes.reader(buffer.fromstring("BMF\2")))
t:check(e1 and e1.code == Err.UNSUPPORTED, "binary version 2: " .. tostring(e1))
local _, e2 = Bmfont.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.binary, 1, 40))))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated binary: " .. tostring(e2))
local _, e3 = Bmfont.decode(Bytes.reader(buffer.fromstring("hello")))
t:check(e3 and e3.code == Err.CORRUPT, "not a descriptor")
local f = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx.text)))
f.meta.bmfont.chars[3].x = 1.5
local _, e4 = Bmfont.encode(f)
t:check(e4 and e4.code == Err.ARG, "fractional field: " .. tostring(e4))
local _, e5 = Bmfont.encode({ kind = "image" })
t:check(e5 and e5.code == Err.ARG, "not a font")
end
t:fuzz("decode", function(b: buffer)
local f = Bmfont.decode(Bytes.reader(b))
if f then
Bmfont.encode(f, { variant = "binary" })
end
return f
end, { Fx.binary, string.sub(Fx.text, 1, 3000), string.sub(Fx.xml, 1, 3000) }, { mutations = 40 })
t:done()
+105
View File
@@ -0,0 +1,105 @@
# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans
# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode
# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG.
# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings },
# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) }
import base64, json, os, subprocess
FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf")
CODE = r'''
import base64, io, json, struct, sys, zlib
import freetype
from PIL import Image
data = base64.b64decode(sys.stdin.read())
face = freetype.Face(io.BytesIO(data))
face.set_pixel_sizes(0, 24)
chars = [c for c in range(32, 127)] + [0xE9, 0x2014]
page = Image.new("RGBA", (256, 256), (255, 255, 255, 0))
x, y, rowh = 1, 1, 0
out = []
crops = []
for cp in chars:
face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
g = face.glyph
bm = g.bitmap
w, h = bm.width, bm.rows
if x + w + 1 > 256:
x, y, rowh = 1, y + rowh + 1, 0
alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w))
for r in range(h):
for c in range(w):
page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c]))
out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left,
"yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15})
crops.append({"id": cp, "crc": zlib.crc32(alpha)})
x += w + 1
rowh = max(rowh, h)
kern = []
for a in "AVTWYLo":
for b in "AVTWYoe.":
k = face.get_kerning(a, b).x // 64
kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1])
info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100,
"smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0}
common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0,
"redChnl": 4, "greenChnl": 4, "blueChnl": 4}
pages = ["karla_0.png"]
CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"]
def tq(s): return '"' + s.replace('"', "") + '"'
lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]),
"common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
'page id=0 file="karla_0.png"', "chars count=%d" % len(out)]
for c in out:
lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS))
lines.append("kernings count=%d" % len(kern))
for k in kern:
lines.append("kerning first=%d second=%d amount=%d" % tuple(k))
text = "\r\n".join(lines) + "\r\n"
def xe(s): return s.replace("&", "&amp;").replace("<", "&lt;").replace('"', "&quot;")
xl = ['<?xml version="1.0"?>', "<font>",
' <info face="%s" size="24" bold="0" italic="1" charset="" unicode="1" stretchH="100" smooth="1" aa="1" padding="1,2,3,4" spacing="1,1" outline="0"/>' % xe(info["face"]),
' <common lineHeight="28" base="19" scaleW="256" scaleH="256" pages="1" packed="0" alphaChnl="0" redChnl="4" greenChnl="4" blueChnl="4"/>',
" <pages>", ' <page id="0" file="karla_0.png" />', " </pages>", ' <chars count="%d">' % len(out)]
for c in out:
xl.append(" <char " + " ".join('%s="%d"' % (k, c[k]) for k in CHAR_KEYS) + " />")
xl.append(" </chars>")
xl.append(' <kernings count="%d">' % len(kern))
for k in kern:
xl.append(' <kerning first="%d" second="%d" amount="%d" />' % tuple(k))
xl += [" </kernings>", "</font>"]
xml = "\n".join(xl) + "\n"
face_name = info["face"].encode()
b = bytearray(b"BMF\x03")
blk = struct.pack("<hBBHBBBBBBBB", 24, 0x80 | 0x40 | 0x20, 0, 100, 1, 1, 2, 3, 4, 1, 1, 0) + face_name + b"\0"
b += struct.pack("<BI", 1, len(blk)) + blk
blk = struct.pack("<HHHHHBBBBB", 28, 19, 256, 256, 1, 0, 0, 4, 4, 4)
b += struct.pack("<BI", 2, len(blk)) + blk
blk = b"karla_0.png\0"
b += struct.pack("<BI", 3, len(blk)) + blk
blk = b"".join(struct.pack("<IHHHHhhhBB", *[c[k] for k in CHAR_KEYS]) for c in out)
b += struct.pack("<BI", 4, len(blk)) + blk
blk = b"".join(struct.pack("<IIh", *k) for k in kern)
b += struct.pack("<BI", 5, len(blk)) + blk
png = io.BytesIO()
page.save(png, "PNG")
json.dump({"text": base64.b64encode(text.encode()).decode(), "xml": base64.b64encode(xml.encode()).decode(),
"binary": base64.b64encode(bytes(b)).decode(), "page": base64.b64encode(png.getvalue()).decode(),
"desc": {"info": info, "common": common, "pages": pages, "chars": out, "kernings": kern}, "crops": crops},
sys.stdout)
'''
def generate(ctx):
path = FONT
if not os.path.exists(path):
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], capture_output=True,
check=True, text=True).stdout.strip().split("\n")[-1]
path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf")
raw = ctx.python(["freetype-py", "pillow"], CODE, input=base64.b64encode(open(path, "rb").read()))
res = json.loads(raw)
d = base64.b64decode
for k in ("text", "xml", "binary", "page"):
res[k] = d(res[k])
res["ttf"] = open(path, "rb").read()
ctx.emit("bmfont", res)