#!/usr/bin/env node
// Draws each screen's caption (the hero's name and tagline on a flat panel), the loading label and the loading bar
// onto its text-free art, locally, so every word is spelled exactly, and cuts the 1:1 profile crop. Everything sits
// inside the safe box from assets/safe-zones.json: inside the 3:4 profile-grid crop and clear of the app buttons and
// captions. The panel and the bar strip are solid, so the art behind them can never make the words hard to read.
//
// Usage:
// node scripts/compose-screens.mjs --plan screen.json --out-dir screens/
// [--font "Helvetica Neue"] [--font-file brand.ttf] [--per-screen-size] [--guides]
//
// Writes screens/screen-01.png ... (1080 x 1920 PNG), screens/profile-01.png ... (1080 x 1080 PNG, no text),
// screens/manifest.json (every text box, sizes, contrast and a fingerprint of each file) for
// scripts/check-screens.mjs, and screens/sheet.png when the plan has more than one screen.
// By default the whole set shares one name size and one tagline size, so the screens read as a series.
// --guides also writes screens/guides/screen-01.png ... with the safe zones and the profile crop drawn over each.
// --font-file takes a .ttf or .otf; set --font to that font's family name so it is picked.
// Needs sharp: run `npm install sharp` in the Skill folder (Node 20.9 or newer).
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
let sharp
try {
sharp = (await import('sharp')).default
} catch {
console.error('This script needs the sharp package. Run `npm install sharp` in the Skill folder (Node 20.9 or newer), then try again.')
process.exit(1)
}
const FLAGS = new Set(['plan', 'out-dir', 'font', 'font-file', 'per-screen-size', 'guides'])
const SWITCHES = new Set(['per-screen-size', 'guides'])
function fail(message) {
console.error(message)
process.exit(1)
}
const opts = {}
const argv = process.argv.slice(2)
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (!a.startsWith('--')) fail(`Unexpected argument "${a}". Flags look like --name value.`)
const key = a.slice(2)
if (!FLAGS.has(key)) fail(`Unknown flag --${key}. Allowed: ${[...FLAGS].map((f) => `--${f}`).join(', ')}`)
if (SWITCHES.has(key)) { opts[key] = true; continue }
const value = argv[i + 1]
if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`)
opts[key] = value
i++
}
if (!opts.plan || !opts['out-dir']) fail('Usage: node scripts/compose-screens.mjs --plan screen.json --out-dir screens/ [--font-file brand.ttf --font "Family"] [--per-screen-size] [--guides]')
if (!existsSync(opts.plan)) fail(`Plan not found: ${opts.plan}`)
let plan
try {
plan = JSON.parse(readFileSync(opts.plan, 'utf8'))
} catch {
fail(`${opts.plan} is not valid JSON.`)
}
if (plan.schema !== 'open-world-loading-screen/1') fail(`${opts.plan} schema is "${plan.schema}", expected open-world-loading-screen/1.`)
const zones = JSON.parse(readFileSync(new URL('../assets/safe-zones.json', import.meta.url), 'utf8'))
const base = dirname(resolve(opts.plan))
const rel = (p) => (isAbsolute(p) ? p : join(base, p))
const outDir = resolve(opts['out-dir'])
const style = plan.style ?? {}
const screens = plan.screens ?? []
if (screens.length < 1 || screens.length > 4) fail(`The plan has ${screens.length} screens. Plan 1 to 4.`)
const hex = (name, v) => {
if (typeof v !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(v)) fail(`style.${name} must be a #hex colour like #141414.`)
return v.toLowerCase()
}
const panelColour = hex('panel', style.panel ?? '#ffd23f')
const ink = hex('ink', style.ink ?? '#1a0f1f')
const accent = hex('accent', style.accent ?? '#ff3d7f')
const caseRule = style.case ?? 'upper'
const side = style.side ?? 'left'
if (!['upper', 'as-written'].includes(caseRule)) fail('style.case must be upper or as-written.')
if (!['left', 'right'].includes(side)) fail('style.side must be left or right.')
const family = opts.font ?? style.font ?? 'Helvetica Neue'
if (!/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,60}$/.test(family)) fail('The font must be a plain family name (letters, digits, spaces).')
const fontFile = opts['font-file'] ? resolve(opts['font-file']) : style.font_file ? rel(style.font_file) : ''
if (fontFile && !existsSync(fontFile)) fail(`Font file not found: ${fontFile}`)
const label = String(plan.loading?.label ?? 'LOADING').trim().toUpperCase()
const percent = Number(plan.loading?.percent ?? 64)
if (!/^[A-Z0-9 ]{3,14}$/.test(label)) fail('loading.label must be 3 to 14 letters, digits or spaces.')
if (!Number.isInteger(percent) || percent < 1 || percent > 99) fail('loading.percent must be a whole number from 1 to 99.')
const W = zones.frame.width
const H = zones.frame.height
const box = zones.title_box
const L = zones.layout
const drawn = (t) => (caseRule === 'upper' ? t.toUpperCase() : t)
for (const s of screens) {
if (typeof s.name !== 'string' || !s.name.trim()) fail(`Screen ${s.n} has no name.`)
if (typeof s.tagline !== 'string' || !s.tagline.trim()) fail(`Screen ${s.n} has no tagline.`)
if (s.name.trim().split(/\s+/).length > 3 || s.name.length > 20) fail(`Screen ${s.n} name "${s.name}" is over 3 words or 20 characters.`)
if (s.tagline.length > 60) fail(`Screen ${s.n} tagline "${s.tagline}" is over 60 characters.`)
if (!s.art) fail(`Screen ${s.n} has no approved art in "art". Generate it (build-requests.mjs --stage final) and put the path in screen.json.`)
if (!existsSync(rel(s.art))) fail(`Screen ${s.n} art not found: ${rel(s.art)}`)
const c = s.crop ?? {}
if (!(c.x >= 0 && c.x <= 1 && c.y >= 0 && c.y <= 1)) fail(`Screen ${s.n} crop.x and crop.y are fractions of the frame from 0 to 1 (where the hero's face is).`)
if (!(c.zoom >= 1 && c.zoom <= zones.profile.max_zoom)) fail(`Screen ${s.n} crop.zoom must be from 1 to ${zones.profile.max_zoom}.`)
}
const xml = (s) => String(s).replace(/[<>&]/g, (ch) => ({ '<': '<', '>': '>', '&': '&' })[ch])
const cache = new Map()
async function render(text, { size, color, spacing = 0 }) {
const key = JSON.stringify([text, size, color, spacing])
if (cache.has(key)) return cache.get(key)
const markup = `${xml(text)}`
const options = { text: markup, font: `${family} Bold ${size}`, rgba: true, dpi: 72 }
if (fontFile) options.fontfile = fontFile
const { data, info } = await sharp({ text: options }).png().toBuffer({ resolveWithObject: true })
const r = { input: data, width: info.width, height: info.height }
cache.set(key, r)
return r
}
const nameStyle = (size) => ({ size, color: ink, spacing: size * 0.01 })
const tagStyle = (size) => ({ size, color: ink, spacing: 0 })
const labelStyle = (size) => ({ size, color: panelColour, spacing: size * 0.14 })
async function pack(words, st, limit) {
const lines = []
let cur = ''
for (const w of words) {
const next = cur ? `${cur} ${w}` : w
if (cur && (await render(next, st)).width > limit) { lines.push(cur); cur = w } else cur = next
}
if (cur) lines.push(cur)
return lines
}
/** The fewest lines (at most maxLines) that fit the limit, balanced so no line is left with one short word; null if none fit. */
async function wrap(text, st, limit, maxLines) {
const words = text.split(/\s+/).filter(Boolean)
const widths = await Promise.all(words.map(async (w) => (await render(w, st)).width))
if (Math.max(...widths) > limit) return null
if ((await render(words.join(' '), st)).width <= limit) return [words.join(' ')]
for (let n = 2; n <= maxLines; n++) {
if ((await pack(words, st, limit)).length > n) continue
let lo = Math.max(...widths)
let hi = limit
while (hi - lo > 6) {
const mid = Math.round((lo + hi) / 2)
if ((await pack(words, st, mid)).length <= n) hi = mid
else lo = mid
}
return pack(words, st, hi)
}
return null
}
/** Where the ink of a line sits inside its rendered image, from a sample with tall and deep letters. */
const metrics = new Map()
async function inkBox(st, sample) {
const key = JSON.stringify([st.size, st.spacing, sample])
if (metrics.has(key)) return metrics.get(key)
const img = await render(sample, { ...st, color: '#000000' })
const { info } = await sharp(img.input).trim().toBuffer({ resolveWithObject: true })
const top = -(info.trimOffsetTop ?? 0)
const m = { top, bottom: top + info.height, height: info.height }
metrics.set(key, m)
return m
}
const innerLimit = L.panel_max_width - 2 * L.panel_pad
const nameSample = caseRule === 'upper' ? 'H0' : 'Hhdkgjpqy'
async function nameLines(s, size) {
return wrap(drawn(s.name.trim()), nameStyle(size), innerLimit, 2)
}
async function largestName(s) {
for (let size = zones.max_name_px; size >= zones.min_name_px; size -= 4) if (await nameLines(s, size)) return size
return 0
}
async function taglineSize(maxLines) {
for (let size = zones.max_tagline_px; size >= zones.min_tagline_px; size -= 2) {
let ok = true
for (const s of screens) if (!(await wrap(s.tagline.trim(), tagStyle(size), innerLimit, maxLines))) { ok = false; break }
if (ok) return size
}
return 0
}
const nameFits = []
for (const s of screens) {
const size = await largestName(s)
if (!size) fail(`Screen ${s.n}: "${drawn(s.name)}" does not fit in 2 lines at ${zones.min_name_px} px inside a ${L.panel_max_width} px panel. Shorten it (a long word is the usual cause).`)
nameFits.push(size)
}
const sharedName = Math.min(...nameFits)
let sharedTag = await taglineSize(2)
let tagMax = 2
if (!sharedTag) { sharedTag = await taglineSize(3); tagMax = 3 }
if (!sharedTag) fail(`A tagline does not fit in 3 lines at ${zones.min_tagline_px} px. Shorten it.`)
const labelSize = 34
function luminance(r, g, b) {
const lin = (v) => {
const s = v / 255
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
}
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
}
const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16))
const ratio = (a, b) => {
const la = luminance(...rgb(a))
const lb = luminance(...rgb(b))
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
}
const sha = (buf) => createHash('sha256').update(buf).digest('hex')
mkdirSync(outDir, { recursive: true })
if (opts.guides) mkdirSync(join(outDir, 'guides'), { recursive: true })
const records = []
const pad = L.panel_pad
const stroke = L.panel_stroke
const shadow = L.panel_shadow
for (const [index, s] of screens.entries()) {
const nSize = opts['per-screen-size'] ? nameFits[index] : sharedName
const nSt = nameStyle(nSize)
const tSt = tagStyle(sharedTag)
const lSt = labelStyle(labelSize)
const nLines = await nameLines(s, nSize)
const tLines = await wrap(s.tagline.trim(), tSt, innerLimit, tagMax)
const nImgs = await Promise.all(nLines.map((t) => render(t, nSt)))
const tImgs = await Promise.all(tLines.map((t) => render(t, tSt)))
const nm = await inkBox(nSt, nameSample)
const tm = await inkBox(tSt, 'Hhdkgjpqy')
const lm = await inkBox(lSt, 'H0')
const namePitch = nm.height + Math.round(nSize * 0.16)
const tagPitch = Math.round(sharedTag * 1.3)
const nameH = namePitch * (nLines.length - 1) + nm.height
const tagH = tagPitch * (tLines.length - 1) + tm.height
const ruleGap = 24
const ruleH = 10
const panelW = Math.max(300, Math.max(...nImgs.map((i) => i.width), ...tImgs.map((i) => i.width)) + 2 * pad)
const panelH = pad + nameH + ruleGap + ruleH + ruleGap + tagH + pad
// The loading strip: label and percent over a bar, on a solid ink block the width of the panel.
const stripPad = 20
const barH = 26
const stripH = Math.max(L.strip_height, stripPad + lm.height + 14 + barH + stripPad)
const stripY = L.stack_bottom - stripH
// The strip is a column with the panel, on the plan's side, so the other side of the frame stays the hero's.
const stripW = Math.min(box.width, Math.max(L.strip_min_width, panelW + stroke + shadow))
const stripX = side === 'left' ? box.x : box.x + box.width - stripW
const labelImg = await render(label, lSt)
const percentImg = await render(`${percent}%`, lSt)
const labelY = stripY + stripPad
const barX = stripX + 28
const barW = stripW - 56
const barY = labelY + lm.height + 14
const fillW = Math.round((barW * percent) / 100)
// The panel, above the strip, on the plan's side. The hard shadow falls down and to the right.
const panelBottomOuter = stripY - L.gap_panel_strip
const panelY = panelBottomOuter - shadow - panelH
const panelX = side === 'left' ? box.x + stroke / 2 : box.x + box.width - stroke / 2 - shadow - panelW
if (panelY - stroke / 2 < box.y) fail(`Screen ${s.n}: the caption is too tall to fit above the loading bar inside the safe box (it needs ${Math.round(panelH + stroke + shadow + L.gap_panel_strip + stripH)} px of ${box.height}). Shorten the tagline or the name.`)
const nameTop = panelY + pad
const tagTop = nameTop + nameH + ruleGap + ruleH + ruleGap
const ruleY = nameTop + nameH + ruleGap
const textLeft = panelX + pad
const layers = []
const boxes = []
boxes.push({ role: 'panel', x: Math.round(panelX - stroke / 2), y: Math.round(panelY - stroke / 2), width: Math.round(panelW + stroke + shadow), height: Math.round(panelH + stroke + shadow) })
for (const [i, img] of nImgs.entries()) {
const top = nameTop + i * namePitch
layers.push({ input: img.input, left: Math.round(textLeft), top: Math.round(top - nm.top) })
boxes.push({ role: 'name', line: i + 1, x: Math.round(textLeft), y: Math.round(top), width: img.width, height: nm.height })
}
for (const [i, img] of tImgs.entries()) {
const top = tagTop + i * tagPitch
layers.push({ input: img.input, left: Math.round(textLeft), top: Math.round(top - tm.top) })
boxes.push({ role: 'tagline', line: i + 1, x: Math.round(textLeft), y: Math.round(top), width: img.width, height: tm.height })
}
boxes.push({ role: 'strip', x: stripX, y: stripY, width: stripW, height: stripH })
layers.push({ input: labelImg.input, left: barX, top: Math.round(labelY - lm.top) })
boxes.push({ role: 'label', x: barX, y: labelY, width: labelImg.width, height: lm.height })
const percentX = barX + barW - percentImg.width
layers.push({ input: percentImg.input, left: percentX, top: Math.round(labelY - lm.top) })
boxes.push({ role: 'percent', x: percentX, y: labelY, width: percentImg.width, height: lm.height })
boxes.push({ role: 'bar', x: barX, y: barY, width: barW, height: barH })
const shapes = [
``,
``,
``,
``,
``,
``,
``,
]
const svg = Buffer.from(``)
const art = rel(s.art)
const baseImage = await sharp(art).resize(W, H, { fit: 'cover' }).png().toBuffer()
const meta = await sharp(art).metadata()
if (meta.width < W || meta.height < H) console.warn(`warning: screen ${s.n} art is ${meta.width} x ${meta.height}, smaller than ${W} x ${H}, so it is upscaled. Use the final art (1088 x 1936), not a draft.`)
if (Math.abs(meta.width / meta.height - 9 / 16) > 0.02) console.warn(`warning: screen ${s.n} art is ${meta.width} x ${meta.height}, not 9:16, so its edges are cropped.`)
const name = `screen-${String(s.n).padStart(2, '0')}.png`
const png = await sharp(baseImage).composite([{ input: svg, left: 0, top: 0 }, ...layers]).png().toBuffer()
writeFileSync(join(outDir, name), png)
// The 1:1 profile crop: the plain art, no text, centred on the hero's face.
const c = s.crop
const side1 = Math.round(zones.profile.size / c.zoom)
const left = Math.min(W - side1, Math.max(0, Math.round(c.x * W - side1 / 2)))
const top = Math.min(H - side1, Math.max(0, Math.round(c.y * H - side1 / 2)))
const profilePng = await sharp(baseImage).extract({ left, top, width: side1, height: side1 }).resize(zones.profile.size, zones.profile.size).png().toBuffer()
const profileName = `profile-${String(s.n).padStart(2, '0')}.png`
writeFileSync(join(outDir, profileName), profilePng)
const faceX = (c.x * W - left) / side1
const faceY = (c.y * H - top) / side1
const faceOffset = Math.hypot(faceX - 0.5, faceY - 0.5)
if (faceOffset > zones.profile.circle_ratio) console.warn(`warning: screen ${s.n} the face centre is ${(faceOffset * 100).toFixed(0)} percent of the side from the middle of the profile crop; apps show it as a circle. Move crop.x and crop.y onto the face.`)
if (opts.guides) {
const keepOut = zones.zones.filter((z) => z.kind === 'keep-out').map((z) => ``)
const grid = zones.zones.find((z) => z.id === 'grid-3x4').rect
const guide = ``
await sharp(png).composite([{ input: Buffer.from(guide), left: 0, top: 0 }]).png().toFile(join(outDir, 'guides', name))
}
records.push({
n: s.n,
file: name,
sha256: sha(png),
art: relative(outDir, art),
art_sha256: sha(readFileSync(art)),
name: s.name,
name_drawn: drawn(s.name.trim()),
name_lines: nLines,
name_px: nSize,
tagline: s.tagline,
tagline_drawn: s.tagline.trim(),
tagline_lines: tLines,
tagline_px: sharedTag,
label_drawn: label,
label_px: labelSize,
percent_drawn: `${percent}%`,
bar_fill_percent: percent,
boxes,
contrast: { text_on_panel: Number(ratio(ink, panelColour).toFixed(2)), label_on_strip: Number(ratio(panelColour, ink).toFixed(2)), bar_on_strip: Number(ratio(accent, ink).toFixed(2)) },
profile: { file: profileName, sha256: sha(profilePng), size: zones.profile.size, left, top, side: side1, zoom: c.zoom, face_offset: Number(faceOffset.toFixed(3)) },
})
const bottom = Math.max(...boxes.map((b) => b.y + b.height))
console.log(`${join(outDir, name)} ${W}x${H}, name ${nSize}px (${nLines.length} line${nLines.length === 1 ? '' : 's'}), tagline ${sharedTag}px (${tLines.length}), caption from y ${Math.min(...boxes.map((b) => b.y))} to ${bottom}, contrast ${ratio(ink, panelColour).toFixed(1)}:1; profile ${profileName} ${zones.profile.size}x${zones.profile.size}`)
}
// A contact sheet when there is more than one screen, so the set can be seen side by side.
let sheet
if (screens.length > 1) {
const tileW = 360
const tileH = 640
const gap = 12
const cols = screens.length === 4 ? 2 : screens.length
const rows = Math.ceil(screens.length / cols)
const tiles = await Promise.all(records.map(async (r, i) => ({
input: await sharp(join(outDir, r.file)).resize(tileW, tileH).png().toBuffer(),
left: gap + (i % cols) * (tileW + gap),
top: gap + Math.floor(i / cols) * (tileH + gap),
})))
const sheetPng = await sharp({ create: { width: gap + cols * (tileW + gap), height: gap + rows * (tileH + gap), channels: 3, background: '#ffffff' } }).composite(tiles).png().toBuffer()
writeFileSync(join(outDir, 'sheet.png'), sheetPng)
sheet = { file: 'sheet.png', sha256: sha(sheetPng), screens: records.map((r) => ({ n: r.n, sha256: r.sha256 })) }
console.log(`${join(outDir, 'sheet.png')} the set side by side.`)
}
const manifest = {
schema: 'open-world-loading-screen-manifest/1',
plan: relative(outDir, resolve(opts.plan)),
zones_checked: zones.checked,
frame: { width: W, height: H },
settings: { font: fontFile ? relative(outDir, fontFile) : family, panel: panelColour, ink, accent, case: caseRule, side, shared_size: !opts['per-screen-size'], name_px: sharedName, tagline_px: sharedTag, label: label, percent },
screens: records,
...(sheet ? { sheet } : {}),
}
writeFileSync(join(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
console.log(`${join(outDir, 'manifest.json')} written. Next: node scripts/check-screens.mjs --plan ${opts.plan} --manifest ${join(opts['out-dir'], 'manifest.json')}`)