|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Build the stroke-data JSON consumed by StrokeSketch. |
| 4 | +
|
| 5 | +For each requested character, the output carries: |
| 6 | + - glyph: Huiwen Mincho's full SVG outline path, scaled to a 1024 em |
| 7 | + box so it shares the coord system MMH medians live in. y-up, |
| 8 | + baseline at 0, ascender ~900, descender ~-124. |
| 9 | + - medians: list of stroke medians from make-me-a-hanzi, one inner |
| 10 | + array per stroke (`[[x, y], ...]`). These are the centerlines — |
| 11 | + StrokeSketch uses them to clip the Huiwen glyph into per-stroke |
| 12 | + bitmaps at runtime. |
| 13 | +
|
| 14 | +We keep only what the sketch consumes — no stroke outline polygons |
| 15 | +(the Huiwen path replaces them visually) and no per-stroke rendering |
| 16 | +metadata (bbox, etc., are computed in JS). |
| 17 | +
|
| 18 | +Usage: |
| 19 | + python scripts/build-strokes.py # PROTOTYPE_CHARS |
| 20 | + python scripts/build-strokes.py 字的颗粒度 # explicit set |
| 21 | +""" |
| 22 | +import json |
| 23 | +import sys |
| 24 | +from pathlib import Path |
| 25 | +from typing import Optional |
| 26 | + |
| 27 | +from fontTools.ttLib import TTFont |
| 28 | +from fontTools.pens.svgPathPen import SVGPathPen |
| 29 | +from fontTools.pens.transformPen import TransformPen |
| 30 | +from fontTools.misc.transform import Transform |
| 31 | + |
| 32 | +HERE = Path(__file__).resolve().parent |
| 33 | +ROOT = HERE.parent |
| 34 | +MMH_SRC = ROOT / "data" / "makemeahanzi" / "graphics.txt" |
| 35 | +FONT_SRC = ROOT / "src" / "assets" / "fonts" / "huiwen-mincho.ttf" |
| 36 | +OUT = ROOT / "public" / "data" / "strokes.json" |
| 37 | + |
| 38 | +# Title + a representative flood-cue phrase. Picked for stroke-count |
| 39 | +# variety so the sketch reads as a mix of light/dense glyphs. |
| 40 | +PROTOTYPE_CHARS = "字的颗粒度这一段汉横跨整片海" |
| 41 | + |
| 42 | +# MMH medians live in a 1024-wide em box. We scale Huiwen to match so |
| 43 | +# the two data sources align without further per-char tweaks. |
| 44 | +TARGET_UPEM = 1024 |
| 45 | + |
| 46 | + |
| 47 | +def extract_glyph_path(font: TTFont, char: str) -> Optional[str]: |
| 48 | + """Huiwen glyph as an SVG path string in the target 1024 em space. |
| 49 | + The font's own units-per-em can be anything (Huiwen Mincho is 1000); |
| 50 | + the TransformPen rescales as the path streams through. Returns None |
| 51 | + if the char isn't covered by the font's cmap.""" |
| 52 | + cmap = font.getBestCmap() |
| 53 | + cp = ord(char) |
| 54 | + if cp not in cmap: |
| 55 | + return None |
| 56 | + glyph_set = font.getGlyphSet() |
| 57 | + glyph = glyph_set[cmap[cp]] |
| 58 | + |
| 59 | + upem = font["head"].unitsPerEm |
| 60 | + s = TARGET_UPEM / upem |
| 61 | + |
| 62 | + pen = SVGPathPen(glyph_set) |
| 63 | + glyph.draw(TransformPen(pen, Transform().scale(s, s))) |
| 64 | + return pen.getCommands() |
| 65 | + |
| 66 | + |
| 67 | +def main(): |
| 68 | + chars = sys.argv[1] if len(sys.argv) > 1 else PROTOTYPE_CHARS |
| 69 | + wanted = set(chars) |
| 70 | + print(f"extracting {len(wanted)} char(s): {''.join(sorted(wanted))}") |
| 71 | + |
| 72 | + if not MMH_SRC.exists(): |
| 73 | + sys.exit( |
| 74 | + f"missing {MMH_SRC}\n" |
| 75 | + " run: curl -sL -o data/makemeahanzi/graphics.txt " |
| 76 | + "https://raw.githubusercontent.com/skishore/makemeahanzi/master/graphics.txt" |
| 77 | + ) |
| 78 | + if not FONT_SRC.exists(): |
| 79 | + sys.exit(f"missing {FONT_SRC}") |
| 80 | + |
| 81 | + font = TTFont(str(FONT_SRC)) |
| 82 | + print(f" font unitsPerEm = {font['head'].unitsPerEm} → normalize to {TARGET_UPEM}") |
| 83 | + |
| 84 | + # MMH file is line-delimited JSON. We only need medians. |
| 85 | + mmh = {} |
| 86 | + with MMH_SRC.open(encoding="utf-8") as f: |
| 87 | + for line in f: |
| 88 | + if not line.strip(): |
| 89 | + continue |
| 90 | + entry = json.loads(line) |
| 91 | + ch = entry.get("character") |
| 92 | + if ch in wanted: |
| 93 | + mmh[ch] = entry["medians"] |
| 94 | + if len(mmh) == len(wanted): |
| 95 | + break |
| 96 | + |
| 97 | + out = {} |
| 98 | + missing = [] |
| 99 | + for ch in wanted: |
| 100 | + path = extract_glyph_path(font, ch) |
| 101 | + medians = mmh.get(ch) |
| 102 | + if path is None: |
| 103 | + missing.append(f"{ch} (no Huiwen glyph)") |
| 104 | + continue |
| 105 | + if medians is None: |
| 106 | + missing.append(f"{ch} (no MMH medians)") |
| 107 | + continue |
| 108 | + out[ch] = {"glyph": path, "medians": medians} |
| 109 | + |
| 110 | + if missing: |
| 111 | + print(f" WARNING: dropped {missing}") |
| 112 | + |
| 113 | + OUT.parent.mkdir(parents=True, exist_ok=True) |
| 114 | + OUT.write_text( |
| 115 | + json.dumps(out, ensure_ascii=False, separators=(",", ":")), |
| 116 | + encoding="utf-8", |
| 117 | + ) |
| 118 | + size_kb = OUT.stat().st_size / 1024 |
| 119 | + total_strokes = sum(len(v["medians"]) for v in out.values()) |
| 120 | + print( |
| 121 | + f"wrote {OUT.relative_to(ROOT)}: " |
| 122 | + f"{len(out)} char(s), {total_strokes} stroke(s), {size_kb:.1f} KB" |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + main() |
0 commit comments