Der 8×10-Satz lässt sich nicht auf 24 px hochziehen: 3-px-Stamm bei 24 px Zelle ist 1:8, ein gezeichneter Satz hat 1:4. Deshalb zwei freie Schriften. - entschieden: Fließtext/UI Press Start 2P @24, Titel/Namensschild Pirata One @36 (final/Font/ttf/, OFL 1.1, Lizenzhinweis in ttf/README.md) - tools/font_ttf.py: TTF rastern (Schwelle 50 %, Versatz je Zeichen) - tools/font_ttf_export.py: BMFont + Atlas, 1× und 2×, Prüfung ohne Godot (116 Zeichen aus den Metriken gesetzt und pixelgleich verglichen) - final/Font/: pressstart2p_24 + pirataone_36 als .fnt/_atlas, ×2 - prep/font24/: Kandidatenvergleich (Fließtext und Titel getrennt), Skalierung als verworfener Weg, Belegbilder aus der .fnt
246 lines
10 KiB
Python
246 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""font_ttf_export.py — eine TTF/OTF als Engine-Font (BMFont + Textur-Atlas).
|
|
|
|
`font_export.py` exportiert den 8x10-Pixelsatz aus `font8.py`. Dasselbe hier
|
|
für eine echte Schriftdatei: gerastert wird über `font_ttf.py` (FreeType,
|
|
Schwelle bei 50 %), geschrieben wird das BMFont-Textformat plus PNG-Atlas —
|
|
das, was Godot als `FontFile` liest.
|
|
|
|
python3 tools/font_ttf_export.py --font final/Font/ttf/PressStart2P-Regular.ttf --size 24
|
|
python3 tools/font_ttf_export.py --font final/Font/ttf/PirataOne-Regular.ttf --size 36
|
|
python3 tools/font_ttf_export.py --check # beide pruefen, nichts schreiben
|
|
|
|
Erzeugt (je Schrift, in `final/Font/`):
|
|
|
|
<name>_atlas.png Glyphen weiss auf transparent
|
|
<name>.fnt BMFont, zeigt auf die 1x-Textur
|
|
<name>_atlas_2x.png dasselbe nearest-verdoppelt
|
|
<name>_2x.fnt BMFont fuer die 2x-Textur (alle Masse x2)
|
|
|
|
**Pruefung ohne Godot:** `--check` liest die geschriebene `.fnt` mit dem Parser
|
|
aus `font_export.py`, setzt alle Zeichen nur aus Metriken und Textur zusammen
|
|
und vergleicht Pixel fuer Pixel mit `font_ttf.Font.draw_text`. Weicht etwas ab,
|
|
ist die Datei falsch — nicht erst die Engine.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
ART = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(ART / "tools"))
|
|
import font_ttf # noqa: E402
|
|
from font_export import lies_fnt # noqa: E402 (gleicher BMFont-Leser)
|
|
|
|
# ASCII 32..126 plus die deutschen Zeichen. Mehr als `font8` (dem `# $ @ \\ ^
|
|
# _ ` { } | ~` fehlen) — die TTF hat sie, und ein fehlendes Zeichen waere in
|
|
# der Engine ein `?`.
|
|
ZEICHEN = ([chr(i) for i in range(32, 127)] + list("ÄÖÜäöüß")
|
|
# deutsche Satzzeichen, die ASCII nicht kennt: Anfuehrungszeichen,
|
|
# Halbgeviert-/Geviertstrich, Auslassung, Mittelpunkt, Euro, Guillemets
|
|
+ list("„“”‚‘’–—…·°€«»"))
|
|
ATLAS_BREITE = 512 # Zielbreite des Atlas; umbrochen wird nach Bedarf
|
|
LUFT = 1 # px zwischen zwei Glyphen im Atlas
|
|
|
|
SCHRIFTEN = [("PressStart2P-Regular.ttf", 24), ("PirataOne-Regular.ttf", 36)]
|
|
|
|
|
|
# ------------------------------------------------------------------ bauen ----
|
|
|
|
def atlas(font: font_ttf.Font, scale: int = 1):
|
|
"""Bild und Eintraege (Zeichen, Rect, Versatz, Vorschub) bauen."""
|
|
roh, fehlt = [], []
|
|
for ch in ZEICHEN:
|
|
maske, (dx, dy) = font.ink(ch)
|
|
eng = maske.getbbox()
|
|
if eng is None:
|
|
if ch == " ": # Leerzeichen: nur Vorschub
|
|
roh.append((ch, None, 0, 0, font.advance(ch)))
|
|
else: # Schrift hat das Zeichen nicht
|
|
fehlt.append(ch)
|
|
continue
|
|
teil = maske.crop(eng)
|
|
roh.append((ch, teil, dx + eng[0], dy + eng[1], font.advance(ch)))
|
|
|
|
x = y = zeilen_hoehe = 0
|
|
gesetzt = []
|
|
for ch, teil, ox, oy, adv in roh:
|
|
breite = teil.width if teil else 0
|
|
hoehe = teil.height if teil else 0
|
|
if x + breite > ATLAS_BREITE and x:
|
|
x, y = 0, y + zeilen_hoehe + LUFT
|
|
zeilen_hoehe = 0
|
|
gesetzt.append((ch, x, y, breite, hoehe, ox, oy, adv))
|
|
x += breite + LUFT
|
|
zeilen_hoehe = max(zeilen_hoehe, hoehe)
|
|
breite_ges = ATLAS_BREITE
|
|
hoehe_ges = y + zeilen_hoehe
|
|
|
|
im = Image.new("RGBA", (breite_ges, hoehe_ges), (0, 0, 0, 0))
|
|
for (ch, gx, gy, breite, hoehe, *_rest), eintrag in zip(gesetzt, roh):
|
|
teil = eintrag[1]
|
|
if teil is None:
|
|
continue
|
|
weiss = Image.new("RGBA", teil.size, (255, 255, 255, 255))
|
|
weiss.putalpha(teil)
|
|
im.alpha_composite(weiss, (gx, gy))
|
|
if fehlt:
|
|
print(f" Hinweis: fehlt in dieser Schrift und bleibt aussen vor: "
|
|
f"{''.join(fehlt)}")
|
|
if scale > 1:
|
|
im = im.resize((im.width * scale, im.height * scale), Image.NEAREST)
|
|
return im, gesetzt
|
|
|
|
|
|
def fnt(font: font_ttf.Font, gesetzt, scale: int, bild: str,
|
|
name: str, linehoehe: int, atlas_hoehe: int) -> str:
|
|
s = scale
|
|
zeilen = [
|
|
f'info face="{name}" size={font.size * s} bold=0 italic=0 charset="" '
|
|
f"unicode=1 stretchH=100 smooth=0 aa=1 padding=0,0,0,0 spacing=0,0 outline=0",
|
|
f"common lineHeight={linehoehe * s} base={font.ttf.getmetrics()[0] * s} "
|
|
f"scaleW={ATLAS_BREITE * s} scaleH={atlas_hoehe} pages=1 packed=0 "
|
|
f"alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
|
|
f'page id=0 file="{bild}"',
|
|
f"chars count={len(gesetzt)}",
|
|
]
|
|
for ch, gx, gy, breite, hoehe, ox, oy, adv in gesetzt:
|
|
zeilen.append(
|
|
f"char id={ord(ch)} x={gx * s} y={gy * s} width={breite * s} "
|
|
f"height={hoehe * s} xoffset={ox * s} yoffset={oy * s} "
|
|
f"xadvance={adv * s} page=0 chnl=15")
|
|
return "\n".join(zeilen) + "\n"
|
|
|
|
|
|
# -------------------------------------------------------------- pruefen ------
|
|
|
|
def setze(text: str, f: dict, breite: int, hoehe: int) -> Image.Image:
|
|
"""Text nur aus den .fnt-Metriken setzen (kein font_ttf)."""
|
|
bild = Image.open(f["dir"] / f["seite"]).convert("RGBA")
|
|
im = Image.new("RGBA", (breite, hoehe), (0, 0, 0, 0))
|
|
x = y = 0
|
|
for ch in text:
|
|
if ch == "\n":
|
|
x, y = 0, y + f["kopf"]["lineHeight"]
|
|
continue
|
|
c = f["chars"].get(ch) or f["chars"]["?"]
|
|
if c["width"] and c["height"]:
|
|
teil = bild.crop((c["x"], c["y"], c["x"] + c["width"],
|
|
c["y"] + c["height"]))
|
|
im.alpha_composite(teil, (x + c["xoffset"], y + c["yoffset"]))
|
|
x += c["xadvance"]
|
|
return im
|
|
|
|
|
|
def pruefen(font: font_ttf.Font, name: str, scale: int,
|
|
linehoehe: int) -> list[str]:
|
|
datei = f"{name}.fnt" if scale == 1 else f"{name}_2x.fnt"
|
|
f = lies_fnt(ART / "final" / "Font" / datei)
|
|
|
|
zeilen, cur = [], ""
|
|
for ch in ZEICHEN:
|
|
if font.text_width(cur + ch) > 900:
|
|
zeilen.append(cur)
|
|
cur = ""
|
|
cur += ch
|
|
if cur:
|
|
zeilen.append(cur)
|
|
|
|
breite = max(font.text_width(z) for z in zeilen) + 12
|
|
hoehe = linehoehe * len(zeilen) + 8
|
|
soll = Image.new("RGBA", (breite, hoehe), (0, 0, 0, 0))
|
|
for i, z in enumerate(zeilen):
|
|
font.draw_text(soll, 0, i * linehoehe, z, (255, 255, 255, 255))
|
|
if scale > 1:
|
|
soll = soll.resize((soll.width * scale, soll.height * scale),
|
|
Image.NEAREST)
|
|
|
|
ist = setze("\n".join(zeilen), f, soll.width, soll.height)
|
|
if ist.tobytes() == soll.tobytes():
|
|
return []
|
|
fehler = [f"{datei}: gesetzter Text weicht von draw_text ab"]
|
|
for i, z in enumerate(zeilen):
|
|
y0 = i * linehoehe * scale
|
|
a = ist.crop((0, y0, breite * scale, y0 + linehoehe * scale))
|
|
b = soll.crop((0, y0, breite * scale, y0 + linehoehe * scale))
|
|
if a.tobytes() != b.tobytes():
|
|
fehler.append(f" betroffen: Zeile {i + 1}: {z[:40]!r}")
|
|
break
|
|
return fehler
|
|
|
|
|
|
# ------------------------------------------------------------------ main -----
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
ap.add_argument("--font", type=Path, help="nur diese Schrift exportieren")
|
|
ap.add_argument("--size", type=int, help="Rastergroesse in px (Designgroesse)")
|
|
ap.add_argument("--name", help="Dateistamm (Vorgabe: <font>_<size>)")
|
|
ap.add_argument("--linehoehe", type=int,
|
|
help="Zeilenhöhe in px (Vorgabe: 1,5 x Groesse)")
|
|
ap.add_argument("--out", type=Path, default=ART / "final" / "Font")
|
|
ap.add_argument("--check", action="store_true", help="nur pruefen")
|
|
a = ap.parse_args(argv)
|
|
|
|
if a.check:
|
|
auftraege = ([(a.font, a.size)] if a.font else
|
|
[(ART / "final" / "Font" / "ttf" / d, s) for d, s in SCHRIFTEN])
|
|
fehler = []
|
|
for pfad, size in auftraege:
|
|
if size is None:
|
|
raise SystemExit(" --font braucht auch --size")
|
|
name = a.name or f"{pfad.stem.split('-')[0].lower()}_{size}"
|
|
lh = a.linehoehe or round(size * 1.5)
|
|
font = font_ttf.Font(pfad, size)
|
|
fehler += pruefen(font, name, 1, lh) + pruefen(font, name, 2, lh)
|
|
print(f" geprueft: {name} (1x und 2x)")
|
|
for f in fehler:
|
|
print(" ", f, file=sys.stderr)
|
|
print("\nPruefung:", "bestanden" if not fehler else "FEHLGESCHLAGEN")
|
|
return 1 if fehler else 0
|
|
|
|
if not (a.font and a.size):
|
|
raise SystemExit(" --font und --size angeben (oder --check).")
|
|
size, out = a.size, a.out
|
|
lh = a.linehoehe or round(size * 1.5)
|
|
name = a.name or f"{a.font.stem.split('-')[0].lower()}_{size}"
|
|
font = font_ttf.Font(a.font, size)
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
|
|
for s in (1, 2):
|
|
bild, gesetzt = atlas(font, s)
|
|
png = f"{name}_atlas{'' if s == 1 else '_2x'}.png"
|
|
fntname = f"{name}{'' if s == 1 else '_2x'}.fnt"
|
|
bild.save(out / png)
|
|
(out / fntname).write_text(
|
|
fnt(font, gesetzt, s, png, name, lh, bild.height))
|
|
print(f" {png:34s} {bild.width}x{bild.height}")
|
|
print(f" {fntname:34s} {len(gesetzt)} Zeichen, Zeile {lh * s}, "
|
|
f"Vorschub (M) {font.advance('M') * s}")
|
|
|
|
# Belegbild: derselbe Text, aber ueber die .fnt gesetzt (nicht font_ttf)
|
|
probe = ["Der Ghul greift an. ÄÖÜäöüß",
|
|
"Valyria zahlt 5 % in Ferrum —",
|
|
"Was wollt Ihr in Garana?"]
|
|
f = lies_fnt(out / f"{name}.fnt")
|
|
w = max(font.text_width(z) for z in probe) + 12
|
|
h = lh * len(probe) + 10
|
|
blatt = Image.new("RGBA", (w, h), (58, 47, 39, 255))
|
|
blatt.alpha_composite(setze("\n".join(probe), f, w, h), (5, 5))
|
|
ziel = ART / "prep" / "font24"
|
|
ziel.mkdir(parents=True, exist_ok=True)
|
|
blatt.save(ziel / f"_bmfont_probe_{name}.png")
|
|
print(f" {ziel}/_bmfont_probe_{name}.png (aus der .fnt gesetzt)")
|
|
|
|
fehler = pruefen(font, name, 1, lh) + pruefen(font, name, 2, lh)
|
|
for f_ in fehler:
|
|
print(" ", f_, file=sys.stderr)
|
|
print("\nPruefung:", "bestanden" if not fehler else "FEHLGESCHLAGEN")
|
|
return 1 if fehler else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|