mirror of
https://github.com/juanjiant-bit/JIANT.git
synced 2026-12-06 21:04:32 +01:00
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
319 lines
18 KiB
Python
319 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
# Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
|
|
# Portions Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
|
|
"""Pre-rasterise TTF fonts into anti-aliased 4-bit alpha glyph tables for the UI (run by
|
|
tools/build.py generate() with --preset inter-tight).
|
|
|
|
gen_aa_font.py OUT.h --preset standin|inter-tight|chakra-petch [--tracking EM] [--gamma G] [--kern-min N]
|
|
gen_aa_font.py OUT.h --face NAME=FONT[#index]:PX:FIRST-LAST[+0xNN,...] ... (explicit faces)
|
|
|
|
Faces of the presets (S labels, M values/headers, L big numerals / titles):
|
|
standin an installed Inter (~/Library/Fonts/Inter.ttc, else Inter in fonts/ next to tools/) with
|
|
-2.5 % tracking: a stand-in for Inter Tight, for previews only.
|
|
inter-tight assets/fonts/InterTight[wght].ttf (SIL OFL 1.1, Google Fonts) at weights 400 / 500 / 600.
|
|
chakra-petch assets/fonts/ChakraPetch-Medium / SemiBold / Bold.ttf (SIL OFL 1.1): JIANT's face since 0.5.
|
|
|
|
Output (a C header; the glyph / font types live in the renderer, firmware/src/gfx.c):
|
|
AF_<N>_DATA 4-bit alpha, trimmed to the ink box, rows back to back, each glyph a byte-aligned bit stream
|
|
(MSB first) of canonical Huffman codes (AF_<N>_HC); a symbol is a value and a repeat count:
|
|
a run of 1..16 zeros or 15s, or one value 1..14 (huff_pack; about 28 % less than 2 px per byte)
|
|
AF_<N>_HC the code: the number of codes of each length 1..15, then the symbols in code order
|
|
((count - 1) << 4 | value)
|
|
AF_<N>_GH / _GP {off, adv (1/16 px), bx, by, bw, bh} per glyph and phase (PHASES of S M, PHASES_L of L:
|
|
the glyph drawn at a pen of +0, +1/phases .. px, next to each other), ASCII 32..126, then the
|
|
extras (Latin-1 by their code; the ellipsis U+2026 as code 0x85, as in Windows-1252); (0.9.0) packed
|
|
(aa_raster.glyph_tables): GH a glyph's lowest offset and its advance, GP each phase's rest in 32 bits
|
|
AF_<N>_KI / _KP kerning pairs (GPOS of the weight) by the first glyph's number g (0.9.0): KP[2 KI[g] ..
|
|
2 KI[g + 1] - 1] its pairs, each the second character's code (sorted) and the delta in 1/16 px (int8)
|
|
AF_<N> aafont_t (its last field: log2 of the phases)
|
|
Prints the byte cost of every face.
|
|
"""
|
|
import argparse
|
|
import heapq
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import aa_raster as ar # noqa: E402
|
|
|
|
FONTS = Path(__file__).resolve().parents[1] / "fonts"
|
|
LOCAL_INTER = os.path.expanduser("~/Library/Fonts/Inter.ttc") # 4.001: 0 Regular, 10 Medium, 12 SemiBold
|
|
EXTRAS = [0xB0, 0xB7, 0xC4, 0xD6, 0xDC, 0xE4, 0xF6, 0xFC, 0x2026] # deg . A: O: U: a: o: u: (Latin-1), ... (V10.8.13: (c) gone,
|
|
# no text draws it; a name with it: '?', gfx.c glyph)
|
|
# (V10.8.13, the owner) S and M (AF_X is S): these no text of the firmware draws (tests/glyph_cover_test.py); their places in
|
|
# the range kept (its index is the character's), drawn as a space: a name from the app or a patch with one stays in its layout
|
|
BLANK = {"S": '"$\\^', "M": '"$\\^'}
|
|
CODE = {0x2026: 0x85} # characters outside Latin-1 -> their one-byte code in the firmware
|
|
PHASES, PHASES_L = 1, 1 # horizontal phases per glyph (aa_raster.raster_font): S M, L. (JIANT 0.9.9-snd4, flash)
|
|
# S M 2, were 4: 12.9 KB less of the glyph tables; a glyph within 1/4 px of its
|
|
# place, a gap within 1/2 px (text_spacing_test.py, as L since 0.5)
|
|
# All UI faces use the existing lossless decoder. The four-entry cache keeps
|
|
# frequently used faces resident and shares its last slot; no new RAM table.
|
|
HUFF = [("S", "M", "L")]
|
|
# L draws only "JIANT" (ABOUT), the UPDATE MODE countdown digit, the calibration's control names (panel.c
|
|
# B_NAME / E_NAME) and MENU > LARGE's card values and page titles (ui_draw.c draw_column_tall, ui_graph.c
|
|
# graph_title: # . / J W too; a value with another character is set in M): a sparse face of those glyphs, the
|
|
# space as its range and the rest as extras
|
|
# (ui_test.c checks that every L string is covered)
|
|
# (JIANT 0.6.56) a face's ink raised by n px in its line: IBM Plex Mono's taller ascent put its values 1 px under where
|
|
# Chakra Petch's sat (tests/ui_render.c alignment: a value centred in its window, its unit on its baseline)
|
|
RISE = {"IBMPlexMono-SemiBold.ttf": 1}
|
|
UI_PRESET = "jiant-lab" # the firmware's faces (tools/build.py; tests/text_spacing_test.py)
|
|
L_CHARS = " #+-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXY"
|
|
V_CHARS = " %+-./0123456789"
|
|
|
|
|
|
def preset(name):
|
|
if name == "chakra-petch": # JIANT 0.5: a tech face (SIL OFL 1.1, Google Fonts)
|
|
v = str(FONTS.parent / "assets" / "fonts" / "ChakraPetch-")
|
|
return [("S", v + "Medium.ttf", 12, (32, 126), EXTRAS, -0.055, PHASES),
|
|
("M", v + "SemiBold.ttf", 15, (32, 126), EXTRAS, -0.05, PHASES),
|
|
("L", v + "Bold.ttf", 28, (32, 32), [ord(c) for c in L_CHARS[1:]], 0.0, PHASES_L)]
|
|
if name == "jiant-lab": # JIANT 0.6.56: the landing's faces (SIL OFL 1.1, Google Fonts): Chakra Petch
|
|
f = FONTS.parent / "assets" / "fonts" # for labels and (0.7.7, the polish) values again, Michroma for the big titles;
|
|
# (0.8.9, the skins' mock-up "Sans 0.6") the values and the header's BPM in a rounded sans again, as the 0.6 had
|
|
# them: Inter Tight SemiBold
|
|
# (snd7: no lowercase: the UI folds every text to capitals, gfx.c fold; 6.7 KB of flash back)
|
|
return [("S", str(f / "ChakraPetch-Medium.ttf"), 12, (32, 95), EXTRAS, -0.055, PHASES),
|
|
("M", str(f / "InterTight[wght].ttf") + "@600", 15, (32, 95), EXTRAS, 0.0, PHASES),
|
|
("L", str(f / "Michroma-Regular.ttf"), 18, (32, 32), [ord(c) for c in L_CHARS[1:]], 0.0, PHASES_L),
|
|
# V: a card's value when it is a number: M's face at 19 px (capitals 14, a figure 12 px wide: "1000" in a
|
|
# card), the figures and their signs only
|
|
("V", str(f / "InterTight[wght].ttf") + "@600", 19, (32, 32), [ord(c) for c in V_CHARS[1:]], 0.0, PHASES_L)]
|
|
if name == "inter-tight":
|
|
v = str(FONTS.parent / "assets" / "fonts" / "InterTight[wght].ttf") # SIL OFL 1.1, Google Fonts
|
|
return [("S", v + "@400", 12, (32, 126), EXTRAS, 0.0, PHASES),
|
|
("M", v + "@500", 15, (32, 126), EXTRAS, 0.0, PHASES),
|
|
("L", v + "@600", 28, (32, 32), [ord(c) for c in L_CHARS[1:]], 0.0, PHASES_L)]
|
|
if name == "standin":
|
|
if os.path.exists(LOCAL_INTER):
|
|
reg, med, semi = LOCAL_INTER + "#0", LOCAL_INTER + "#10", LOCAL_INTER + "#12"
|
|
else: # the repo's Inter 3.019 (only Regular + Light)
|
|
reg = med = semi = str(FONTS / "Inter-Regular.ttf")
|
|
t = -0.025 # Inter Tight is Inter with tighter spacing
|
|
return [("S", reg, 12, (32, 126), EXTRAS, t, PHASES), ("M", med, 15, (32, 126), EXTRAS, t, PHASES),
|
|
("L", semi, 28, (32, 32), [ord(c) for c in L_CHARS[1:]], t, PHASES_L)]
|
|
raise SystemExit(f"unknown preset {name}")
|
|
|
|
|
|
def parse_face(s):
|
|
name, _, rest = s.partition("=")
|
|
font, px, rng = rest.rsplit(":", 2)
|
|
extras = []
|
|
if "+" in rng:
|
|
rng, ex = rng.split("+", 1)
|
|
extras = [int(x, 0) for x in ex.split(",") if x]
|
|
a, b = rng.split("-")
|
|
return (name, font, int(px), (int(a), int(b)), extras, None, PHASES)
|
|
|
|
|
|
HC_MAXLEN = 15
|
|
|
|
|
|
def huff_symbols(v, runs=(0, 15)):
|
|
"""a glyph's alpha values -> symbols (count - 1) << 4 | value: runs of 1..16 zeros or 15s (the values in runs), single
|
|
others"""
|
|
out, i = [], 0
|
|
while i < len(v):
|
|
j = i + 1
|
|
if v[i] in runs:
|
|
while j < len(v) and v[j] == v[i] and j - i < 16:
|
|
j += 1
|
|
out.append((j - i - 1) << 4 | v[i])
|
|
i = j
|
|
return out
|
|
|
|
|
|
def huff_lengths(count):
|
|
"""symbol -> code length (Huffman), at most HC_MAXLEN"""
|
|
heap = [(c, k, (s,)) for k, (s, c) in enumerate(sorted(count.items()))]
|
|
heapq.heapify(heap)
|
|
length = {s: 0 for s in count}
|
|
if len(heap) == 1:
|
|
return {s: 1 for s in count}
|
|
k = len(heap)
|
|
while len(heap) > 1:
|
|
a, b = heapq.heappop(heap), heapq.heappop(heap)
|
|
for s in a[2] + b[2]:
|
|
length[s] += 1
|
|
k += 1
|
|
heapq.heappush(heap, (a[0] + b[0], k, a[2] + b[2]))
|
|
assert max(length.values()) <= HC_MAXLEN, "code too long: limit the lengths"
|
|
return length
|
|
|
|
|
|
def huff_pack(glyph_values, runs=(0, 15)):
|
|
"""[alpha values per glyph] -> (hc table bytes, [bytes per glyph]): canonical Huffman, MSB first"""
|
|
syms = [huff_symbols(v, runs) for v in glyph_values]
|
|
count = {}
|
|
for g in syms:
|
|
for s in g:
|
|
count[s] = count.get(s, 0) + 1
|
|
length = huff_lengths(count)
|
|
order = sorted(count, key=lambda s: (length[s], s))
|
|
code, c, prev = {}, 0, length[order[0]]
|
|
for s in order: # canonical: by length, then symbol
|
|
c <<= length[s] - prev
|
|
prev = length[s]
|
|
code[s] = c
|
|
c += 1
|
|
hc = [sum(1 for s in order if length[s] == n) for n in range(1, HC_MAXLEN + 1)] + order
|
|
out = []
|
|
for g in syms:
|
|
acc, nb, b = 0, 0, bytearray()
|
|
for s in g:
|
|
acc, nb = (acc << length[s]) | code[s], nb + length[s]
|
|
while nb >= 8:
|
|
nb -= 8
|
|
b.append((acc >> nb) & 255)
|
|
if nb:
|
|
b.append((acc << (8 - nb)) & 255)
|
|
out.append(bytes(b))
|
|
return hc, out
|
|
|
|
|
|
def huff_unpack(hc, data, n):
|
|
"""the decoder (gfx.c cv_alpha_hc), for the self-check: n values from the bit stream data"""
|
|
out, pos = [], 0
|
|
while len(out) < n:
|
|
code = first = idx = 0
|
|
for ln in range(HC_MAXLEN):
|
|
code |= (data[pos >> 3] >> (7 - (pos & 7))) & 1
|
|
pos += 1
|
|
if code - first < hc[ln]:
|
|
break
|
|
idx += hc[ln]
|
|
first = (first + hc[ln]) << 1
|
|
code <<= 1
|
|
s = hc[HC_MAXLEN + idx + code - first]
|
|
out += [s & 15] * ((s >> 4) + 1)
|
|
assert len(out) == n
|
|
return out
|
|
|
|
|
|
def emit(face, tracking, gamma, kern_min):
|
|
name, font, px, (first, last), extras, ftrack, phases = face
|
|
chars = [chr(c) for c in range(first, last + 1)] + [chr(c) for c in extras]
|
|
r = ar.raster_font(font, px, chars, tracking if ftrack is None else ftrack, gamma, True, kern_min, phases)
|
|
rise = RISE.get(os.path.basename(font.split("#")[0].split("@")[0]), 0)
|
|
if rise: # the ink up by rise px in its line (the line shorter by as much)
|
|
r["asc"] -= rise
|
|
r["h"] -= rise
|
|
r["glyphs"] = {ch: (a, [(bx, by - rise if bw else by, bw, bh, b) for bx, by, bw, bh, b in ph])
|
|
for ch, (a, ph) in r["glyphs"].items()}
|
|
for ch in BLANK.get(name, ""): # (V10.8.13) as the space: no ink, its advance
|
|
r["glyphs"][ch] = r["glyphs"][" "]
|
|
data, table, lines = bytearray(), [], []
|
|
for ch in chars:
|
|
adv16, ph = r["glyphs"][ch]
|
|
off = len(data)
|
|
for bx, by, bw, bh, b in ph:
|
|
table.append((len(data), adv16, bx, by, bw, bh))
|
|
data += b
|
|
table += [(off,) + table[-1][1:]] * (phases - len(ph)) # one phase (aa_raster.FIXED): the same bitmap
|
|
raw, hc = bytes(data), []
|
|
if name in HUFF[0]:
|
|
# Huffman-code every distinct bitmap (phases may share one), byte-aligned per glyph
|
|
offs = sorted({e[0] for e in table if e[4]})
|
|
vals = []
|
|
for off in offs:
|
|
e = next(t for t in table if t[0] == off and t[4])
|
|
v = []
|
|
for byte in raw[off:off + (e[4] * e[5] + 1) // 2]:
|
|
v += [byte >> 4, byte & 15]
|
|
vals.append(v[:e[4] * e[5]])
|
|
# Pick the smaller existing run alphabet per face. The firmware already
|
|
# decodes arbitrary alpha repeats (also used by keycaps).
|
|
hc, packed = min((huff_pack(vals, runs) for runs in ((0, 15), (0,), tuple(range(16)))),
|
|
key=lambda p: len(p[0]) + sum(map(len, p[1])))
|
|
data, newoff = bytearray(), {}
|
|
for off, v, b in zip(offs, vals, packed):
|
|
assert huff_unpack(hc, b, len(v)) == v
|
|
newoff[off] = len(data)
|
|
data += b
|
|
table = [(newoff.get(off, 0),) + t[1:] for t in table for off in (t[0],)]
|
|
data += bytes(2) # gfx.c cv_alpha_hc reads up to 2 bytes ahead
|
|
assert len(data) < 65536, "glyph data over 64 KiB: split the face"
|
|
kern = sorted(r["kern"].items())
|
|
keys = [(ord(a) << 8) | ord(b) for (a, b), _ in kern if ord(a) < 256 and ord(b) < 256]
|
|
deltas = [d for (a, b), d in kern if ord(a) < 256 and ord(b) < 256]
|
|
order = sorted(range(len(keys)), key=lambda i: keys[i])
|
|
keys, deltas = [keys[i] for i in order], [deltas[i] for i in order]
|
|
# (0.9.0) the pairs by the first glyph's number: KI where its pairs start, KP each pair's second character and
|
|
# delta (2 B a pair less than a << 8 | b, and the search runs over that glyph's own pairs only)
|
|
gi = {CODE.get(ord(c), ord(c)): i for i, c in enumerate(chars)}
|
|
pairs = sorted((gi[k >> 8], k & 255, d) for k, d in zip(keys, deltas))
|
|
assert all(-128 <= d < 128 for d in deltas) and len(pairs) < 65536
|
|
nki = pairs[-1][0] + 1 if pairs else 0
|
|
ki = [sum(1 for p in pairs if p[0] < g) for g in range(nki + 1)]
|
|
kp = [v for _, b, d in pairs for v in (b, d & 255)]
|
|
psh = phases.bit_length() - 1
|
|
lines.append(f"/* {name}: {os.path.basename(font.split('#')[0])} {px}px, h {r['h']}, baseline {r['asc']}, "
|
|
f"{len(chars)} glyphs x {phases} phases, {len(data)} B data"
|
|
+ (f" (Huffman; {len(raw)} B as nibbles) */" if hc else " */"))
|
|
lines.append(ar.c_array(f"AF_{name}_DATA", "uint8_t", list(data), 24, "0x{:02x}"))
|
|
if hc:
|
|
lines.append(ar.c_array(f"AF_{name}_HC", "uint8_t", hc, 24))
|
|
gtext, gsize = ar.glyph_tables(name, table, phases)
|
|
lines.append(gtext)
|
|
if keys:
|
|
lines.append(ar.c_array(f"AF_{name}_KI", "uint16_t", ki, 12))
|
|
lines.append(ar.c_array(f"AF_{name}_KP", "uint8_t", kp, 24))
|
|
ex = ", ".join(str(CODE.get(c, c)) for c in extras) or "0"
|
|
lines.append(f"static const uint8_t AF_{name}_EX[{max(1, len(extras))}] = {{{ex}}};")
|
|
lines.append(f"static const aafont_t AF_{name} = {{{r['h']}, {r['asc']}, {first}, {last}, {len(extras)}, {nki}, "
|
|
f"AF_{name}_GH, AF_{name}_GP, AF_{name}_DATA, {'AF_%s_KI' % name if keys else '0'}, "
|
|
f"{'AF_%s_KP' % name if keys else '0'}, AF_{name}_EX, {psh}, {'AF_%s_HC' % name if hc else '0'}}};")
|
|
if "H" in chars or "0" in chars: # the capitals' band (gfx.c CAP_IN: centring text by it; V, the
|
|
cap = table[chars.index("H" if "H" in chars else "0") * phases] # figures' face: a figure's)
|
|
lines.append(f"#define AF_{name}_CAP_Y {cap[3]} /* the ink of H: rows {cap[3]} .. {cap[3] + cap[5] - 1} of the line */")
|
|
lines.append(f"#define AF_{name}_CAP_H {cap[5]}")
|
|
if name == "S": # AF_X: the labels, tabs, header and footer (the 5 x 7 pixel face until V10.7.18): S itself,
|
|
init = lines[-3] # its ink 2 rows higher, so a place set for the pixel face (capitals from row 1) keeps its top
|
|
assert init.startswith("static const aafont_t AF_S = {") and init.endswith("};")
|
|
lines.append("static const aafont_t AF_X = {" + init[len("static const aafont_t AF_S = {"):-2] + ", 2};")
|
|
lines.append(f"#define AF_X_CAP_Y {cap[3] - 2}")
|
|
lines.append(f"#define AF_X_CAP_H {cap[5]}")
|
|
cost = {"data": len(data) + len(hc), "glyph_table": gsize, "kern": len(kp) + 2 * len(ki), "extras": len(extras),
|
|
"glyphs": len(chars), "phases": phases, "pairs": len(keys), "h": r["h"], "asc": r["asc"], "px": px,
|
|
"font": os.path.basename(font.split("#")[0]), "adv_digit": r["glyphs"]["0"][0] / 16}
|
|
cost["total"] = cost["data"] + cost["glyph_table"] + cost["kern"] + cost["extras"]
|
|
return "\n".join(lines) + "\n", cost
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("out")
|
|
ap.add_argument("--preset", choices=["standin", "inter-tight", "chakra-petch", "jiant-lab"])
|
|
ap.add_argument("--face", action="append", default=[])
|
|
ap.add_argument("--tracking", type=float, default=0.0, help="extra advance per glyph in em")
|
|
ap.add_argument("--gamma", type=float, default=1.0, help="coverage curve; <1 thickens light-on-dark text")
|
|
ap.add_argument("--kern-min", type=int, default=1, help="smallest kerning pair kept, in 1/16 px (0 pairs = no kerning)")
|
|
ap.add_argument("--huff", default=",".join(HUFF[0]), help="faces stored Huffman-coded (comma list, '' = none)")
|
|
a = ap.parse_args()
|
|
HUFF[0] = tuple(x for x in a.huff.split(",") if x)
|
|
faces = ([parse_face(s) for s in a.face] if a.face else []) or (preset(a.preset) if a.preset else None)
|
|
if not faces:
|
|
ap.error("--preset or --face is required")
|
|
out = ["/* generated by tools/gen_aa_font.py: 4-bit alpha glyphs (Inter Tight, SIL OFL 1.1, "
|
|
"Copyright 2022 The Inter Project Authors; see assets/fonts/OFL.txt) */",
|
|
"#pragma once", "#include <stdint.h>", ""]
|
|
total = 0
|
|
for f in faces:
|
|
text, c = emit(f, a.tracking, a.gamma, a.kern_min)
|
|
out.append(text)
|
|
total += c["total"]
|
|
print(f"face {f[0]}: {c['font']} {c['px']}px h{c['h']} base{c['asc']} {c['glyphs']} glyphs x {c['phases']} "
|
|
f"data {c['data']} B + table {c['glyph_table']} B + kern {c['kern']} B ({c['pairs']} pairs) "
|
|
f"= {c['total']} B digit adv {c['adv_digit']:.2f}px")
|
|
Path(a.out).write_text("\n".join(out))
|
|
print(f"fonts total {total} B -> {a.out}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
|