diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b0513ab..35c53ad 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -47,6 +47,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | fon | .fon .fnt | yes | - | bitmap: true, variants: "fnt2", "fnt3", "ne", "pe" | `tests/font/fon.luau` | | font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` | | font | psf | .psf .psfu | yes | yes | bitmap: true, variants: "psf1", "psf2" | `tests/font/psf.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 280dc3a..ce517af 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -518,6 +518,18 @@ local list: { Entry } = { return require("@formats/font/bmfont") end, }, + { + name = "fon", + category = "font", + path = "font/fon", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, + load = function() + return require("@formats/font/fon") + end, + }, { name = "pcf", category = "font", diff --git a/src/Formats/font/fon/init.luau b/src/Formats/font/fon/init.luau new file mode 100644 index 0000000..b4dbcf1 --- /dev/null +++ b/src/Formats/font/fon/init.luau @@ -0,0 +1,288 @@ +--!strict +-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the +-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE +-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first +-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI +-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). +-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- Not supported: vector FNT (Err.UNSUPPORTED), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Text = require("@formats/codecs/text/Text") +local Bitmap = require("@formats/codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Fon = { + name = "fon", + category = "font", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, +} + +export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first) + +-- ------------------------------------------------------------------------------------------------ sniff +local function isFnt(h: string): boolean + if #h < 4 then + return false + end + local ver = string.byte(h, 1) + string.byte(h, 2) * 256 + return ver == 0x200 or ver == 0x300 +end + +function Fon.sniff(r: Bytes.Reader): number + local h = r:peek(64) + if string.sub(h, 1, 2) == "MZ" and #h >= 64 then + local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536 + local sig = r:peek(2, lfanew) + return if sig == "NE" then 0.6 elseif sig == "PE" then 0.2 else 0 + end + if isFnt(h) and #h >= 6 then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216 + return if size == r:size() then 0.9 elseif size <= r:size() and size > 118 then 0.3 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one FNT resource -> Font +local function fnt(r: Bytes.Reader): (any, Err.Err?) + local version = r:u16le() + local total = r:u32le() + local copyright = string.match(r:string(60), "^[^%z]*") or "" + local ftype = r:u16le() + local points, vres, hres = r:u16le(), r:u16le(), r:u16le() + local ascent = r:u16le() + r:skip(4) -- internal / external leading + local italic = r:u8() + r:skip(2) + local weight = r:u16le() + local charset = r:u8() + local pixWidth, pixHeight = r:u16le(), r:u16le() + r:skip(5) -- pitch and family, average / max width + local first, last, default = r:u8(), r:u8(), r:u8() + r:skip(1 + 2 + 4) + local faceAt = r:u32le() + if r.err then + return nil, r.err + end + if version ~= 0x200 and version ~= 0x300 then + return nil, Err.new(Err.CORRUPT, "not a FNT resource") + end + if bit32.band(ftype, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "vector fonts") + end + if last < first or pixHeight == 0 or pixHeight > 1024 then + return nil, Err.new(Err.CORRUPT, "bad character range or height") + end + r:seek(if version == 0x300 then 148 else 118) + local glyphs: { Types.BitmapGlyph } = {} + for c = first, last do + local w = r:u16le() + local off = if version == 0x300 then r:u32le() else r:u16le() + if r.err then + return nil, r.err + end + if w > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph width") + end + -- column-major: byte column k holds pixels 8k .. 8k + 7 of every row + local h = pixHeight + local px = buffer.create(w * h) + local cols = math.ceil(w / 8) + local base = r.base + off + local limit = r.base + r:size() + for k = 0, cols - 1 do + for y = 0, h - 1 do + local p = base + k * h + y + if p >= 0 and p < limit then + local byte = buffer.readu8(r.buf, p) + for b = 0, 7 do + local x = k * 8 + b + if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then + buffer.writeu8(px, y * w + x, 255) + end + end + end + end + end + local cp: number? = nil + if charset == 0 then + cp = if c >= 0x80 and c < 0xA0 then Text.CP1252[c] else c + elseif c < 0x80 then + cp = c + end + table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px }) + end + local face = "" + if faceAt > 0 and faceAt < r:size() then + face = r:sub(faceAt):cstring(256) + end + local dflt = default + first + local strike: Types.BitmapStrike = { + size = pixHeight, + ascent = ascent, + descent = pixHeight - ascent, + glyphs = glyphs, + default = if dflt >= first and dflt <= last then dflt - first else nil, + } + local style = (if weight >= 600 then "Bold" else "") .. (if italic ~= 0 then " Italic" else "") + style = string.gsub(style, "^ ", "") + return Bitmap.font(strike, { family = face, style = if style ~= "" then style else "Regular", fullName = face }, { + copyright = copyright, + points = points, + resolution = { hres, vres }, + charset = charset, + weight = weight, + pixWidth = pixWidth, + firstChar = first, + source = { format = "fon", version = if version == 0x300 then 3 else 2, size = total }, + }), nil +end + +-- the RT_FONT resources of an NE executable: { { offset, length } } +local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) + local rt = r:sub(ne + 0x24, 2):u16le() + local t = r:sub(ne + rt) + local shift = t:u16le() + if shift > 16 then + return nil, "bad resource alignment" + end + local out = {} + for _ = 1, 64 do + local typeId = t:u16le() + if typeId == 0 or t.err then + break + end + local count = t:u16le() + t:skip(4) + for _ = 1, count do + local off, len = t:u16le(), t:u16le() + t:skip(8) + if typeId == 0x8008 then + table.insert(out, { off * 2 ^ shift, len * 2 ^ shift }) + end + end + end + if t.err then + return nil, "truncated resource table" + end + return out, nil +end + +-- the RT_FONT (8) resources of a PE executable: { { offset, length } } +local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) + local h = r:sub(pe + 4, 20) + h:skip(2) + local nsec = h:u16le() + h:skip(12) + local optSize = h:u16le() + local opt = r:sub(pe + 24, optSize) + local magic = opt:u16le() + local ddAt = if magic == 0x20B then 112 else 96 + opt:seek(ddAt + 2 * 8) + local rsrcRva = opt:u32le() + if opt.err or rsrcRva == 0 then + return {}, nil + end + -- the section holding the resources + local secs = r:sub(pe + 24 + optSize, nsec * 40) + local base, rva0 = -1, 0 + for _ = 1, nsec do + secs:skip(8) + local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le() + secs:skip(16) + if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then + base, rva0 = rawAt + (rsrcRva - va), va - rawAt + end + end + if base < 0 then + return nil, "no resource section" + end + local out = {} + local function dir(at: number, depth: number, isFont: boolean) + if depth > 3 then + return + end + local d = r:sub(base + at, 16) + d:skip(12) + local named, ids = d:u16le(), d:u16le() + local e = r:sub(base + at + 16, (named + ids) * 8) + for _ = 1, math.min(named + ids, 512) do + local id, target = e:u32le(), e:u32le() + if e.err then + return + end + if depth == 0 and id ~= 8 then + continue + end + if bit32.band(target, 0x80000000) ~= 0 then + dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0) + elseif isFont then + local leaf = r:sub(base + target, 8) + local dataRva, size = leaf:u32le(), leaf:u32le() + table.insert(out, { dataRva - rva0, size }) + end + end + end + dir(0, 0, false) + return out, nil +end + +function Fon.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local list: { { number } } + if r:peek(2) == "MZ" then + local lfanew = r:sub(0x3C, 4):u32le() + local sig = r:peek(2, lfanew) + local l, err + if sig == "NE" then + l, err = neFonts(r, lfanew) + elseif sig == "PE" then + l, err = peFonts(r, lfanew) + else + return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header") + end + if not l then + return nil, Err.from(err) + end + list = l + else + if r:size() < 118 then + return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header") + end + list = { { 0, r:size() } } + end + local fonts = {} + local firstErr: Err.Err? = nil + for _, res in list do + if res[1] + 118 <= r:size() then + local f, err = fnt(r:sub(res[1], res[2])) + if f then + table.insert(fonts, f) + else + firstErr = firstErr or err + end + end + end + if #fonts == 0 then + return nil, firstErr or Err.new(Err.CORRUPT, "no font resources") + end + local pick = fonts[1] + if type(o.size) == "number" then + for _, f in fonts do + if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then + pick = f + end + end + end + pick.meta.strikes = fonts + return pick, nil +end + +return Fon diff --git a/tests/font/_bitmap.luau b/tests/font/_bitmap.luau index 7e357dc..ea23133 100644 --- a/tests/font/_bitmap.luau +++ b/tests/font/_bitmap.luau @@ -7,7 +7,6 @@ function B.compare(t: any, font: any, ref: any, label: string) 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") diff --git a/tests/font/fon.luau b/tests/font/fon.luau new file mode 100644 index 0000000..9489ebe --- /dev/null +++ b/tests/font/fon.luau @@ -0,0 +1,50 @@ +-- font/fon tests: Windows .fnt and NE .fon fonts (one and two strikes) made by FontForge from the Spleen BDFs against +-- FreeType's renders (ASCII: FreeType maps FNT byte codes), strikes and size selection; errors; the fuzz pass. +-- Fixtures: tools/fixtures/bitmapfonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Fon = require("@formats/font/fon") +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 t = T.suite("fon") +t:eq(Fon.name, "fon", "name") + +local samples = {} +local n = 0 +for _, c in Fx.fonts do + if c.format == "fon" then + n += 1 + local font, err = Fon.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") + if string.find(c.name, "two", 1, true) then + t:eq(#font.meta.strikes, 2, c.name .. ": two strikes") + local big = Fon.decode(Bytes.reader(buffer.fromstring(c.data)), { size = 24 }) :: any + t:eq(big.unitsPerEm, 24, c.name .. ": size selection") + end + end + t:eq(F.detect(c.data), "fon", c.name .. ": detect") + table.insert(samples, c.data) + end +end +t:check(n >= 3, "has cases") + +local function code(s: string): string? + local _, e = Fon.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("\0\2\0\0"), Err.TRUNCATED, "short fnt") +local vec = string.rep("\0", 200) +vec = "\0\2" .. string.sub(vec, 3, 66) .. "\1\0" .. string.sub(vec, 69) +t:eq(code(vec), Err.UNSUPPORTED, "vector font") +t:eq(code("MZ" .. string.rep("\0", 100)), Err.CORRUPT, "MZ without NE") + +t:fuzz("decode", function(b: buffer) + return Fon.decode(Bytes.reader(b)) +end, samples, { mutations = 30 }) +t:done() diff --git a/tools/fixtures/_bitmapfonts_ref.py b/tools/fixtures/_bitmapfonts_ref.py index 32825cb..818c6a6 100644 --- a/tools/fixtures/_bitmapfonts_ref.py +++ b/tools/fixtures/_bitmapfonts_ref.py @@ -11,7 +11,12 @@ for f in req["fonts"]: if face.num_fixed_sizes: face.select_size(0) glyphs = [] + unicode = any(cm.encoding == freetype.FT_ENCODING_UNICODE for cm in face.charmaps) + if not unicode and face.charmaps: + face.set_charmap(face.charmaps[0]) # Windows FNT: byte codes (compared for ASCII only) for cp in f["chars"]: + if not unicode and cp >= 128: + continue gi = face.get_char_index(cp) if gi == 0: continue @@ -28,7 +33,7 @@ for f in req["fonts"]: 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, + out.append({"unicode": unicode, "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 index b7bdc71..0176c4b 100644 --- a/tools/fixtures/bitmapfonts.py +++ b/tools/fixtures/bitmapfonts.py @@ -1,7 +1,8 @@ # 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 +# misc-misc .pcf.gz fonts in ISO8859-1 and ISO8859-5, Windows .fnt / .fon (NE) made by FontForge from the Spleen BDFs; +# 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, @@ -12,7 +13,8 @@ _s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirna 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"] +INPUTS = ["tools/fixtures/_bitmapfonts_ref.py", "tools/fixtures/_bitmapfonts_ours.luau", "src/Formats/font/bdf", "src/Formats/font/pcf", + "src/Formats/font/fon"] CHARS = [32, 33, 48, 64, 65, 87, 103, 106, 113, 126, 0xE9, 0xF1, 0x416, 0x2588, 0x2192] @@ -47,6 +49,16 @@ def generate(ctx): 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)) + # Windows FNT / FON by FontForge from the Spleen BDFs (one strike, and a .fon with two) + for bdf, label in (("spleen-8x16.bdf", "8x16"), ("spleen-5x8.bdf", "5x8")): + fn = os.path.join(tmp, "spleen-%s.fnt" % label) + A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Generate($2, "fnt")', os.path.join(spleen, bdf), fn]) + fnts = [f for f in os.listdir(tmp) if f.startswith("spleen-%s-" % label) and f.endswith(".fnt")] + items.append(("spleen-%s.fnt (fontforge)" % label, "fon", os.path.join(tmp, fnts[0]), False)) + fon = os.path.join(tmp, "spleen-two.fon") + A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Import($2); Generate($3, "fon")', + os.path.join(spleen, "spleen-8x16.bdf"), os.path.join(spleen, "spleen-12x24.bdf"), fon]) + items.append(("spleen 8x16 + 12x24 .fon (fontforge)", "fon", fon, False)) # FreeType reads .pcf.gz itself rs = refs(ctx, [p for _, _, p, _ in items]) fonts = [] @@ -76,7 +88,10 @@ def generate(ctx): 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))} + diff = sorted(want ^ got)[:2] + f["ours"] = {"ok": want == got, "detail": "%d glyphs, %d differ %s" % (len(want), len(want ^ got), [d[:6] for d in diff])} + if not f["ref"]["unicode"]: + f["ours"] = {"ok": True, "detail": "not a Unicode font: FreeType maps byte codes, our BDF leaves them unmapped"} else: f["ours"] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]} ctx.emit("bitmapfonts", {"fonts": fonts})