storebound/cli/shots/fonts.ts
CRT 55d8e2498f shots: glyph coverage check per language, automatic Noto fallbacks, check errors on fallback / system-font glyphs
Lilita One lacks most of Latin Extended-A (Turkish s-cedilla, g-breve, dotted I ...), so Turkish titles were drawn
with a silent browser fallback while shots check passed. shots fonts now reads the cmap of every face (pure TS,
TTF/OTF/WOFF/WOFF2), adds a Noto fallback per missing character or fails with language + characters; render
measures which face drew each character (CDP probes) and records it in report.json; check errors on fallbacks the
config did not choose (shots.fonts.fallback) and on system-font glyphs. Default game title font: Paytone One.
2026-10-11 19:05:23 +00:00

89 lines
5.5 KiB
TypeScript

// Downloads the fonts the screenshot template needs, subset by Google Fonts (css2 `text=`) to exactly the characters
// your copy uses, so even CJK stays small. `text=` pulls the glyphs from every subset the family has (latin, latin-ext,
// vietnamese, cyrillic, greek ...), so a missing glyph means the family itself lacks it.
// Then the glyph coverage check: every character of every language's copy (copy.json languages + config languages)
// is looked up in the cmap of the faces that draw it (title font: titles, badge values, app name; body font: eyebrows,
// sublines, badge labels; plus the Noto face of a non-Latin script). A character the stack lacks gets an automatic
// Noto fallback (logged; `shots check` errors on renders that used it unless shots.fonts.fallback lists it); a
// character no fallback covers fails with the language and the characters.
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
// All of these fonts are SIL Open Font License 1.1.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { shotsStyle } from '../lib/config';
import { type CopyFile, shotFonts } from './lib';
import { fontCodepoints } from './cmap';
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·';
export async function fetchSubset(family: string, chars: string, axis: string | null): Promise<ArrayBuffer> {
const fam = encodeURIComponent(family) + (axis ? ':' + axis : '');
let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } });
if (!res.ok && axis) return fetchSubset(family, chars, null);
if (!res.ok) throw new Error(`${family}: ${res.status} ${(await res.text()).slice(0, 200)}`);
const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1];
if (!src) throw new Error(`${family}: no font url`);
res = await fetch(src, { headers: { 'user-agent': UA } });
if (!res.ok) throw new Error(`${family}: ${res.status} for ${src}`);
return res.arrayBuffer();
}
/** Per-language role texts for every language of the copy and the config. */
export function langTexts(copy: CopyFile, langs: string[], appName: string): Record<string, RoleTexts> {
const out: Record<string, RoleTexts> = {};
for (const lang of [...new Set([...Object.keys(copy), ...langs])]) out[lang] = roleTexts(lang, copy[lang], appName);
return out;
}
export const fontsDirOf = (root: string): string => join(root, '.storebound', 'fonts');
export function readManifest(dir: string): FontManifest | null {
try { return JSON.parse(readFileSync(join(dir, 'fonts.json'), 'utf8')) as FontManifest; } catch { return null; }
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
const dir = fontsDirOf(root);
mkdirSync(dir, { recursive: true });
const style = shotsStyle(config);
const { title, body, titleVariable } = shotFonts(shots, style);
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
const sizes: string[] = [];
const manifest = await planFonts({
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII,
}, async (job: FaceJob) => {
let bin: Uint8Array;
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
if (job.kind !== 'fallback') throw e;
log('shots', `${job.family} has none of ${[...job.chars].join(' ')} (${(e as Error).message.split(' for ')[0]}), trying the next fallback`);
return new Set<number>();
}
writeFileSync(join(dir, job.file), bin);
const cps = fontCodepoints(bin);
sizes.push(`${job.file.padEnd(28)} ${job.family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...job.chars].length} chars asked, ${cps.size} in the cmap`);
return cps;
});
writeFileSync(join(dir, 'fonts.css'), fontsCss(manifest));
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
if (ctx.args.has('json')) return printJson(manifest);
for (const s of sizes) log('shots', s);
let auto = 0;
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
const ok = manifest.faces[f.face]?.chosen;
if (!ok) auto++;
const base = f.role === 'title' ? title : body;
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`);
}
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
done('shots', 'fonts done');
}