| 4 | import { PNG } from 'pngjs'; |
| 5 | // Blitz experiment (docs/blitz-experiment.md), "PaintScene on CoreGraphics": the native renderers side by side |
| 6 | // from the desktop harness' --png-dir output (same corpus, same width and dpr, no browser involved). |
| 7 | // |
| 8 | // usage: corepack pnpm tsx scripts/blitz-experiment/gallery-native.mts <outDir> <label=pngDir[:tableTxt]>... [--strips N] [--crop X,Y,W,H] |
| 9 | // e.g. … reports/blitz-experiment/native vello=/tmp/gen-vello:/tmp/gen-vello.txt cg=/tmp/gen-cg:/tmp/gen-cg.txt litehtml=/tmp/gen-litehtml:/tmp/gen-litehtml.txt |
| 10 | // The first label is the baseline the pixel diffs are taken against. tableTxt is twidget-run's stdout (paint / loaded / height |
| 11 | // per widget). --strips N also writes strip-<widget>.png for the first N widgets: the same crop from every renderer stacked, |
| 12 | // 1:1 pixels, for looking at glyph rendering up close. |
| 13 | const argv = process.argv.slice(2); |
| 14 | const outDir = argv.shift(); |
| 15 | if (!outDir) throw new Error('usage: gallery-native.mts <outDir> <label=pngDir[:tableTxt]>... [--strips N] [--crop X,Y,W,H]'); |
| 16 | let strips = 0; |
| 17 | let crop = { x: 0, y: 0, w: 640, h: 220 }; |
| 18 | const sources: { label: string; dir: string; table?: string }[] = []; |
| 19 | for (let i = 0; i < argv.length; i++) { |
| 20 | const a = argv[i]; |
| 21 | if (a === '--strips') strips = Number(argv[++i]); |
| 22 | else if (a === '--crop') { const [x, y, w, h] = argv[++i].split(',').map(Number); crop = { x, y, w, h }; } |
| 23 | else { const eq = a.indexOf('='); const label = a.slice(0, eq); const [dir, table] = a.slice(eq + 1).split(':'); sources.push({ label, dir, table }); } |
| 24 | } |
| 25 | if (sources.length < 2) throw new Error('need at least two label=dir sources'); |
| 26 |
| 27 | type Row = { status: string; height: number; paintMs: number; loadedMs: number }; |
| 28 | function parseTable(file?: string): Map<string, Row> { |
| 29 | const m = new Map<string, Row>(); |
| 30 | if (!file || !fs.existsSync(file)) return m; |
| 31 | for (const line of fs.readFileSync(file, 'utf8').split('\n')) { |
| 32 | const r = /^(\S+\.html)\s+(\S+)\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+([\d.]+)ms\s+(\d+)ms/.exec(line); |
| 33 | if (r) m.set(r[1].replace(/\.html$/, ''), { status: r[2], height: Number(r[3]), paintMs: Number(r[4]), loadedMs: Number(r[5]) }); |
| 34 | } |
| 35 | return m; |
| 36 | } |
| 37 | const tables = sources.map((s) => parseTable(s.table)); |
| 38 | const pad = (img: PNG, w: number, h: number) => { if (img.width === w && img.height === h) return img; const o = new PNG({ width: w, height: h }); o.data.fill(0); PNG.bitblt(img, o, 0, 0, Math.min(img.width, w), Math.min(img.height, h), 0, 0); return o; }; |
| 39 | const readPng = (p: string) => (fs.existsSync(p) ? PNG.sync.read(fs.readFileSync(p)) : null); |
| 40 | const med = (xs: number[]) => { const s = xs.filter((x) => Number.isFinite(x)).sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : NaN; }; |
| 41 | const pct = (x: number) => (x * 100).toFixed(1) + '%'; |
| 42 |
| 43 | fs.mkdirSync(outDir, { recursive: true }); |
| 44 | for (const s of sources) fs.mkdirSync(path.join(outDir, s.label), { recursive: true }); |
| 45 | const stems = fs.readdirSync(sources[0].dir).filter((f) => f.endsWith('.png')).map((f) => f.replace(/\.png$/, '')).sort(); |
| 46 | const rows: string[] = []; |
| 47 | const stats: { stem: string; diff: number[]; paint: number[] }[] = []; |
| 48 | for (const [idx, stem] of stems.entries()) { |
| 49 | const imgs = sources.map((s) => readPng(path.join(s.dir, `${stem}.png`))); |
| 50 | for (const [i, s] of sources.entries()) if (imgs[i]) fs.copyFileSync(path.join(s.dir, `${stem}.png`), path.join(outDir, s.label, `${stem}.png`)); |
| 51 | const base = imgs[0]; |
| 52 | const diffs: number[] = []; |
| 53 | for (let i = 1; i < sources.length; i++) { |
| 54 | const other = imgs[i]; |
| 55 | if (!base || !other) { diffs.push(NaN); continue; } |
| 56 | const w = Math.max(base.width, other.width), h = Math.max(base.height, other.height); |
| 57 | const A = pad(base, w, h), B = pad(other, w, h); |
| 58 | const d = new PNG({ width: w, height: h }); |
| 59 | const n = pixelmatch(A.data, B.data, d.data, w, h, { threshold: 0.15, includeAA: true }); |
| 60 | fs.writeFileSync(path.join(outDir, sources[i].label, `${stem}.diff.png`), PNG.sync.write(d)); |
| 61 | diffs.push(n / (w * h)); |
| 62 | } |
| 63 | const paint = sources.map((_, i) => tables[i].get(stem)?.paintMs ?? NaN); |
| 64 | stats.push({ stem, diff: diffs, paint }); |
| 65 | if (idx < strips && imgs.every(Boolean)) { |
| 66 | const gap = 6; |
| 67 | const strip = new PNG({ width: crop.w, height: (crop.h + gap) * imgs.length - gap }); |
| 68 | strip.data.fill(255); |
| 69 | imgs.forEach((img, i) => { const w = Math.min(crop.w, img!.width - crop.x), h = Math.min(crop.h, img!.height - crop.y); if (w > 0 && h > 0) PNG.bitblt(img!, strip, crop.x, crop.y, w, h, 0, i * (crop.h + gap)); }); |
| 70 | fs.writeFileSync(path.join(outDir, `strip-${stem}.png`), PNG.sync.write(strip)); |
| 71 | } |
| 72 | const figs = sources.map((s, i) => { |
| 73 | const t = tables[i].get(stem); |
| 74 | const cap = [s.label, t ? `paint ${t.paintMs.toFixed(1)} ms` : '', t ? `${t.height} px` : '', i > 0 && Number.isFinite(diffs[i - 1]) ? `diff vs ${sources[0].label} ${pct(diffs[i - 1])}` : ''].filter(Boolean).join(' · '); |
| 75 | return imgs[i] ? `<figure><div class="shot"><img src="${s.label}/${stem}.png"></div><figcaption>${cap}</figcaption></figure>` : `<figure><figcaption>${s.label}: no frame</figcaption></figure>`; |
| 76 | }); |
| 77 | const zooms = sources.map((s, i) => (imgs[i] ? `<figure><div class="zoom"><img src="${s.label}/${stem}.png"></div><figcaption>${s.label} · 2×</figcaption></figure>` : '')); |
| 78 | const diffFigs = sources.slice(1).map((s) => `<figure><div class="shot"><img src="${s.label}/${stem}.diff.png"></div><figcaption>${s.label} vs ${sources[0].label}</figcaption></figure>`); |
| 79 | rows.push(`<section id="${stem}"><h2>${stem}</h2><div class="row">${figs.join('')}</div><details open><summary>text up close (2×, top-left corner)</summary><div class="row">${zooms.join('')}</div></details><details><summary>diff maps</summary><div class="row">${diffFigs.join('')}</div></details></section>`); |
| 80 | } |
| 81 | const summary = sources |
| 82 | .map((s, i) => `${s.label}: paint median ${med(stats.map((x) => x.paint[i])).toFixed(1)} ms${i > 0 ? `, diff vs ${sources[0].label} median ${pct(med(stats.map((x) => x.diff[i - 1])))}` : ''}`) |
| 83 | .join('; '); |
| 84 | const html = `<!doctype html><meta charset="utf-8"><title>twidget: native renderers side by side</title> |
| 85 | <style> |
| 86 | body{font:14px/1.4 -apple-system,system-ui,sans-serif;margin:16px;color:#111;background:#fff} |
| 87 | h1{font-size:20px}h2{font-size:15px;margin:28px 0 6px;font-weight:600} |
| 88 | .row{display:flex;gap:12px;align-items:flex-start} |
| 89 | figure{margin:0;flex:1;min-width:0}figcaption{font-size:12px;color:#555;margin-top:4px} |
| 90 | .shot img{width:100%;height:auto;display:block;border:1px solid #ddd;background:#fafafa} |
| 91 | .zoom{width:100%;aspect-ratio:${crop.w}/${crop.h};overflow:hidden;border:1px solid #ddd;position:relative;background:#fafafa} |
| 92 | .zoom img{position:absolute;left:0;top:0;transform:scale(2);transform-origin:0 0;image-rendering:pixelated;width:auto;height:auto;max-width:none} |
| 93 | details{margin-top:8px}summary{cursor:pointer;color:#555;font-size:12px} |
| 94 | nav{font-size:12px;color:#555;max-width:100%;overflow-wrap:anywhere} |
| 95 | </style> |
| 96 | <h1>Native renderers side by side: ${sources.map((s) => s.label).join(' | ')}</h1> |
| 97 | <p>${stems.length} widgets from one run <code>twidget-run --corpus … --png-dir</code> (same width and dpr). Diff is strict pixelmatch (threshold 0.15, AA on) against the first column.<br>${summary}</p> |
| 98 | <nav>${stems.map((s) => `<a href="#${s}">${s.slice(0, 24)}</a>`).join(' · ')}</nav> |
| 99 | ${rows.join('\n')} |
| 100 | <script> |
| 101 | // The zoom boxes show 1 image px per 2 CSS px of the top-left corner: scale the img to the natural pixel size first. |
| 102 | for (const img of document.querySelectorAll('.zoom img')) { const fit = () => { img.style.width = img.naturalWidth / 2 + 'px'; }; img.complete ? fit() : img.addEventListener('load', fit); } |
| 103 | </script>`; |
| 104 | fs.writeFileSync(path.join(outDir, 'gallery.html'), html); |
| 105 | fs.writeFileSync(path.join(outDir, 'stats.json'), JSON.stringify({ sources: sources.map((s) => s.label), stats }, null, 1)); |
| 106 | console.log(summary); |
| 107 | console.log(`gallery: ${path.join(outDir, 'gallery.html')} (${stems.length} widgets${strips ? `, ${Math.min(strips, stems.length)} strips` : ''})`); |
| 108 |