From 87cbc62fb645e87c05fc26f81a559b50a0d5a962 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:56:44 -0500 Subject: [PATCH] ws-arch2: font/bdf (read / write; FreeType reads our output identically) and font/pcf (every pad / unit / order, .pcf.gz via the api), shared bitmap-font fixtures vs FreeType init.luau unwrap: a single-stream archive whose entry is a .pcf / .psf / .bdf loads as that font (category font). --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 24 +++ src/Formats/font/bdf/init.luau | 295 ++++++++++++++++++++++++++ src/Formats/font/pcf/init.luau | 290 +++++++++++++++++++++++++ src/Formats/init.luau | 10 +- tests/font/_bitmap.luau | 23 ++ tests/font/bdf.luau | 61 ++++++ tests/font/pcf.luau | 62 ++++++ tools/fixtures/_bitmapfonts_ours.luau | 30 +++ tools/fixtures/_bitmapfonts_ref.py | 34 +++ tools/fixtures/bitmapfonts.py | 84 ++++++++ 11 files changed, 913 insertions(+), 2 deletions(-) create mode 100644 src/Formats/font/bdf/init.luau create mode 100644 src/Formats/font/pcf/init.luau create mode 100644 tests/font/_bitmap.luau create mode 100644 tests/font/bdf.luau create mode 100644 tests/font/pcf.luau create mode 100644 tools/fixtures/_bitmapfonts_ours.luau create mode 100644 tools/fixtures/_bitmapfonts_ref.py create mode 100644 tools/fixtures/bitmapfonts.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d0c6461..e63f38f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -45,7 +45,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | +| font | bdf | .bdf | yes | yes | bitmap: true | `tests/font/bdf.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `tests/font/bmfont.luau` | +| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 86d0e0d..007355f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -494,6 +494,18 @@ local list: { Entry } = { return require("@formats/cad/step") end, }, + { + name = "bdf", + category = "font", + path = "font/bdf", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, + load = function() + return require("@formats/font/bdf") + end, + }, { name = "bmfont", category = "font", @@ -506,6 +518,18 @@ local list: { Entry } = { return require("@formats/font/bmfont") end, }, + { + name = "pcf", + category = "font", + path = "font/pcf", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, + load = function() + return require("@formats/font/pcf") + end, + }, { name = "ttf", category = "font", diff --git a/src/Formats/font/bdf/init.luau b/src/Formats/font/bdf/init.luau new file mode 100644 index 0000000..700f119 --- /dev/null +++ b/src/Formats/font/bdf/init.luau @@ -0,0 +1,295 @@ +--!strict +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in +-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), +-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to +-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for +-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and +-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font +-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. +-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Bitmap = require("@formats/codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Bdf = { + name = "bdf", + category = "font", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, +} + +export type DecodeOptions = { maxGlyphs: number? } -- default 1114112 +export type EncodeOptions = { + px: number?, -- pixel size for outline fonts (default 16) + chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) + name: string?, -- the FONT (XLFD) name (default built from the font's family / style) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bdf.sniff(r: Bytes.Reader): number + local head = r:peek(32) + return if string.match(head, "^STARTFONT%s+2%.%d") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unquote(v: string): any + local s = string.match(v, '^"(.*)"%s*$') + if s then + return (string.gsub(s, '""', '"')) + end + return tonumber(v) or v +end + +local function hexRow(line: string, w: number, row: buffer, rowOff: number) + local n = math.min(#line // 2, math.ceil(w / 8)) + for i = 0, n - 1 do + local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0 + buffer.writeu8(row, rowOff + i, v) + end +end + +function Bdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split(text, "\n") + local props: { [string]: any } = {} + local fontName, size = "", 0 + local fbb = { 0, 0, 0, 0 } + local fontDw = 0 + local glyphs: { Types.BitmapGlyph } = {} + local encodings: { number } = {} + local i = 1 + local n = #lines + local function line(): string + local l = string.gsub(lines[i] or "", "\r$", "") + i += 1 + return l + end + local first = line() + if not string.match(first, "^STARTFONT%s") then + return nil, Err.new(Err.CORRUPT, "no STARTFONT") + end + local ended = false + while i <= n do + local l = line() + local key, rest = string.match(l, "^(%S+)%s*(.*)$") + if key == "FONT" then + fontName = rest :: string + elseif key == "SIZE" then + size = tonumber(string.match(rest :: string, "^(%S+)")) or 0 + elseif key == "FONTBOUNDINGBOX" then + local a, b, c, d = string.match(rest :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif key == "DWIDTH" then + fontDw = tonumber(string.match(rest :: string, "^(%-?%d+)")) or 0 + elseif key == "STARTPROPERTIES" then + while i <= n do + local pl = line() + if string.match(pl, "^ENDPROPERTIES") then + break + end + local pk, pv = string.match(pl, "^(%S+)%s*(.*)$") + if pk then + props[pk :: string] = unquote(pv :: string) + end + end + elseif key == "STARTCHAR" then + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local name = rest :: string + local enc = -1 + local dw = fontDw + local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] } + local px: buffer? = nil + while i <= n do + local cl = line() + local ck, cr = string.match(cl, "^(%S+)%s*(.*)$") + if ck == "ENCODING" then + local e1, e2 = string.match(cr :: string, "^(%-?%d+)%s*(%-?%d*)") + enc = tonumber(e1) or -1 + if enc == -1 and e2 and e2 ~= "" then + enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings) + end + elseif ck == "DWIDTH" then + dw = tonumber(string.match(cr :: string, "^(%-?%d+)")) or dw + elseif ck == "BBX" then + local a, b, c, d = string.match(cr :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif ck == "BITMAP" then + local w, h = bbx[1], bbx[2] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name) + end + local stride = math.ceil(w / 8) + local rows = buffer.create(stride * h) + for y = 0, h - 1 do + local rl = string.gsub(lines[i] or "", "%s", "") + if string.match(rl, "^ENDCHAR") then + break + end + i += 1 + hexRow(rl, w, rows, y * stride) + end + px = Bitmap.unpack(rows, 0, w, h, stride) + elseif ck == "ENDCHAR" then + break + end + end + local gl: Types.BitmapGlyph = { + name = name, + codepoint = nil, + width = bbx[1], + height = bbx[2], + left = bbx[3], + top = bbx[4] + bbx[2], + advance = dw, + pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])), + } + table.insert(glyphs, gl) + table.insert(encodings, enc) + elseif key == "ENDFONT" then + ended = true + break + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no ENDFONT") + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local default: number? = nil + for k, gl in glyphs do + local enc = encodings[k] + if unicode and enc >= 0 then + gl.codepoint = enc + end + if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then + default = k - 1 + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (if fbb[2] > 0 then fbb[2] else size) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else fbb[2] + fbb[4], + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else -fbb[4], + glyphs = glyphs, + default = default, + } + local slant = props.SLANT + local weight = props.WEIGHT_NAME + local style = (if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "") + if slant == "I" or slant == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + local info = { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else fontName, + style = if style ~= "" then style else "Regular", + fullName = fontName, + } + local font = Bitmap.font(strike, info, { + properties = props, + encodings = encodings, + unicode = unicode, + fontName = fontName, + boundingBox = fbb, + source = { format = "bdf", charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }) + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function quote(s: string): string + return '"' .. string.gsub(s, '"', '""') .. '"' +end + +function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local info = if type(font.info) == "table" then font.info else {} + local family = string.gsub(tostring(info.family or "formats-luau"), "[%-\n\r\"]", " ") + local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil + local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil + local px = strike.size + -- the font bounding box + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, g in strike.glyphs do + if g.width > 0 and g.height > 0 then + x0 = math.min(x0, g.left) + x1 = math.max(x1, g.left + g.width) + y0 = math.min(y0, g.top - g.height) + y1 = math.max(y1, g.top) + end + end + if x0 == math.huge then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + local name = o.name + or string.format("-formats-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, if bold then "bold" else "medium", if italic then "i" else "r", px, px * 10, (x1 - x0) * 10) + local out = { + "STARTFONT 2.1", + "FONT " .. name, + string.format("SIZE %d 75 75", px), + string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), + } + -- the default glyph: the strike's default, else glyph 0 + local defaultIndex = (strike.default or 0) + 1 + local props: { { any } } = { + { "FAMILY_NAME", quote(family) }, + { "WEIGHT_NAME", quote(if bold then "Bold" else "Medium") }, + { "SLANT", quote(if italic then "I" else "R") }, + { "PIXEL_SIZE", px }, + { "POINT_SIZE", px * 10 }, + { "RESOLUTION_X", 75 }, + { "RESOLUTION_Y", 75 }, + { "CHARSET_REGISTRY", quote("ISO10646") }, + { "CHARSET_ENCODING", quote("1") }, + { "FONT_ASCENT", strike.ascent }, + { "FONT_DESCENT", strike.descent }, + } + local dg = strike.glyphs[defaultIndex] + if dg and dg.codepoint then + table.insert(props, { "DEFAULT_CHAR", dg.codepoint }) + end + table.insert(out, "STARTPROPERTIES " .. #props) + for _, p in props do + table.insert(out, p[1] .. " " .. tostring(p[2])) + end + table.insert(out, "ENDPROPERTIES") + table.insert(out, "CHARS " .. #strike.glyphs) + for k, g in strike.glyphs do + local gname = g.name or (if g.codepoint then string.format("uni%04X", g.codepoint) else "glyph" .. (k - 1)) + table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_")) + table.insert(out, "ENCODING " .. (if g.codepoint then tostring(g.codepoint) else "-1")) + table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5))) + table.insert(out, string.format("DWIDTH %d 0", g.advance)) + table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height)) + table.insert(out, "BITMAP") + local stride = math.ceil(g.width / 8) + local rows = Bitmap.pack(g.pixels, g.width, g.height, stride) + for y = 0, g.height - 1 do + local hex = table.create(stride) + for x = 0, stride - 1 do + hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x)) + end + table.insert(out, table.concat(hex)) + end + table.insert(out, "ENDCHAR") + end + table.insert(out, "ENDFONT") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Bdf diff --git a/src/Formats/font/pcf/init.luau b/src/Formats/font/pcf/init.luau new file mode 100644 index 0000000..a9fe873 --- /dev/null +++ b/src/Formats/font/pcf/init.luau @@ -0,0 +1,290 @@ +--!strict +-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), +-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad +-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. +-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets +-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver +-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Bitmap = require("@formats/codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcf = { + name = "pcf", + category = "font", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, +} + +export type DecodeOptions = { maxGlyphs: number? } -- default 1114112 + +-- ------------------------------------------------------------------------------------------------ constants +local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8 +local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256 +local COMPRESSED = 0x100 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "\1fcp" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Table = { format: number, size: number, offset: number } + +-- a reader positioned after a table's format word, with the integer readers for its byte order +type TR = { r: Bytes.Reader, format: number, big: boolean } + +local function open(r: Bytes.Reader, t: Table?): TR? + if not t or t.offset + 4 > r:size() then + return nil + end + local s = r:sub(t.offset, t.size) + local format = s:u32le() + return { r = s, format = format, big = bit32.band(format, 4) ~= 0 } +end + +local function u32(t: TR): number + return if t.big then t.r:u32be() else t.r:u32le() +end +local function i32(t: TR): number + return if t.big then t.r:i32be() else t.r:i32le() +end +local function i16(t: TR): number + return if t.big then t.r:i16be() else t.r:i16le() +end +local function u16(t: TR): number + return if t.big then t.r:u16be() else t.r:u16le() +end + +local REV = buffer.create(256) +for i = 0, 255 do + local v, rv = i, 0 + for _ = 1, 8 do + rv = rv * 2 + v % 2 + v //= 2 + end + buffer.writeu8(REV, i, rv) +end + +function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + if r:string(4) ~= "\1fcp" then + return nil, Err.new(if r.err then Err.TRUNCATED else Err.CORRUPT, "not a PCF file") + end + local count = r:u32le() + if count > 64 then + return nil, Err.new(Err.CORRUPT, "too many tables") + end + local tables: { [number]: Table } = {} + for _ = 1, count do + local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le() + tables[ty] = { format = format, size = size, offset = offset } + end + if r.err then + return nil, r.err + end + -- properties + local props: { [string]: any } = {} + local pt = open(r, tables[PROPERTIES]) + if pt then + local n = i32(pt) + if n < 0 or n > 4096 then + return nil, Err.new(Err.CORRUPT, "bad property count") + end + local raw = {} + for k = 1, n do + raw[k] = { i32(pt), pt.r:u8(), i32(pt) } + end + if n % 4 ~= 0 then + pt.r:skip(4 - n % 4) + end + local strSize = i32(pt) + local strAt = pt.r:tell() + local function str(off: number): string + if off < 0 or off >= strSize then + return "" + end + local s = pt.r:sub(strAt + off, strSize - off) + return s:cstring() + end + for _, p in raw do + props[str(p[1])] = if p[2] ~= 0 then str(p[3]) else p[3] + end + if pt.r.err then + return nil, Err.new(Err.TRUNCATED, "properties table") + end + end + -- accelerators: ascent / descent + local ascent, descent = nil, nil + local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) + if at then + at.r:skip(8) + ascent, descent = i32(at), i32(at) + end + -- metrics + local mt = open(r, tables[METRICS]) + if not mt then + return nil, Err.new(Err.CORRUPT, "no METRICS table") + end + local metrics = {} + local compressed = bit32.band(mt.format, COMPRESSED) ~= 0 + local nm = if compressed then u16(mt) else u32(mt) + if nm > maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + for k = 1, nm do + if compressed then + local b = mt.r + metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 } + else + metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) } + mt.r:skip(2) + end + end + if mt.r.err then + return nil, Err.new(Err.TRUNCATED, "metrics table") + end + -- bitmaps + local bt = open(r, tables[BITMAPS]) + if not bt then + return nil, Err.new(Err.CORRUPT, "no BITMAPS table") + end + local nb = u32(bt) + if nb ~= nm then + return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count") + end + local offsets = table.create(nb, 0) + for k = 1, nb do + offsets[k] = u32(bt) + end + local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) } + local padIndex = bit32.band(bt.format, 3) + local pad = bit32.lshift(1, padIndex) + local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3)) + local msbBit = bit32.band(bt.format, 8) ~= 0 + local dataAt = bt.r:tell() + local dataSize = sizes[padIndex + 1] + if bt.r.err or dataAt + dataSize > bt.r:size() then + return nil, Err.new(Err.TRUNCATED, "bitmaps table") + end + -- the bitmap data normalised to MSB-first bits and bytes + local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize) + if not msbBit then + for k = 0, dataSize - 1 do + buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k))) + end + end + if bt.big ~= msbBit and unit > 1 then + for k = 0, dataSize - unit, unit do + for j = 0, unit // 2 - 1 do + local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j) + buffer.writeu8(bits, k + j, y) + buffer.writeu8(bits, k + unit - 1 - j, x) + end + end + end + local glyphs: { Types.BitmapGlyph } = table.create(nm) + for k = 1, nm do + local m = metrics[k] + local w, h = m[2] - m[1], m[4] + m[5] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph metrics") + end + local stride = math.ceil(w / (pad * 8)) * pad + local px = Bitmap.unpack(bits, offsets[k], w, h, stride) + glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } + end + -- encodings + local encodings: { [number]: number } = {} + local default: number? = nil + local et = open(r, tables[BDF_ENCODINGS]) + if et then + local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et) + if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then + return nil, Err.new(Err.CORRUPT, "bad encoding ranges") + end + for b1 = min1, max1 do + for b2 = min2, max2 do + local g = u16(et) + if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then + encodings[g + 1] = b1 * 256 + b2 + end + end + end + if et.r.err then + return nil, Err.new(Err.TRUNCATED, "encodings table") + end + local dcols = max2 - min2 + 1 + local d1, d2 = def // 256, def % 256 + if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then + local slot = (d1 - min1) * dcols + (d2 - min2) + local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2) + local g = if et.big then dr:u16be() else dr:u16le() + if g ~= 0xFFFF and g < nm then + default = g + end + end + end + -- glyph names + local nt = open(r, tables[GLYPH_NAMES]) + if nt then + local n = u32(nt) + if n == nm then + local offs = table.create(n, 0) + for k = 1, n do + offs[k] = u32(nt) + end + local strSize = u32(nt) + local strAt = nt.r:tell() + for k = 1, n do + if offs[k] < strSize then + glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring() + end + end + end + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if props.CHARSET_ENCODING ~= nil then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local encList = table.create(nm, -1) + for k = 1, nm do + local enc = encodings[k] + encList[k] = enc or -1 + if unicode and enc then + glyphs[k].codepoint = enc + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (ascent or 0) + (descent or 0) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else ascent or 0, + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else descent or 0, + glyphs = glyphs, + default = default, + } + local weight = props.WEIGHT_NAME + local style = if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "" + if props.SLANT == "I" or props.SLANT == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + return Bitmap.font(strike, { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else nil, + style = if style ~= "" then style else "Regular", + fullName = if type(props.FONT) == "string" then props.FONT else nil, + }, { + properties = props, + encodings = encList, + unicode = unicode, + source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }), nil +end + +return Pcf diff --git a/src/Formats/init.luau b/src/Formats/init.luau index d4bc7e2..9acf676 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -240,7 +240,7 @@ end -- .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. Package archives name their payload entry in meta.payload (a .deb's -- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the --- outer archive (its control data). +-- outer archive (its control data). A single-stream archive holding a .pcf / .psf / .bdf font loads as the font. local function unwrap(value: any, formatName: string, o: Options): any if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then return value @@ -261,12 +261,18 @@ local function unwrap(value: any, formatName: string, o: Options): any if not rok or type(inner) ~= "buffer" then return value end + local category = "archive" local e = detect(inner, nil, "archive", nil) + if not e and value.meta.stream and ((Input.extension(entryName) or "") == "pcf" or (Input.extension(entryName) or "") == "psf" or (Input.extension(entryName) or "") == "bdf") then + -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font + e = detect(inner, entryName, "font", nil) + category = "font" + end if not e then return value end local io = table.clone(o) - io.category = "archive" + io.category = category io.name = entryName io._depth = (o._depth or 0) + 1 local v = load(inner, io) diff --git a/tests/font/_bitmap.luau b/tests/font/_bitmap.luau new file mode 100644 index 0000000..7e357dc --- /dev/null +++ b/tests/font/_bitmap.luau @@ -0,0 +1,23 @@ +-- shared by the bitmap font tests: compare(t, font, ref, label) checks every glyph FreeType rendered (code point, +-- bitmap size, left / top offsets, advance, pixels) against font:rasterize(font:glyphIndex(cp)). +local B = {} + +function B.compare(t: any, font: any, ref: any, label: string) + for _, g in ref.glyphs do + local gi = font:glyphIndex(g.cp) + local img = font:rasterize(gi, 16) + local tag = string.format("%s U+%04X", label, g.cp) + t:check(gi > 0 or font.bitmap.default == 0, tag .. ": mapped") + t:check(img, tag .. ": rasterize") + if img then + t:eq(img.width, g.width, tag .. ": width") + t:eq(img.height, g.height, tag .. ": height") + t:eq(img.meta.left, g.left, tag .. ": left") + t:eq(img.meta.top, g.top, tag .. ": top") + t:eq(img.meta.advance, g.advance, tag .. ": advance") + t:check(buffer.tostring(img.pixels) == g.pixels, tag .. ": pixels") + end + end +end + +return B diff --git a/tests/font/bdf.luau b/tests/font/bdf.luau new file mode 100644 index 0000000..a728224 --- /dev/null +++ b/tests/font/bdf.luau @@ -0,0 +1,61 @@ +-- font/bdf tests: Spleen BDF fonts against FreeType's renders (bitmaps, offsets, advances), properties and metrics; our +-- BDF output (of BDF, PCF and outline fonts) read back by FreeType identically (fixture step) and round-tripping; an +-- outline font written as BDF; errors; the fuzz pass. Fixtures: tools/fixtures/bitmapfonts.py, tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Bdf = require("@formats/font/bdf") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local B = require("@tests/font/_bitmap") +local Fx = require("@tests/gen/bitmapfonts") +local Fonts = require("@tests/gen/fonts") + +local t = T.suite("bdf") +t:eq(Bdf.name, "bdf", "name") + +local samples = {} +for _, c in Fx.fonts do + t:check(c.ours.ok, c.name .. ": FreeType reads our BDF of it the same: " .. c.ours.detail) + if c.format == "bdf" then + local font, err = Bdf.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(font, c.name .. ": " .. tostring(err)) + if font then + B.compare(t, font, c.ref, c.name) + t:eq(font.ascent, c.ref.ascent, c.name .. ": ascent") + t:eq(-font.descent, c.ref.descent, c.name .. ": descent") + t:eq(font.info.family, "Spleen", c.name .. ": family") + -- round trip through our writer + local out = Bdf.encode(font) :: buffer + local back = Bdf.decode(Bytes.reader(out)) :: any + t:check(back and #back.bitmap.glyphs == #font.bitmap.glyphs, c.name .. ": round trip glyph count") + if back then + B.compare(t, back, c.ref, c.name .. " (round trip)") + end + end + t:eq(F.detect(c.data), "bdf", c.name .. ": detect") + table.insert(samples, string.sub(c.data, 1, 6000) .. "\nENDFONT\n") + end +end + +-- an outline font as BDF +local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fonts.fonts[1].data))) +local out, err = Bdf.encode(ttf, { px = 14, chars = "Hello" }) +t:check(out, "ttf -> bdf: " .. tostring(err)) +local back = Bdf.decode(Bytes.reader(out :: buffer)) :: any +t:check(back and back:glyphIndex(72) > 0 and back.unitsPerEm == 14 and back:rasterize(back:glyphIndex(72), 14).width > 3, "ttf -> bdf glyphs") + +-- errors +local function code(s: string): string? + local _, e = Bdf.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("hello"), Err.CORRUPT, "not BDF") +t:eq(code("STARTFONT 2.1\nFONT x\n"), Err.TRUNCATED, "no ENDFONT") +t:eq(code("STARTFONT 2.1\nSTARTCHAR a\nBBX 99999 2 0 0\nBITMAP\nENDCHAR\nENDFONT\n"), Err.CORRUPT, "bad BBX") +t:eq((select(2, Bdf.encode({}))) and (select(2, Bdf.encode({})) :: any).code, Err.ARG, "encode a non-font") + +t:fuzz("decode", function(b: buffer) + return Bdf.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/font/pcf.luau b/tests/font/pcf.luau new file mode 100644 index 0000000..5cb3143 --- /dev/null +++ b/tests/font/pcf.luau @@ -0,0 +1,62 @@ +-- font/pcf tests: PCF fonts compiled by bdftopcf with every glyph pad / scan unit / bit and byte order and -t, Tamzen +-- PCFs and X11 misc-misc .pcf.gz fonts against FreeType's renders (bitmaps, offsets, advances) and metrics; charsets +-- other than Unicode / Latin-1 stay unmapped; .pcf.gz through the api; errors; the fuzz pass. +-- Fixtures: tools/fixtures/bitmapfonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Pcf = require("@formats/font/pcf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Deflate = require("@formats/codecs/compress/Deflate") +local B = require("@tests/font/_bitmap") +local Fx = require("@tests/gen/bitmapfonts") + +local t = T.suite("pcf") +t:eq(Pcf.name, "pcf", "name") + +local samples = {} +for _, c in Fx.fonts do + if c.format == "pcf" then + local data = buffer.fromstring(c.data) + if c.gz then + data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer + end + local font, err = Pcf.decode(Bytes.reader(data)) + t:check(font, c.name .. ": " .. tostring(err)) + if font then + B.compare(t, font, c.ref, c.name) + t:eq(font.ascent, c.ref.ascent, c.name .. ": ascent") + t:eq(-font.descent, c.ref.descent, c.name .. ": descent") + t:eq(#font.bitmap.glyphs, c.ref.numGlyphs - 1, c.name .. ": glyph count (FreeType counts one more)") + if string.find(c.name, "ISO8859-5", 1, true) then + t:check(font.meta.unicode == false and font:glyphIndex(65) == (font.bitmap.default or 0), c.name .. ": not mapped to Unicode") + end + end + t:eq(F.detect(data), "pcf", c.name .. ": detect") + if #samples < 3 then + table.insert(samples, data) + end + end +end + +-- a .pcf.gz through the api: the gzip unwraps to the font (meta.compression = "gzip") +for _, c in Fx.fonts do + if c.gz then + local v = F.load(c.data, { name = c.name }) :: any + t:check(v and v.kind == "font" and v.meta.compression == "gzip" and #v.bitmap.glyphs > 100, c.name .. ": F.load unwraps the gzip") + end +end + +-- errors +local function code(s: string): string? + local _, e = Pcf.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("\1fc"), Err.TRUNCATED, "short") +t:eq(code("xxxx\0\0\0\0"), Err.CORRUPT, "bad magic") +t:eq(code("\1fcp\0\0\0\0"), Err.CORRUPT, "no tables") + +t:fuzz("decode", function(b: buffer) + return Pcf.decode(Bytes.reader(b)) +end, samples, { mutations = 40 }) +t:done() diff --git a/tools/fixtures/_bitmapfonts_ours.luau b/tools/fixtures/_bitmapfonts_ours.luau new file mode 100644 index 0000000..a4fd1f1 --- /dev/null +++ b/tools/fixtures/_bitmapfonts_ours.luau @@ -0,0 +1,30 @@ +-- tools/fixtures/_bitmapfonts_ours.luau: our bitmap font writers' output for FreeType to read back (run by +-- tools/fixtures/bitmapfonts.py after it wrote tests/gen/bitmapfonts_src.luau): decodes each source font with its +-- format and prints " " lines. +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Deflate = require("@formats/codecs/compress/Deflate") +local Src = require("@tests/gen/bitmapfonts_src") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +for _, c in Src.fonts do + local data = buffer.fromstring(c.data) + if c.gz then + data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer + end + local mod = F.format(c.format) :: any + local font = if mod then mod.decode(Bytes.reader(data)) else nil + if font and F.format("bdf") then + local out = (F.format("bdf") :: any).encode(font) + if out then + print(c.name .. " " .. hex(out)) + end + end +end diff --git a/tools/fixtures/_bitmapfonts_ref.py b/tools/fixtures/_bitmapfonts_ref.py new file mode 100644 index 0000000..32825cb --- /dev/null +++ b/tools/fixtures/_bitmapfonts_ref.py @@ -0,0 +1,34 @@ +# FreeType's view of bitmap fonts (run by tools/fixtures/bitmapfonts.py in a nix python with freetype-py): stdin is +# JSON { fonts: [ { path, chars } ] }; prints JSON [ { glyphs: [ { cp, width, height, left, top, advance, pixels(hex) } ], +# ascent, descent, family, style, height } ] from FT_LOAD_RENDER | FT_LOAD_TARGET_MONO on the first strike. +import json, sys +import freetype + +req = json.load(sys.stdin) +out = [] +for f in req["fonts"]: + face = freetype.Face(f["path"]) + if face.num_fixed_sizes: + face.select_size(0) + glyphs = [] + for cp in f["chars"]: + gi = face.get_char_index(cp) + if gi == 0: + continue + face.load_glyph(gi, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO) + g = face.glyph + bm = g.bitmap + w, h, pitch = bm.width, bm.rows, bm.pitch + buf = bm.buffer + px = bytearray(w * h) + for y in range(h): + for x in range(w): + if (buf[y * pitch + x // 8] >> (7 - x % 8)) & 1: + px[y * w + x] = 255 + glyphs.append({"cp": cp, "width": w, "height": h, "left": g.bitmap_left, "top": g.bitmap_top, + "advance": g.advance.x >> 6, "pixels": px.hex()}) + m = face.size + out.append({"glyphs": glyphs, "ascent": m.ascender >> 6, "descent": -(m.descender >> 6), "height": m.height >> 6, + "family": (face.family_name or b"").decode("latin-1"), "style": (face.style_name or b"").decode("latin-1"), + "numGlyphs": face.num_glyphs}) +print(json.dumps(out)) diff --git a/tools/fixtures/bitmapfonts.py b/tools/fixtures/bitmapfonts.py new file mode 100644 index 0000000..b7bdc71 --- /dev/null +++ b/tools/fixtures/bitmapfonts.py @@ -0,0 +1,84 @@ +# Bitmap font fixtures (tools/fixtures.py) for font/bdf and font/pcf (and codecs/font/Bitmap): BDF fonts (Spleen 5x8, +# 12x24; BSD-2, nixpkgs#spleen), PCF fonts compiled from them by `bdftopcf` with every glyph pad / scan unit / bit and +# byte order (-p1/2/4/8, -u1/2/4, -m / -l) and with -t (terminal fonts), Tamzen PCFs (nixpkgs#tamzen) and X11 +# misc-misc .pcf.gz fonts in ISO8859-1 and ISO8859-5; all read from the nix store at fixture time. Reference glyph +# bitmaps, offsets and advances come from FreeType (tools/fixtures/_bitmapfonts_ref.py); our BDF writer's output for +# each font (tools/fixtures/_bitmapfonts_ours.luau) is read back by FreeType and compared too. +# tests/gen/bitmapfonts.luau { fonts = { { name, format, data, gz?, ref = { glyphs = { { cp, width, height, left, +# top, advance, pixels } }, ascent, descent }, ours = { ok, detail } } } } +import gzip, importlib.util, json, os, shutil, subprocess + +_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py")) +A = importlib.util.module_from_spec(_s) +_s.loader.exec_module(A) + +INPUTS = ["tools/fixtures/_bitmapfonts_ref.py", "tools/fixtures/_bitmapfonts_ours.luau", "src/Formats/font/bdf", "src/Formats/font/pcf"] +CHARS = [32, 33, 48, 64, 65, 87, 103, 106, 113, 126, 0xE9, 0xF1, 0x416, 0x2588, 0x2192] + + +def store(pkg): + return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1] + + +def refs(ctx, paths): + code = open(os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ref.py")).read() + raw = ctx.python(["freetype-py"], code, input=json.dumps({"fonts": [{"path": p, "chars": CHARS} for p in paths]}).encode()) + return json.loads(raw) + + +def generate(ctx): + spleen = os.path.join(store("spleen"), "share", "fonts", "misc") + tamzen = os.path.join(store("tamzen"), "share", "fonts", "misc") + misc = os.path.join(store("xorg.fontmiscmisc"), "share", "fonts", "X11", "misc") + tmp = A.tmpdir() + try: + items = [] # (name, format, path, gz) + for f in ("spleen-5x8.bdf", "spleen-12x24.bdf"): + items.append((f, "bdf", os.path.join(spleen, f), False)) + src = os.path.join(spleen, "spleen-5x8.bdf") + for opts in (["-p1", "-u1", "-m"], ["-p2", "-u2", "-l"], ["-p4", "-u4", "-m"], ["-p8", "-u4", "-l"], ["-p4", "-u1", "-l", "-t"]): + out = os.path.join(tmp, "spleen-5x8" + "".join(opts) + ".pcf") + A.tool(["xorg.bdftopcf"], ["bdftopcf"] + opts + ["-o", out, src]) + items.append(("spleen-5x8 bdftopcf " + " ".join(opts), "pcf", out, False)) + out = os.path.join(tmp, "spleen-12x24.pcf") + A.tool(["xorg.bdftopcf"], ["bdftopcf", "-o", out, os.path.join(spleen, "spleen-12x24.bdf")]) + items.append(("spleen-12x24 bdftopcf", "pcf", out, False)) + for f in ("Tamzen7x13r.pcf", "Tamzen10x20b.pcf"): + items.append((f, "pcf", os.path.join(tamzen, f), False)) + for f in ("6x13-ISO8859-1.pcf.gz", "9x18B-ISO8859-5.pcf.gz"): + items.append((f, "pcf", os.path.join(misc, f), True)) + # FreeType reads .pcf.gz itself + rs = refs(ctx, [p for _, _, p, _ in items]) + fonts = [] + for (name, fmt, path, gz), ref in zip(items, rs): + for g in ref["glyphs"]: + g["pixels"] = bytes.fromhex(g["pixels"]) + e = {"name": name, "format": fmt, "data": open(path, "rb").read(), "ref": ref} + if gz: + e["gz"] = True + fonts.append(e) + # our BDF writer, read back by FreeType + ctx.emit("bitmapfonts_src", {"fonts": [{k: v for k, v in f.items() if k != "ref"} for f in fonts]}) + subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True) + exe = shutil.which("luau") + argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ours.luau")] + r = subprocess.run(argv, capture_output=True, cwd=ctx.root) + ours = {} + for line in r.stdout.decode().splitlines(): + n, h = line.rsplit(" ", 1) + p = os.path.join(tmp, "ours-%d.bdf" % len(ours)) + open(p, "wb").write(bytes.fromhex(h)) + ours[n] = p + names = list(ours) + back = refs(ctx, [ours[n] for n in names]) if names else [] + for f in fonts: + if f["name"] in ours: + b = back[names.index(f["name"])] + want = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"].hex()) for g in f["ref"]["glyphs"]} + got = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"]) for g in b["glyphs"]} + f["ours"] = {"ok": want == got, "detail": "%d glyphs, %d differ" % (len(want), len(want ^ got))} + else: + f["ours"] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]} + ctx.emit("bitmapfonts", {"fonts": fonts}) + finally: + A.rmtree(tmp)