Files
rosetta/examples/font.luau
T

65 lines
2.8 KiB
Luau

-- examples/font.luau: loads a TrueType font, prints its metrics, renders a line of text into a PNG and bakes the font
-- into a BMFont (descriptor + page images). Run from the repository root: luau examples/font.luau
-- It needs a .ttf: from the repo it uses the docs test font (generate it first with python3 -I tools/fixtures.py docs),
-- elsewhere set TTF_BYTES below to the bytes of any font (the luau CLI cannot read files). docs/guide/font.md explains.
local F = require("@formats")
local TTF_BYTES: buffer? = nil
if not TTF_BYTES then
local ok, IN = pcall(function()
return require("@tests/docs/snippets/_inputs")
end)
if ok then
TTF_BYTES = IN.ttfBytes
end
end
if not TTF_BYTES then
print("font example: no font. Run `python3 -I tools/fixtures.py docs` in the repository, or set TTF_BYTES.")
return
end
local font = assert(F.font.load(TTF_BYTES))
print(string.format("%s %s: %d glyphs, %d units per em, ascent %d, descent %d", font.info.family or "?",
font.info.style or "", font.numGlyphs, font.unitsPerEm, font.ascent, font.descent))
-- render "Hello, fonts!" at 32 px into a white-on-dark rgba8 image
local px, text = 32, "Hello, fonts!"
local scale = px / font.unitsPerEm
local width, prev = 0, nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
width += font:advance(g) + (if prev then font:kern(prev, g) else 0)
prev = g
end
local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 8, math.ceil((font.ascent - font.descent) * scale) + 8))
F.ops.image.fill(canvas, 24, 28, 40, 255)
local baseline = 4 + math.ceil(font.ascent * scale)
local pen = 4
prev = nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
if prev then
pen += font:kern(prev, g) * scale
end
local glyph = assert(font:rasterize(g, px)) -- alpha8, placed by meta.left / meta.top
if glyph.width > 0 then
F.ops.image.blit(canvas, glyph, math.floor(pen + glyph.meta.left + 0.5), baseline - glyph.meta.top)
end
pen += glyph.meta.advance
prev = g
end
local png = assert(F.save(canvas, nil, { format = "png" }))
print(string.format("rendered %q: %d x %d, %d bytes of PNG", text, canvas.width, canvas.height, buffer.len(png)))
-- bake printable ASCII at 20 px into a BMFont for a game's text renderer
local baked = assert(F.format("bmfont").bake(font, { px = 20, file = "ui" }))
local fnt = assert(F.saveString(baked))
for i, page in baked.pages do
local bytes = assert(F.save(page, nil, { format = "png" }))
print(string.format("bmfont page %s: %d x %d, %d bytes", baked.meta.pageFiles[i], page.width, page.height, buffer.len(bytes)))
end
print(string.format("bmfont descriptor: %d bytes, %d characters", #fnt, #baked.meta.bmfont.chars))
local again = assert(F.font.load(fnt, { pages = baked.pages }))
assert(again:rasterize(again:glyphIndex(string.byte("A"))))
print("font example: ok")