diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..f535771 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -111,6 +111,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. - codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): - **font** + - codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - **image** diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 63e3d79..1e6b9cf 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -640,8 +640,27 @@ export type Font = { outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8 pages: { Image }?, -- bitmap fonts (BMFont) + bitmap: BitmapStrike?, -- bitmap fonts with per-glyph bitmaps (BDF, PCF, PSF, FON): codecs/font/Bitmap meta: { [string]: any }, } +-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline +export type BitmapGlyph = { + codepoint: number?, -- Unicode (nil for unencoded glyphs) + name: string?, -- glyph name (BDF STARTCHAR, PCF glyph names, PostScript names) + width: number, -- bitmap width / height in pixels + height: number, + left: number, -- x of the bitmap's left column relative to the pen + top: number, -- y of the bitmap's top row above the baseline (BDF: BBXoff + BBh) + advance: number, -- pen advance in pixels + pixels: buffer, -- u8 per pixel (width * height, rows top down): 0 = off, 255 = on (grey fonts use 1..254) +} +export type BitmapStrike = { + size: number, -- pixel size (em height in pixels) + ascent: number, -- pixels above the baseline + descent: number, -- pixels below the baseline (positive) + glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph) + default: number?, -- glyph index (0-based) used for unmapped code points +} -- ------------------------------------------------------------------------------------------------ Archive export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } diff --git a/src/Formats/codecs/font/Bitmap.luau b/src/Formats/codecs/font/Bitmap.luau new file mode 100644 index 0000000..fcb9123 --- /dev/null +++ b/src/Formats/codecs/font/Bitmap.luau @@ -0,0 +1,213 @@ +--!strict +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike +-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels +-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's +-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, +-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an +-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row +-- packing every bitmap font format shares. New code. +-- +-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) +-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized +-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 +-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) +-- +-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Bitmap = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ bits +-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left +-- pixel unless lsbFirst); bytes past the end of buf read as 0 +function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer + local out = buffer.create(math.max(0, w * h)) + local n = buffer.len(b) + for y = 0, h - 1 do + local row = off + y * stride + for x = 0, w - 1 do + local p = row + bit32.rshift(x, 3) + if p >= 0 and p < n then + local byte = readu8(b, p) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then + writeu8(out, y * w + x, 255) + end + end + end + end + return out +end + +-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on +function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer + local s = stride or math.ceil(w / 8) + local out = buffer.create(math.max(0, s * h)) + local n = buffer.len(px) + for y = 0, h - 1 do + for x = 0, w - 1 do + local i = y * w + x + if i < n and readu8(px, i) >= 128 then + local p = y * s + bit32.rshift(x, 3) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn))) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ font +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.bitmap.glyphs[g + 1] + return if gl then gl.advance else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face.outline(_self: any, _g: number): { any }? + return nil +end + +-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1] + if not gl or gl.width < 0 or gl.height < 0 then + return nil + end + local img = Types.Image.new(gl.width, gl.height, "alpha8") + local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels)) + if n > 0 then + buffer.copy(img.pixels, 0, gl.pixels, 0, n) + end + img.meta.left = gl.left + img.meta.top = gl.top + img.meta.advance = gl.advance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1 + return img +end + +-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) +function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any + local index: { [number]: number } = {} + for i, gl in strike.glyphs do + local cp = gl.codepoint + if cp and index[cp] == nil then + index[cp] = i - 1 + end + end + local f = setmetatable({ + kind = "font", + info = info or {}, + unitsPerEm = strike.size, + ascent = strike.ascent, + descent = -strike.descent, + lineGap = 0, + numGlyphs = #strike.glyphs, + bitmap = strike, + meta = meta or {}, + _index = index, + }, Face) + if strike.default then + setmetatable(index, { __index = function() + return strike.default + end }) + end + return f +end + +-- ------------------------------------------------------------------------------------------------ strike +export type StrikeOptions = { + px: number?, -- pixel size for outline fonts (default 16) + chars: (string | { number })?, -- code points for outline fonts (default 32..126) + threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128) +} + +local function codepoints(chars: (string | { number })?): { number } + if type(chars) == "table" then + return chars + end + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + return out + end + for c = 32, 126 do + table.insert(out, c) + end + return out +end + +-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px +function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then + return font.bitmap, nil + end + if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "font has no glyphs to rasterize") + end + local o: StrikeOptions = opts or {} + local px = o.px or 16 + if type(px) ~= "number" or px < 1 or px > 1024 then + return nil, Err.new(Err.ARG, "px must be 1..1024") + end + local threshold = o.threshold or 128 + local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px + local scale = px / upm + local ascent = math.ceil((font.ascent or upm) * scale) + local descent = math.ceil(math.abs(font.descent or 0) * scale) + local glyphs: { Types.BitmapGlyph } = {} + local function add(cp: number?, g: number) + local ok, img = pcall(font.rasterize, font, g, px) + local adv = 0 + local aok, a = pcall(font.advance, font, g) + if aok and type(a) == "number" then + adv = math.floor(a * scale + 0.5) + end + local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) } + if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then + local n = img.width * img.height + local pxs = buffer.create(n) + for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do + if readu8(img.pixels, i) >= threshold then + writeu8(pxs, i, 255) + end + end + gl.width, gl.height, gl.pixels = img.width, img.height, pxs + gl.left = math.floor(img.meta.left or 0) + gl.top = math.floor(img.meta.top or 0) + if type(img.meta.advance) == "number" then + gl.advance = math.floor(img.meta.advance + 0.5) + end + end + table.insert(glyphs, gl) + end + add(nil, 0) + for _, cp in codepoints(o.chars) do + local ok, g = pcall(font.glyphIndex, font, cp) + if ok and type(g) == "number" and g > 0 then + add(cp, g) + end + end + return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil +end + +return Bitmap diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 4f90979..1c7efdd 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -224,19 +224,26 @@ end -- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a -- .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. +-- 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). 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 end - if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" or not value.meta.stream then + if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then + return value + end + local payload = value.meta.payload + if not value.meta.stream and type(payload) ~= "string" then return value end local ok, list = pcall(value.list, value) - if not ok or type(list) ~= "table" or #list ~= 1 then + if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then return value end - local rok, inner = pcall(value.read, value, list[1].name) + local entryName = if type(payload) == "string" then payload else list[1].name + local rok, inner = pcall(value.read, value, entryName) if not rok or type(inner) ~= "buffer" then return value end @@ -246,13 +253,18 @@ local function unwrap(value: any, formatName: string, o: Options): any end local io = table.clone(o) io.category = "archive" - io.name = list[1].name + io.name = entryName io._depth = (o._depth or 0) + 1 local v = load(inner, io) if type(v) ~= "table" or type(v.meta) ~= "table" then return value end - v.meta.compression = formatName + if type(payload) == "string" then + v.meta.container = formatName + v.meta.outer = value + else + v.meta.compression = formatName + end return v end diff --git a/tests/codecs/bitmap.luau b/tests/codecs/bitmap.luau new file mode 100644 index 0000000..b4d8b0a --- /dev/null +++ b/tests/codecs/bitmap.luau @@ -0,0 +1,73 @@ +-- codecs/font/Bitmap tests: 1-bit row pack / unpack round trips (MSB- and LSB-first, padded strides), the Font over a +-- strike (glyphIndex / advance / rasterize / default glyph), Bitmap.strike of a bitmap font and of the first outline +-- font from tools/fixtures/fonts.py (thresholded rasterization), and argument errors. +local T = require("@tests/T") +local Bitmap = require("@formats/codecs/font/Bitmap") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("bitmap") + +local rand = T.rng(3) +for k = 1, 30 do + local w, h = rand(40), rand(20) + local px = buffer.create(w * h) + for i = 0, w * h - 1 do + if rand(2) == 1 then + buffer.writeu8(px, i, 255) + end + end + local stride = math.ceil(w / 8) + (k % 3) + local lsb = k % 2 == 0 + local packed = Bitmap.pack(px, w, h, stride, lsb) + t:eq(buffer.len(packed), stride * h, "pack size " .. k) + t:eq(buffer.tostring(Bitmap.unpack(packed, 0, w, h, stride, lsb)), buffer.tostring(px), "round trip " .. k) +end +-- 0x81 = left and right pixel on (MSB first) +t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0x81 }), 0, 8, 1, 1)), "\255\0\0\0\0\0\0\255", "msb order") +t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0x01 }), 0, 2, 1, 1, true)), "\255\0", "lsb order") +t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0xFF }), 0, 8, 2, 1)), string.rep("\255", 8) .. string.rep("\0", 8), "past the end reads 0") + +local A = { codepoint = 65, width = 2, height = 2, left = 1, top = 7, advance = 4, pixels = T.bytes({ 255, 0, 0, 255 }) } +local strike = { size = 8, ascent = 7, descent = 1, glyphs = { { width = 0, height = 0, left = 0, top = 0, advance = 3, pixels = buffer.create(0) }, A }, default = 0 } +local font = Bitmap.font(strike, { family = "Test" }) +t:eq(font.kind, "font", "kind") +t:eq(font.unitsPerEm, 8, "unitsPerEm") +t:eq(font.descent, -1, "descent") +t:eq(font:glyphIndex(65), 1, "glyphIndex") +t:eq(font:glyphIndex(66), 0, "default glyph") +t:eq(font:advance(1), 4, "advance") +t:eq(font:outline(1), nil, "no outline") +local img = font:rasterize(1, 16) +t:check(img and img.format == "alpha8" and img.width == 2 and buffer.tostring(img.pixels) == "\255\0\0\255", "rasterize") +t:eq(img and img.meta.top, 7, "rasterize top") +t:eq(img and img.meta.scale, 2, "rasterize scale") +t:eq(font:rasterize(9, 8), nil, "rasterize out of range") +t:eq(Bitmap.strike(font), strike, "strike of a bitmap font") + +local s1, e1 = Bitmap.strike({}) +t:check(s1 == nil and e1 and e1.code == Err.ARG, "strike of a non-font") +if Fx.fonts[1] then + local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fx.fonts[1].data))) + local s, err = Bitmap.strike(ttf, { px = 16, chars = "AB" }) + t:check(s, "strike of " .. Fx.fonts[1].name .. ": " .. tostring(err)) + if s then + t:eq(#s.glyphs, 3, "strike glyphs") + local g = s.glyphs[2] + t:eq(g.codepoint, 65, "strike codepoint") + t:check(g.width > 4 and g.height > 6 and g.top > 6 and g.advance > 4, "strike A metrics") + local on = 0 + for i = 0, buffer.len(g.pixels) - 1 do + local v = buffer.readu8(g.pixels, i) + t:check(v == 0 or v == 255, "binary pixels") + if v == 255 then + on += 1 + end + end + t:check(on > 10, "A has ink") + end + t:check(select(2, Bitmap.strike(ttf, { px = 0 })) ~= nil, "px 0 refused") +end +t:done()