diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 71f4ab2..e010ee9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -207,28 +207,28 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec - **compress** - - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ - - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder - - codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: - - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - - codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, - - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF - - codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft - - codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code - - codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content - - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd + - codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension. + - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). + - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952). + - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987). + - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder. + - codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2). + - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. + - codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code). + - codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes). + - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1). + - codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders. + - codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode). + - codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2). + - codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries. - **entropy** - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). - codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c. - **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/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a - - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed + - codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. + - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. + - codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. + - codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. - **image** - codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): - codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable diff --git a/src/Rosetta/codecs/font/Bitmap.luau b/src/Rosetta/codecs/font/Bitmap.luau index a6aa021..f32efe1 100644 --- a/src/Rosetta/codecs/font/Bitmap.luau +++ b/src/Rosetta/codecs/font/Bitmap.luau @@ -1,18 +1,6 @@ --!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). +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. +-- Bit rows are MSB = left pixel unless lsbFirst; a pixel >= 128 is on. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") @@ -20,9 +8,6 @@ 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) @@ -42,7 +27,6 @@ function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: num 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)) @@ -60,7 +44,6 @@ function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst return out end --- ------------------------------------------------------------------------------------------------ font local Face = {} Face.__index = Face @@ -81,7 +64,6 @@ 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 @@ -100,7 +82,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? 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 @@ -136,11 +117,10 @@ function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: 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) + px: number?, + chars: (string | { number })?, + threshold: number?, } local function codepoints(chars: (string | { number })?): { number } @@ -160,7 +140,6 @@ local function codepoints(chars: (string | { number })?): { number } 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") diff --git a/src/Rosetta/codecs/font/Cff/init.luau b/src/Rosetta/codecs/font/Cff/init.luau index a4cebb6..892c09f 100644 --- a/src/Rosetta/codecs/font/Cff/init.luau +++ b/src/Rosetta/codecs/font/Cff/init.luau @@ -1,17 +1,7 @@ --!strict --- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts --- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed --- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands --- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 --- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, --- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage --- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). --- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. --- --- local cff, err = Cff.parse(buf, offset, length) --- local cmds, err = Cff.outline(cff, glyphIndex) --- --- Never throws: malformed data returns nil, message. +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. +-- Charstrings ported from stb_truetype 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua, plus +-- flex1's last delta, an operation budget, and the TN #5177 4.4 arithmetic / storage operators. local Cff = {} local readu8 = buffer.readu8 @@ -38,15 +28,14 @@ export type Font = { limit: number, charStrings: Index, gsubrs: Index, - subrs: Index?, -- name-keyed fonts - fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict - fdSelect: number?, -- absolute offset of FDSelect + subrs: Index?, + fdSubrs: { Index? }?, + fdSelect: number?, numGlyphs: number, cid: boolean, fontMatrix: { number }?, } --- INDEX at absolute offset p (within [base, limit)) -> Index | nil local function index(b: buffer, p: number, limit: number): Index? if p + 2 > limit then return nil @@ -71,7 +60,6 @@ local function index(b: buffer, p: number, limit: number): Index? return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } end --- item(idx, i) -> absolute start, length (nil when out of range / corrupt) local function item(b: buffer, idx: Index, i: number): (number?, number) if i < 0 or i >= idx.count then return nil, 0 @@ -85,7 +73,7 @@ local function item(b: buffer, idx: Index, i: number): (number?, number) end Cff.item = item --- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +-- DICT operators: two-byte ops (12 x) are keyed 1200 + x local function dict(b: buffer, p: number, n: number): { [number]: { number } } local out: { [number]: { number } } = {} local ops: { number } = {} @@ -171,7 +159,6 @@ local function privateSubrs(b: buffer, base: number, limit: number, d: { [number return index(b, ps + s[1], limit) end --- parse(buf, offset, length) -> Font | nil, message function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) local base, limit = offset, math.min(offset + length, blen(b)) if limit - base < 4 then @@ -256,7 +243,6 @@ local function bias(count: number): number return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 end --- the local subrs of glyph g (CID fonts: through FDSelect) local function localSubrs(f: Font, g: number): Index? if not f.cid then return f.subrs @@ -286,7 +272,6 @@ end local BUDGET = 200000 -- operators per glyph (subroutine bombs) --- outline(f, g) -> path commands | nil, message function Cff.outline(f: Font, g: number): ({ any }?, string?) local b = f.buf local p, len = item(b, f.charStrings, g) @@ -295,14 +280,14 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) end local e = p + len local cmds: { any } = {} - local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count + local s: { number } = table.create(48, 0) local sp = 0 local trans = table.create(32, 0) :: { number } local x, y = 0, 0 local open = false local maskbits = 0 local inHeader = true - local stack: { { number } } = {} -- return addresses { p, e } + local stack: { { number } } = {} local subrs: Index? = nil local haveSubrs = false local ops = 0 @@ -334,13 +319,12 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) x, y = x2 + dx3, y2 + dy3 table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) end - local function S(i: number): number -- operand i (0-based), 0 past the stack + local function S(i: number): number return s[i + 1] or 0 end while true do if p >= e then - -- the end of a subroutine without return, or of the charstring without endchar if #stack > 0 then local r = table.remove(stack) :: { number } p, e = r[1], r[2] @@ -535,12 +519,10 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) curveTo(S(6), S(7), S(8), S(9), dx6, dy6) else - -- arithmetic and storage operators: they leave results on the stack clear = false local top = sp local a, c = S(top - 2), S(top - 1) local function set(n: number, v: number) - -- pop n operands, push v sp = math.max(0, sp - n) sp += 1 s[sp] = v diff --git a/src/Rosetta/codecs/font/GlyphNames.luau b/src/Rosetta/codecs/font/GlyphNames.luau index 4130e91..5a9d862 100644 --- a/src/Rosetta/codecs/font/GlyphNames.luau +++ b/src/Rosetta/codecs/font/GlyphNames.luau @@ -1,12 +1,7 @@ --!strict --- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a --- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: --- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and --- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). --- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. --- --- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) --- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +-- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. +-- Data: the Adobe Glyph List For New Fonts (AGLFN 1.7, BSD-3-Clause: licenses/agl-LICENSE.txt; the f-ligatures and +-- dotlessj added) and StandardEncoding, generated from fontTools.agl / fontTools.encodings.StandardEncoding. local GlyphNames = {} -- AGLFN: "name hex" pairs @@ -126,7 +121,6 @@ do end GlyphNames.STANDARD = STANDARD --- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil function GlyphNames.unicode(name: string): number? local base = string.match(name, "^([^%.]+)") or name local t = byName or load() diff --git a/src/Rosetta/codecs/font/TrueType/Glyf.luau b/src/Rosetta/codecs/font/TrueType/Glyf.luau index ce08e9f..7e99dab 100644 --- a/src/Rosetta/codecs/font/TrueType/Glyf.luau +++ b/src/Rosetta/codecs/font/TrueType/Glyf.luau @@ -1,12 +1,7 @@ --!strict --- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and --- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / --- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 --- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point --- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the --- spec do not). No hinting. --- --- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +-- codecs/font/TrueType/Glyf: TrueType glyph outlines from the glyf / loca tables, simple and composite. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett) via imgui-luau's imstb_truetype.lua; component +-- offsets follow FreeType and the spec (stb also scales the offsets of transformed components). local Glyf = {} local readu8, readi8 = buffer.readu8, buffer.readi8 @@ -35,7 +30,7 @@ end export type Face = { buf: buffer, - glyf: number, -- absolute offset of the glyf table + glyf: number, glyfLen: number, loca: number, locaLen: number, @@ -44,7 +39,6 @@ export type Face = { [string]: any, } --- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index function Glyf.range(f: Face, g: number): (number?, number) if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then return nil, 0 @@ -67,7 +61,6 @@ function Glyf.range(f: Face, g: number): (number?, number) return f.glyf + a, z - a end --- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) function Glyf.bounds(f: Face, g: number): (number?, number, number, number) local o, n = Glyf.range(f, g) if not o or n < 10 then @@ -77,7 +70,6 @@ function Glyf.bounds(f: Face, g: number): (number?, number, number, number) return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) end --- contours: { { xs, ys, on } } point lists in font units type Contour = { x: { number }, y: { number }, on: { boolean } } local MAX_POINTS = 65536 @@ -108,7 +100,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour if p > e then return nil, "instructions past the end" end - -- flags local flags = table.create(n, 0) local i = 1 while i <= n do @@ -134,7 +125,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour end end end - -- coordinates local xs = table.create(n, 0) local x = 0 for k = 1, n do @@ -247,7 +237,6 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con if not child then return nil, err end - -- transform the child's points local tc = table.create(#child) :: { Contour } for i, c in child do local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number } @@ -308,7 +297,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) end local o, len = Glyf.range(f, g) if not o then - return {}, nil -- empty glyph (space) + return {}, nil end if len < 10 then return nil, "glyph header past the end" @@ -320,7 +309,6 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) return composite(f, o, len, depth) end --- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message function Glyf.outline(f: Face, g: number): ({ any }?, string?) local cs, err = contours(f, g, 0) if not cs then @@ -365,7 +353,7 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) local k = (s + i - 1) % n + 1 local x, y, isOn = xs[k], ys[k], on[k] if i == n then - x, y, isOn = sx, sy, true -- back to the start + x, y, isOn = sx, sy, true end if isOn then if off then @@ -387,7 +375,6 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) return cmds, nil end --- points(f, g) -> the number of points and contours (for tests) function Glyf.counts(f: Face, g: number): (number, number) local cs = contours(f, g, 0) if not cs then diff --git a/src/Rosetta/codecs/font/TrueType/Tables.luau b/src/Rosetta/codecs/font/TrueType/Tables.luau index 18b468c..081f01e 100644 --- a/src/Rosetta/codecs/font/TrueType/Tables.luau +++ b/src/Rosetta/codecs/font/TrueType/Tables.luau @@ -1,11 +1,6 @@ --!strict --- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode --- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair --- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), --- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public --- domain / MIT) as a reference for cmap 4 and the GPOS walk. --- --- Never throws: every read is range-checked (out of range reads as 0). +-- codecs/font/TrueType/Tables: the sfnt cmap (0, 4, 6, 10, 12, 13), kern, GPOS pair kerning, name and OS/2 tables. +-- Written from the OpenType spec; stb_truetype 1.26 (public domain / MIT) was the reference for cmap 4 and GPOS. local Text = require("@rosetta/codecs/text/Text") local Tables = {} @@ -34,10 +29,9 @@ local function u32(b: buffer, o: number): number end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 --- ------------------------------------------------------------------------------------------------ cmap export type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } --- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +-- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac function Tables.cmap(b: buffer, o: number, n: number): Cmap? local count = u16(b, o + 2) local best, bestRank, symbol = -1, 0, false @@ -102,7 +96,6 @@ local function lookup(c: Cmap, cp: number): number local segX2 = u16(b, t + 6) local segs = segX2 // 2 local ends = t + 14 - -- binary search for the first segment whose end >= cp local lo, hi = 0, segs - 1 while lo < hi do local mid = (lo + hi) // 2 @@ -153,7 +146,6 @@ local function lookup(c: Cmap, cp: number): number return 0 end --- glyph(cmap, codepoint) -> glyph index (0 = .notdef) function Tables.glyph(c: Cmap?, cp: number): number if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then return 0 @@ -165,8 +157,6 @@ function Tables.glyph(c: Cmap?, cp: number): number return g end --- ------------------------------------------------------------------------------------------------ kern --- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } function Tables.kern(b: buffer, o: number, n: number): { [number]: number } local pairs: { [number]: number } = {} local e = o + n @@ -219,7 +209,6 @@ function Tables.kern(b: buffer, o: number, n: number): { [number]: number } return pairs end --- ------------------------------------------------------------------------------------------------ GPOS local function popcount(v: number): number local c = 0 while v ~= 0 do @@ -229,7 +218,6 @@ local function popcount(v: number): number return c end --- coverage index of glyph g in the Coverage table at t, or -1 local function coverage(b: buffer, t: number, g: number): number local fmt = u16(b, t) if fmt == 1 then @@ -291,7 +279,6 @@ local function classOf(b: buffer, t: number, g: number): number return 0 end --- the x advance adjustment in a value record with format vf at r local function xAdvance(b: buffer, r: number, vf: number): number if band(vf, 4) == 0 then return 0 @@ -299,7 +286,6 @@ local function xAdvance(b: buffer, r: number, vf: number): number return i16(b, r + 2 * popcount(band(vf, 3))) end --- one PairPos subtable: (applies, value) local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) local fmt = u16(b, t) local ci = coverage(b, t + u16(b, t + 2), l) @@ -343,9 +329,8 @@ local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, nu return false, 0 end -export type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets +export type Gpos = { buf: buffer, subtables: { { number } } } --- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) function Tables.gpos(b: buffer, o: number, n: number): Gpos? if n < 10 or u16(b, o) ~= 1 then return nil @@ -396,7 +381,6 @@ function Tables.gpos(b: buffer, o: number, n: number): Gpos? return { buf = b, subtables = lookups } end --- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) function Tables.gposKern(g: Gpos, l: number, r: number): number local total = 0 for _, subs in g.subtables do @@ -411,7 +395,6 @@ function Tables.gposKern(g: Gpos, l: number, r: number): number return total end --- ------------------------------------------------------------------------------------------------ name, OS/2 local MAC_ROMAN_HIGH = { 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, @@ -456,7 +439,6 @@ local NAME_IDS: { [number]: string } = { [17] = "typographicStyle", } --- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) function Tables.names(b: buffer, o: number, n: number): { [string]: string } local out: { [string]: string } = {} local rank: { [string]: number } = {} @@ -490,7 +472,6 @@ function Tables.names(b: buffer, o: number, n: number): { [string]: string } return out end --- os2(OS/2 table) -> the commonly used fields function Tables.os2(b: buffer, o: number, n: number): { [string]: number } local t: { [string]: number } = { version = u16(b, o), diff --git a/src/Rosetta/codecs/font/TrueType/init.luau b/src/Rosetta/codecs/font/TrueType/init.luau index 56b0eb5..ed66c70 100644 --- a/src/Rosetta/codecs/font/TrueType/init.luau +++ b/src/Rosetta/codecs/font/TrueType/init.luau @@ -1,20 +1,6 @@ --!strict --- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed --- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines --- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), --- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all --- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean --- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. --- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), --- colour layers (COLR), GSUB substitutions. --- --- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err --- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units --- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo --- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) --- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) --- --- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +-- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett et al.) via imgui-luau's imstb_truetype.lua. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Raster = require("@rosetta/codecs/image/Raster") @@ -33,7 +19,6 @@ local function tag(b: buffer, o: number): string return buffer.readstring(b, o, 4) end --- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) function TrueType.count(b: buffer, offset: number?): number local o = offset or 0 local t = tag(b, o) @@ -46,7 +31,6 @@ function TrueType.count(b: buffer, offset: number?): number return 0 end --- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) local n = u16(b, dir + 4) if dir + 12 + n * 16 > limit then @@ -64,7 +48,6 @@ function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ( return out, nil end --- ------------------------------------------------------------------------------------------------ the Font value local Face = {} Face.__index = Face @@ -116,7 +99,6 @@ function Face.kern(self: any, a: number, b: number): number return v end --- kernCodepoints(a, b) -> kern between two code points function Face.kernCodepoints(self: any, a: number, b: number): number return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end @@ -141,7 +123,6 @@ function Face.outline(self: any, g: number): { any }? return cmds end --- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph function Face.bounds(self: any, g: number): (number?, number, number, number) local cmds = self:outline(g) if not cmds then @@ -160,21 +141,18 @@ function Face.bounds(self: any, g: number): (number?, number, number, number) return x0, y0, x1, y1 end --- scale(px) -> pixels per font unit for an em of px pixels function Face.scale(self: any, px: number): number return px / self.unitsPerEm end export type RasterOptions = { - scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise + scaleX: number?, scaleY: number?, - shiftX: number?, -- subpixel shift (pixels) + shiftX: number?, shiftY: number?, } --- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; --- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty --- glyphs give a 0 x 0 image. +-- meta.top counts up from the baseline, as FreeType's bitmap_top function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? if type(px) ~= "number" or not (px > 0) or px > 4096 then return nil @@ -204,10 +182,8 @@ function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): return img end --- ------------------------------------------------------------------------------------------------ parsing -export type Options = { index: number? } -- the font in a collection (default 0) +export type Options = { index: number? } --- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) local b = buf local file = offset or 0 @@ -271,7 +247,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti _numHMetrics = nh, _kernCache = {}, }, Face) - -- outlines if t.glyf and t.loca then font._glyf = { buf = b, @@ -296,7 +271,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti else return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) end - -- cmap, kerning, names, OS/2, post if t.cmap then font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) end