--!strict -- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont -- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. -- Not supported: packed multi-channel glyphs (read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Parse = require("@rosetta/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" }, extraFiles = true }, } export type DecodeOptions = { pages: { Types.Image }?, -- page id 0 first loadPage: ((file: string, page: number) -> any)?, } export type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" px: number?, chars: (string | { number })?, file: string?, -- default: opts.name without its extension, else "font" name: string?, files: { [string]: any }?, encodeImage: ((img: any, format: string) -> (buffer?, any))?, } export type BakeOptions = { px: number?, -- default 32 chars: (string | { number })?, -- default printable ASCII 32..126 pageSize: number?, -- default: the smallest power of two that fits, up to 4096 padding: number?, -- default 1 file: string?, -- default "font"; pages are _.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, "", 1, true) or (string.find(head, "", 1, true)) then return if string.find(r:peek(512), " byte in rgba8 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 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), " 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 local pages = font.pages if d == nil then local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") if file == "" then file = nil end end local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) if not baked then return nil, err end d = baked.meta.bmfont pages = baked.pages end if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then for i, name in d.pages do local img = pages[i] if type(img) == "table" and type(name) == "string" and name ~= "" then local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") local bytes, eerr = encodeImage(img, ext) if not bytes then return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) end files[name] = bytes end end 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 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: BakeOptions = 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: { { cp: number, g: number, img: Types.Image } } = {} local area = 0 local seen = {} for _, cp in codepoints(o.chars) do local g = (font :: any):glyphIndex(cp) if (g ~= 0 or cp == 0) and not seen[cp] then seen[cp] = true local img: Types.Image? = (font :: any):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: number if type(o.pageSize) == "number" then size = o.pageSize else 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