3D engine that AI agents drive
# Writes src/font-default.js, the outlines of the printable ASCII characters of one TrueType font, as plain integers.
# uv run --no-project --with fonttools python scripts/build-font.py <font.ttf>
# The bundled font is DejaVu Sans 2.37 (Bitstream Vera licence, public domain changes; notice in THIRD-PARTY-NOTICES.md).
import json
import sys
from pathlib import Path
from fontTools.ttLib import TTFont
FIRST_CHARACTER = 32
LAST_CHARACTER = 126
OUTPUT = Path(__file__).resolve().parent.parent / "src" / "font-default.js"
def glyph_record(font, name):
glyph = font["glyf"][name]
record = [font["hmtx"][name][0]]
if glyph.numberOfContours <= 0:
return record
coordinates, end_points, flags = glyph.getCoordinates(font["glyf"])
start = 0
for end in end_points:
contour = []
for index in range(start, end + 1):
x, y = coordinates[index]
contour.extend([int(x), int(y), flags[index] & 1])
# Some fonts keep a one-point contour as an anchor; it has no area.
if len(contour) >= 9:
record.append(contour)
start = end + 1
return record
def main():
font = TTFont(sys.argv[1])
cmap = font.getBestCmap()
glyphs = {}
for code in range(FIRST_CHARACTER, LAST_CHARACTER + 1):
glyphs[chr(code)] = glyph_record(font, cmap[code])
table = {
"name": "DejaVu Sans",
"unitsPerEm": font["head"].unitsPerEm,
"ascender": font["hhea"].ascent,
"descender": font["hhea"].descent,
"glyphs": glyphs,
}
text = json.dumps(table, separators=(",", ":"))
header = (
"// DejaVu Sans 2.37, printable ASCII outlines, generated by scripts/build-font.py. Copyright (c) 2003 Bitstream, Inc.\n"
"// Changes by DejaVu are in the public domain. Licence text: THIRD-PARTY-NOTICES.md.\n"
"// Glyph: [advance, contour...]. Contour: x, y, onCurve repeated, in font units (TrueType quadratic points).\n"
)
OUTPUT.write_text(f"{header}export const DEFAULT_FONT_DATA = JSON.parse({json.dumps(text)});\n", encoding="utf-8")
print(f"Wrote {len(text)} bytes for {len(glyphs)} glyphs.")
main()