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:
1 parent
ef6c658d78
commit
945abe6d94
7 files changed
+1181
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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, '[&<>"]', { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """ }))
|
||||
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user