storebound/cli/shots/render.ts

157 lines
9.7 KiB
TypeScript

// Store screenshots + Play feature graphic at exact pixel sizes, from raw game frames and per-language copy.
// storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--variant b | --variants]
// [--no-sheet] [--port 8792] [--dry]
// Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png,
// <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags
// per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/...
// Default sizes: defaultSizes() (ipad13 only with apple.ipad). Needs playwright + ffmpeg.
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { join, relative } from 'node:path';
import { spawnSync } from 'node:child_process';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { launch } from './browser';
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib';
import { type RenderReport, mergeReport, readReport } from './report';
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const a = ctx.args;
const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id);
const sizes = a.list('size').length ? a.list('size') : defaultSizes(config);
for (const s of sizes) if (!SIZES[s]) throw new Error(`unknown size ${s} (${Object.keys(SIZES).join(', ')})`);
const variants: (string | undefined)[] = a.has('variants') ? [undefined, ...Object.keys(shots.variants ?? {})] : [a.get('variant')];
const baseCopy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
const jobs = new Map<string, { scenes: typeof shots.scenes; copy: CopyFile }>();
for (const v of variants) {
const scenes = variantScenes(shots, v);
const vc = v && shots.variants?.[v]?.copy ? JSON.parse(readFileSync(resolve(shots.variants[v]!.copy!), 'utf8')) as CopyFile : undefined;
const copy = mergeCopy(baseCopy, vc);
const problems = validateCopy(copy, { ...shots, scenes }, langs);
if (problems.length) throw new Error(`shots copy${v ? ` (variant ${v})` : ''}:\n ` + problems.join('\n '));
jobs.set(v ?? '', { scenes, copy });
}
const framesDir = resolve(shots.frames), outDir = resolve(shots.out);
if (a.has('dry')) {
let n = 0;
for (const [v, job] of jobs) for (const lang of langs) {
const scenes = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id);
const files = sizes.reduce((t, s) => t + (SIZES[s]!.feature ? 1 : scenes.length), 0);
n += files;
log('shots', `would render ${renderDir(outDir, lang, v || undefined)}: ${files} images (${sizes.join(', ')}; scenes ${scenes.join(', ')})`);
}
return done('shots', `render planned (dry run): ${n} images`);
}
const fontsDir = join(root, '.storebound', 'fonts');
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts)');
const { phone, tablet } = frameDims(config);
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
const fonts = { title: shots.fonts?.title ?? 'Lilita One', body: shots.fonts?.body ?? 'Montserrat' };
const tpl = import.meta.dir;
const server = Bun.serve({
port: a.num('port', 8792), hostname: '127.0.0.1',
async fetch(req) {
const url = new URL(req.url);
const p = decodeURIComponent(url.pathname);
if (p === '/job.json') {
const lang = url.searchParams.get('lang') ?? '';
const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!;
const text = copyText(lang, copy[lang]);
const script = scriptFont(lang, text);
const base = { phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } };
if (url.searchParams.has('feature'))
return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? scenes[0]!.palette) });
const sid = url.searchParams.get('s') ?? '';
const scene = scenes.find(s => s.id === sid)!;
const number = scenes.filter(s => !s.hero).indexOf(scene) + 1;
return Response.json({ ...base, scene, number, palette: palette(scene.palette), copy: copy[lang]?.[sid] ?? {} });
}
let file = '';
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
else if (/^\/(template|feature)\.html$/.test(p)) file = join(tpl, p.slice(1));
if (!file || file.includes('..')) return new Response('no', { status: 404 });
const f = Bun.file(file);
if (!(await f.exists())) return new Response('missing ' + p, { status: 404 });
return new Response(f, { headers: { 'content-type': TYPES[file.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream' } });
},
});
const base = `http://127.0.0.1:${server.port}`;
const browser = await launch(root, { headless: true });
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
let warnings = 0;
const report: RenderReport = {};
async function shoot(url: string, w: number, h: number, out: string): Promise<void> {
errs.length = 0;
mkdirSync(join(out, '..'), { recursive: true });
await page.setViewportSize({ width: w, height: h });
await page.goto(url, { waitUntil: 'load' });
await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 });
await page.waitForTimeout(200);
const tmp = out + '.tmp.png';
const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[];
if (!out.endsWith('sheet.png')) report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')) };
if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`);
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);
rmSync(tmp, { force: true });
if (r.status !== 0) throw new Error('ffmpeg: ' + r.stderr);
if (errs.length) warnings++;
log('shots', `${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
}
try {
for (const [v, job] of jobs) for (const lang of langs) {
const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id);
const vq = v ? `&v=${encodeURIComponent(v)}` : '';
const dir = renderDir(outDir, lang, v || undefined);
const rows: { size: string; files: string[] }[] = [];
for (const size of sizes) {
const s = SIZES[size]!;
if (s.feature) {
const f = join(dir, 'feature', '1024x500.png');
await shoot(`${base}/feature.html?lang=${encodeURIComponent(lang)}${vq}`, s.w, s.h, f);
rows.push({ size, files: [f] });
continue;
}
const files: string[] = [];
for (const [i, id] of sceneIds.entries()) {
const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`);
await shoot(`${base}/template.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, s.w, s.h, f);
files.push(f);
}
rows.push({ size, files });
}
if (!a.has('no-sheet') && rows.length) {
const lay = sheetLayout(rows);
const imgs = lay.tiles.map(t => `<img src="/out/${relative(outDir, t.file)}" style="position:absolute;left:${t.x}px;top:${t.y}px;width:${t.w}px;height:${t.h}px;border-radius:14px">`).join('');
const W = lay.w, y = lay.h;
const sheet = join(dir, '.sheet.html');
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${W}px;height:${y}px;position:relative">${imgs}
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(dir, 'sheet.png'));
rmSync(sheet, { force: true });
}
}
} finally {
await browser.close();
server.stop(true);
if (Object.keys(report).length) await Bun.write(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n');
}
const flagged = Object.values(report).filter(r => r.overflow.length).length;
if (flagged) warn('shots', `${flagged} images with text overflow flags: storebound shots check / shots gallery`);
done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`);
}