ws-arch2: font/hershey (JHF stroke fonts, ascii / id mapping, stroked rasterization; read)

This commit is contained in:
4DBug committed 2026-10-31 15:14:05 -05:00
1 parent 0a3f8b3f5d
commit 375140ece2
5 files changed
+334

No files matched your search

+1
View File
@@ -48,6 +48,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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 | hershey | .jhf | yes | - | strokes: true | `tests/font/hershey.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` |
+12
View File
@@ -530,6 +530,18 @@ local list: { Entry } = {
return require("@formats/font/fon")
end,
},
{
name = "hershey",
category = "font",
path = "font/hershey",
extensions = { "jhf" },
mime = { "application/x-hershey-font" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" },
caps = { decode = true, encode = false, strokes = true },
load = function()
return require("@formats/font/hershey")
end,
},
{
name = "pcf",
category = "font",
+200
View File
@@ -0,0 +1,200 @@
--!strict
-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph
-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R",
-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths
-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster
-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of
-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i
-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph
-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported:
-- writing, the Hershey "occidental" index files (.hmp), filled rendering.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/image/Raster")
-- ------------------------------------------------------------------------------------------------ contract
local Hershey = {
name = "hershey",
category = "font",
extensions = { "jhf" },
mime = { "application/x-hershey-font" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" },
caps = { decode = true, encode = false, strokes = true },
}
export type DecodeOptions = {
map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii")
strokeWidth: number?, -- stroke width in font units for rasterize (default 2)
maxGlyphs: number?, -- default 65536
}
-- ------------------------------------------------------------------------------------------------ constants
local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards)
-- ------------------------------------------------------------------------------------------------ sniff
-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R")
local function header(line: string): (number?, number?)
if #line < 10 then
return nil, nil
end
local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", "")))
local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", "")))
if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then
return nil, nil
end
return id, n
end
function Hershey.sniff(r: Bytes.Reader): number
local head = r:peek(256)
local line = string.match(head, "^([^\r\n]*)")
local id, n = header(line or "")
if not id or not n then
return 0
end
local body = string.sub(line :: string, 9)
if string.find(body, "[^ -~]") then
return 0
end
return if #body == math.min(2 * n, 64) or #body == 2 * n then 0.7 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
type Glyph = { id: number, left: number, right: number, cmds: { any } }
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 gl = self._glyphs[g + 1]
return if gl then gl.right - gl.left else 0
end
function Face.kern(_self: any, _a: number, _b: number): number
return 0
end
function Face.outline(self: any, g: number): { any }?
local gl = self._glyphs[g + 1]
if not gl then
return nil
end
local out = table.create(#gl.cmds)
for i, c in gl.cmds do
out[i] = table.clone(c)
end
return out
end
-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels)
function Face.rasterize(self: any, g: number, px: number): Types.Image?
local gl = self._glyphs[g + 1]
if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local s = px / self.unitsPerEm
local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" })
local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
local img
if m then
img = Types.Image.new(m.width, m.height, "alpha8")
buffer.copy(img.pixels, 0, m.coverage)
img.meta.left = m.x
img.meta.top = -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left, img.meta.top = 0, 0
end
img.meta.advance = (gl.right - gl.left) * s
img.meta.glyph = g
return img
end
function Hershey.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines = string.split((string.gsub(text, "\r", "")), "\n")
local glyphs: { Glyph } = {}
local i = 1
while i <= #lines do
local line = lines[i]
i += 1
if string.match(line, "^%s*$") then
continue
end
local id, n = header(line)
if not id or not n then
return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1))
end
local data = string.sub(line, 9)
while #data < 2 * n and i <= #lines do
data ..= lines[i]
i += 1
end
if #data < 2 * n then
return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count")
end
if #glyphs >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
local left = string.byte(data, 1) - 82
local right = string.byte(data, 2) - 82
local cmds: { any } = {}
local pen = false
for k = 1, n - 1 do
local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2)
if a == 32 and b == 82 then
pen = false
else
local x, y = a - 82 - left, BASELINE - (b - 82)
local cmd: any = { op = if pen then "lineTo" else "moveTo" }
cmd[1], cmd[2] = x, y
table.insert(cmds, cmd)
pen = true
end
end
table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds })
end
if #glyphs == 0 then
return nil, Err.new(Err.CORRUPT, "no glyphs")
end
local index: { [number]: number } = {}
local byId = o.map == "id"
for k, g in glyphs do
local cp = if byId then g.id else 31 + k
if index[cp] == nil then
index[cp] = k - 1
end
end
local font = setmetatable({
kind = "font",
info = { family = "Hershey", style = "Regular" },
unitsPerEm = 32,
ascent = 21,
descent = -7,
lineGap = 4,
numGlyphs = #glyphs,
meta = {
strokes = true,
strokeWidth = o.strokeWidth or 2,
ids = table.create(#glyphs, 0),
source = { format = "hershey", map = if byId then "id" else "ascii" },
},
_glyphs = glyphs,
_index = index,
}, Face)
for k, g in glyphs do
font.meta.ids[k] = g.id
end
return font, nil
end
return Hershey
+62
View File
@@ -0,0 +1,62 @@
-- font/hershey tests: JHF text with Roman-style glyphs and random stroke glyphs (records wrapped over 72-column lines)
-- against an independent parser (ids, advances, every moveTo / lineTo), ASCII and id mappings, stroked rasterization;
-- errors; the fuzz pass. Fixtures: tools/fixtures/hershey.py.
local T = require("@tests/T")
local F = require("@formats")
local Hershey = require("@formats/font/hershey")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/hershey")
local t = T.suite("hershey")
t:eq(Hershey.name, "hershey", "name")
local font, err = Hershey.decode(Bytes.reader(buffer.fromstring(Fx.text)))
t:check(font, "decode: " .. tostring(err))
if font then
t:eq(font.numGlyphs, #Fx.glyphs, "glyph count")
for k, g in Fx.glyphs do
local gi = k - 1
t:eq(font.meta.ids[k], g.id, "id " .. k)
t:eq(font:advance(gi), g.advance, "advance " .. g.id)
local cmds = font:outline(gi) :: any
t:eq(#cmds, #g.cmds, "commands " .. g.id)
local same = true
for i, c in g.cmds do
local m = cmds[i]
if not m or m.op ~= c.op or m[1] ~= c.x or m[2] ~= c.y then
same = false
end
end
t:check(same, "outline " .. g.id)
end
t:eq(font:glyphIndex(33), 1, "ascii mapping: the second glyph is \"!\"")
local img = font:rasterize(1, 64) :: any
t:check(img and img.format == "alpha8" and img.width > 20 and img.height > 30 and img.meta.top > 30, "rasterize A")
local ink = 0
for i = 0, buffer.len(img.pixels) - 1 do
ink += buffer.readu8(img.pixels, i)
end
t:check(ink > 255 * 50, "A has ink")
t:eq(font:rasterize(0, 32).width, 0, "space is empty")
end
local byId = Hershey.decode(Bytes.reader(buffer.fromstring(Fx.text)), { map = "id" }) :: any
t:eq(byId:glyphIndex(508), 2, "id mapping")
t:eq(F.detect(Fx.text), "hershey", "detect")
local function code(s: string): string?
local _, e = Hershey.decode(Bytes.reader(buffer.fromstring(s)))
return e and e.code
end
t:eq(code(" 501 9MWRFJ[ RRFZ["), Err.TRUNCATED, "short record")
t:eq(code("hello world\n"), Err.CORRUPT, "not jhf")
t:eq(code("\n\n"), Err.CORRUPT, "empty")
t:fuzz("decode", function(b: buffer)
local f = Hershey.decode(Bytes.reader(b))
if f then
f:rasterize(1, 24)
end
return f
end, { string.sub(Fx.text, 1, 1500) })
t:done()
+59
View File
@@ -0,0 +1,59 @@
# Hershey JHF fixtures (tools/fixtures.py): no package in nixpkgs ships the .jhf files, so JHF text is written here in
# the distribution's layout (5-column id, 3-column count, extents and vertex pairs offset by "R", " R" pen-up, records
# wrapped at 72 columns), with glyphs of known strokes (a Roman-style "A", "H", "O" approximations and random stroke
# glyphs); the expected outlines come from the independent parser below.
# tests/gen/hershey.luau { text, glyphs = { { id, advance, cmds = { { op, x, y } } } } }
BASELINE = 9
def record(gid, left, right, strokes):
pairs = [chr(left + 82) + chr(right + 82)]
for k, s in enumerate(strokes):
if k:
pairs.append(" R")
pairs += [chr(x + 82) + chr(y + 82) for x, y in s]
body = "".join(pairs)
line = "%5d%3d" % (gid, len(pairs)) + body
return "\n".join(line[i:i + 72] for i in range(0, len(line), 72))
def parse(text):
lines = text.replace("\r", "").split("\n")
out, i = [], 0
while i < len(lines):
line = lines[i]
i += 1
if not line.strip():
continue
gid, n = int(line[:5]), int(line[5:8])
data = line[8:]
while len(data) < 2 * n:
data += lines[i]
i += 1
left, right = ord(data[0]) - 82, ord(data[1]) - 82
cmds, pen = [], False
for k in range(1, n):
a, b = data[2 * k], data[2 * k + 1]
if a == " " and b == "R":
pen = False
continue
cmds.append({"op": "lineTo" if pen else "moveTo", "x": ord(a) - 82 - left, "y": BASELINE - (ord(b) - 82)})
pen = True
out.append({"id": gid, "advance": right - left, "cmds": cmds})
return out
def generate(ctx):
rng = ctx.rng(1967)
recs = [record(699, -8, 8, []), # space
record(501, -9, 9, [[(0, -12), (-8, 9)], [(0, -12), (8, 9)], [(-5, 2), (5, 2)]]), # A
record(508, -11, 11, [[(-7, -12), (-7, 9)], [(7, -12), (7, 9)], [(-7, -2), (7, -2)]])] # H
ring = [(round(8 * __import__("math").cos(a / 10 * 6.2832)), round(-1.5 + 10 * __import__("math").sin(a / 10 * 6.2832))) for a in range(11)]
recs.append(record(515, -11, 11, [ring])) # O
for k in range(40):
strokes = []
for _ in range(1 + rng.randrange(4)):
strokes.append([(rng.randrange(-15, 16), rng.randrange(-16, 17)) for _ in range(1 + rng.randrange(30))])
recs.append(record(2000 + k, -rng.randrange(3, 12), rng.randrange(3, 12), strokes))
text = "\n".join(recs) + "\n"
ctx.emit("hershey", {"text": text, "glyphs": parse(text)})