#!/usr/bin/env node
// Draws the exact labels on the approved text-free art and writes the character sheet board. The image model never
// draws text: the character's name, the view names and the expression names are drawn here, in calm bands the prompt
// kept empty. It measures how much art sits under each label, whether each of the eight cells holds a figure and
// whether any two figures touch, and writes all of it to character-sheet.jpg.json for check-sheet.mjs.
// It also sets character.reference (the text-free art, which later shots attach) and character.sheet (the board).
//
// Usage:
// node scripts/compose-sheet.mjs --character character.json --art art/sheet-high-1.jpg --out character-sheet.jpg
// [--font Helvetica] [--font-file brand.ttf] [--guides] [--no-update]
//
// --guides also writes character-sheet.guides.jpg with the eight cells, the label boxes drawn over the art.
// Needs sharp: run `npm install sharp` in the Skill folder (Node.js 20.9 or newer).
import { createHash } from 'node:crypto'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { fail, parseArgs } from './character-lib.mjs'
let sharp
try {
sharp = (await import('sharp')).default
} catch {
fail('This script needs the sharp package. Run `npm install sharp` in the Skill folder (Node.js 20.9 or newer), then try again.')
}
const opts = parseArgs(process.argv.slice(2), ['character', 'art', 'out', 'font', 'font-file', 'guides', 'no-update'], ['guides', 'no-update'])
if (!opts.character || !opts.out) fail('Usage: node scripts/compose-sheet.mjs --character character.json --art art.jpg --out character-sheet.jpg [--font-file brand.ttf --font "Family"] [--guides] [--no-update]')
if (!/\.jpe?g$/i.test(opts.out)) fail('--out must end in .jpg (the board is a JPEG).')
if (!existsSync(opts.character)) fail(`Not found: ${opts.character}`)
const ch = JSON.parse(readFileSync(opts.character, 'utf8'))
const layout = JSON.parse(readFileSync(new URL('../assets/layout.json', import.meta.url), 'utf8'))
const base = dirname(resolve(opts.character))
const outAbs = resolve(opts.out)
const artArg = opts.art ?? ch.reference
if (!artArg) fail('Give the approved text-free art with --art (or set character.reference).')
const artAbs = isAbsolute(artArg) ? artArg : existsSync(resolve(artArg)) ? resolve(artArg) : join(base, artArg)
if (!existsSync(artAbs)) fail(`Art not found: ${artAbs}`)
const { width: W, height: H } = layout.canvas
const fontFile = opts['font-file'] ? resolve(opts['font-file']) : undefined
if (fontFile && !existsSync(fontFile)) fail(`Font file not found: ${fontFile}`)
const family = opts.font ?? 'Helvetica'
if (!/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,60}$/.test(family)) fail('--font must be a plain font family name.')
const artInfo = await sharp(artAbs).metadata()
if (!artInfo.width) fail(`Cannot read the art: ${artAbs}`)
const resized = artInfo.width !== W || artInfo.height !== H
if (resized) console.error(`warning: the art is ${artInfo.width} x ${artInfo.height}, not ${W} x ${H}; it is resized to the board. Layout bands may not line up: make the sheet at ${W} x ${H}.`)
const artBuf = await sharp(artAbs).resize(W, H, { fit: 'fill' }).removeAlpha().jpeg({ quality: 95 }).toBuffer()
const { data: px } = await sharp(artBuf).raw().toBuffer({ resolveWithObject: true })
const L = layout
const lim = L.limits
const R = (x0, y0, x1, y1) => ({ x: Math.round(x0 * W), y: Math.round(y0 * H), width: Math.round((x1 - x0) * W), height: Math.round((y1 - y0) * H) })
const t = L.turnaround
const e = L.expressions
const figCols = t.views.map((_, i) => [t.x0 + i * (t.cell_width + t.gap), t.x0 + i * (t.cell_width + t.gap) + t.cell_width])
const exCols = [0, 1].map((i) => [e.x0 + i * (e.cell_width + e.gap), e.x0 + i * (e.cell_width + e.gap) + e.cell_width])
const leftEnd = figCols[3][1]
// ---- measuring ----
const idx = (x, y) => (y * W + x) * 3
function median(rect, step = 3) {
const out = []
for (let ch2 = 0; ch2 < 3; ch2++) {
const hist = new Uint32Array(256)
let n = 0
for (let y = rect.y; y < rect.y + rect.height; y += step) for (let x = rect.x; x < rect.x + rect.width; x += step) { hist[px[idx(x, y) + ch2]]++; n++ }
let seen = 0
let v = 0
for (; v < 256; v++) { seen += hist[v]; if (seen >= n / 2) break }
out.push(Math.min(v, 255))
}
return out
}
function offPercent(rect, ref) {
const x1 = Math.min(W, rect.x + rect.width)
const y1 = Math.min(H, rect.y + rect.height)
let off = 0
let n = 0
for (let y = Math.max(0, rect.y); y < y1; y++) {
for (let x = Math.max(0, rect.x); x < x1; x++) {
const i = idx(x, y)
const d = Math.abs(px[i] - ref[0]) + Math.abs(px[i + 1] - ref[1]) + Math.abs(px[i + 2] - ref[2])
if (d > lim.backdrop_distance) off++
n++
}
}
return n ? Number(((100 * off) / n).toFixed(2)) : 0
}
const lum = ([r, g, b]) => {
const f = (v) => { const s = v / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4 }
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
}
const ratio = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
const backdrop = median(R(0.0, 0.004, 1, L.header.y[1] - 0.004))
// Black and white text have equal contrast on a backdrop of relative luminance about 0.18; mid greys (a model's "light grey"
// often renders near 0.34) read better with dark text.
const darkBackdrop = lum(backdrop) < 0.18
const ink = darkBackdrop ? '#f3f1ee' : '#1b1b1b'
const muted = darkBackdrop ? '#e0ddd6' : '#2f2d2a'
// ---- text ----
const xml = (s) => String(s).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' })[c])
const cache = new Map()
async function text(str, { size, bold = false, color = ink, spacing = 0 }) {
const key = JSON.stringify([str, size, bold, color, spacing])
if (cache.has(key)) return cache.get(key)
const markup = `${xml(str)}`
const o = { text: markup, font: `${family}${bold ? ' Bold' : ''} ${Math.round(size)}`, rgba: true, dpi: 72 }
if (fontFile) o.fontfile = fontFile
const { data, info } = await sharp({ text: o }).png().toBuffer({ resolveWithObject: true })
const out = { input: data, width: info.width, height: info.height }
cache.set(key, out)
return out
}
const labels = []
const layers = []
const place = async (id, role, str, style, cx, top, align = 'center') => {
const img = await text(str, style)
const left = align === 'center' ? Math.round(cx - img.width / 2) : Math.round(cx)
layers.push({ input: img.input, left, top: Math.round(top) })
labels.push({ id, role, text: str, x: left, y: Math.round(top), width: img.width, height: img.height })
}
const labelStyle = { size: L.label.size * H, bold: true, spacing: L.label.spacing, color: ink }
// A model keeps its own spacing whatever the prompt says, so a label is set in the calm gap the art actually left under
// its figure: the longest run of empty rows in the label's columns, near the nominal band. If no gap is tall enough the
// label stays in the nominal band and the art-under-label measure fails it (re-roll the sheet).
function emptyTop(img, cx, band) {
const mg = L.label.margin_px
const xa = Math.max(0, Math.round(cx - img.width / 2 - mg))
const xb = Math.min(W, Math.round(cx + img.width / 2 + mg))
const lo = Math.max(0, Math.round(band.y - 0.05 * H))
const hi = Math.min(H, Math.round(band.y + band.height + 0.03 * H))
const need = img.height + 2 * mg
const nominal = band.y + (band.height - img.height) / 2
let best = null
let start = -1
for (let y = lo; y <= hi; y++) {
let off = 0
if (y < hi) {
for (let x = xa; x < xb; x++) {
const i = idx(x, y)
if (Math.abs(px[i] - backdrop[0]) + Math.abs(px[i + 1] - backdrop[1]) + Math.abs(px[i + 2] - backdrop[2]) > lim.backdrop_distance) off++
}
}
if (y < hi && off === 0) {
if (start < 0) start = y
} else if (start >= 0) {
if (y - start >= need) {
const top = start + (y - start - img.height) / 2
if (!best || Math.abs(top - nominal) < Math.abs(best - nominal)) best = top
}
start = -1
}
}
return best ?? nominal
}
for (const [i, v] of t.views.entries()) {
const cx = ((figCols[i][0] + figCols[i][1]) / 2) * W
const img = await text(v.label, labelStyle)
const band = R(0, t.label_y[0], 1, t.label_y[1])
await place(v.id, 'view', v.label, labelStyle, cx, emptyTop(img, cx, band))
}
for (const [i, item] of e.items.entries()) {
const c = exCols[i % 2]
const r = e.rows[Math.floor(i / 2)]
const img = await text(item.label, labelStyle)
const band = R(0, r.label_y[0], 1, r.label_y[1])
const cx = ((c[0] + c[1]) / 2) * W
await place(item.id, 'expression', item.label, labelStyle, cx, emptyTop(img, cx, band))
}
const name = String(ch.name ?? '').trim()
const who = String(ch.who ?? '').trim()
const nameStyle = { size: L.header.name_size * H, bold: true, color: ink }
const whoStyle = { size: L.header.who_size * H, color: muted }
const nameImg = await text(name, nameStyle)
const whoImg = await text(who, whoStyle)
const headH = L.header.y[1] * H
const nameTop = (headH - nameImg.height) / 2
await place('name', 'header', name, nameStyle, L.header.name_x * W, nameTop, 'left')
const whoLeft = L.header.name_x * W + nameImg.width + 0.02 * W
if (whoLeft + whoImg.width > leftEnd * W + (e.cell_width * 2 + e.gap) * W) fail('The character name and the one-line "who" do not fit the header. Shorten "who".')
await place('who', 'header', who, whoStyle, whoLeft, nameTop + nameImg.height - whoImg.height - 0.003 * H, 'left')
for (const l of labels) {
if (l.x < 0 || l.y < 0 || l.x + l.width > W || l.y + l.height > H) fail(`Label "${l.text}" falls outside the board.`)
}
// A label wider than its column would run into the next label.
const cellW = t.cell_width * W
for (const l of labels.filter((x) => x.role === 'view')) if (l.width > cellW) fail(`The label "${l.text}" is wider than its column.`)
const m = L.label.margin_px
for (const l of labels) {
const grown = { x: l.x - m, y: l.y - m, width: l.width + 2 * m, height: l.height + 2 * m }
const g = { x: Math.max(0, grown.x), y: Math.max(0, grown.y), width: Math.min(W - Math.max(0, grown.x), grown.width), height: Math.min(H - Math.max(0, grown.y), grown.height) }
// Measured against the sheet's own backdrop, so a label placed on a dark shoe or a shadow fails even when the whole
// box is covered. Contrast is against what is actually behind the text.
l.art_under_percent = offPercent(g, backdrop)
l.contrast = Number(ratio(lum(median(g, 1)), lum(darkBackdrop ? [243, 241, 238] : [27, 27, 27])).toFixed(2))
}
// ---- cells and gaps ----
const cells = []
for (const [i, v] of t.views.entries()) cells.push({ id: v.id, role: 'view', rect: R(figCols[i][0], t.y[0], figCols[i][1], t.y[1]) })
for (const [i, item] of e.items.entries()) cells.push({ id: item.id, role: 'expression', rect: R(exCols[i % 2][0], e.rows[Math.floor(i / 2)].y[0], exCols[i % 2][1], e.rows[Math.floor(i / 2)].y[1]) })
for (const c of cells) c.fill_percent = offPercent(c.rect, backdrop)
// Gaps: the widest run of empty columns (no art in the figure band) between neighbouring figures, measured on the art
// itself. A model keeps its own spacing whatever the prompt says, so a fixed strip would measure the wrong place.
const bandTop = Math.round(Math.min(t.y[0], e.rows[0].y[0]) * H)
const bandBottom = Math.round(Math.max(t.y[1], e.rows[1].y[1]) * H)
const colOn = new Uint32Array(W)
for (let x = 0; x < W; x++) {
let n = 0
for (let y = bandTop; y < bandBottom; y++) {
const i = idx(x, y)
if (Math.abs(px[i] - backdrop[0]) + Math.abs(px[i + 1] - backdrop[1]) + Math.abs(px[i + 2] - backdrop[2]) > lim.backdrop_distance) n++
}
colOn[x] = n
}
function clearRun(x0, x1) {
let best = 0
let run = 0
for (let x = Math.max(0, Math.round(x0)); x < Math.min(W, Math.round(x1)); x++) {
if (colOn[x] <= 2) { run++; best = Math.max(best, run) } else run = 0
}
return best
}
const mid = (c) => ((c[0] + c[1]) / 2) * W
const gaps = []
for (let i = 0; i < 3; i++) gaps.push({ id: `gap-${i + 1}`, between: `${t.views[i].id} and ${t.views[i + 1].id}`, clear_px: clearRun(mid(figCols[i]), mid(figCols[i + 1])) })
gaps.push({ id: 'between-blocks', between: 'back and the portraits', clear_px: clearRun(mid(figCols[3]), mid(exCols[0])) })
// ---- write ----
const board = await sharp(artBuf).composite(layers).jpeg({ quality: 92 }).toBuffer()
writeFileSync(outAbs, board)
if (opts.guides) {
const rects = [
...cells.map((c) => ``),
...labels.map((l) => ``),
``,
]
const svg = Buffer.from(``)
await sharp(board).composite([{ input: svg, left: 0, top: 0 }]).jpeg({ quality: 88 }).toFile(outAbs.replace(/\.jpe?g$/i, '.guides.jpg'))
}
const sha = (buf) => createHash('sha256').update(buf).digest('hex')
const outDir = dirname(outAbs)
const manifest = {
schema: 'character-sheet-board/1',
file: relative(outDir, outAbs),
sha256: sha(board),
width: W,
height: H,
layout_checked: L.checked,
art: relative(outDir, artAbs),
art_sha256: sha(readFileSync(artAbs)),
art_size: { width: artInfo.width, height: artInfo.height },
art_resized: resized,
character: name,
backdrop,
font: fontFile ? relative(outDir, fontFile) : family,
labels,
cells: cells.map((c) => ({ id: c.id, role: c.role, fill_percent: c.fill_percent })),
gaps,
created: new Date().toISOString(),
}
writeFileSync(`${outAbs}.json`, `${JSON.stringify(manifest, null, 2)}\n`)
if (!opts['no-update']) {
ch.reference = relative(base, artAbs)
ch.sheet = relative(base, outAbs)
writeFileSync(opts.character, `${JSON.stringify(ch, null, 2)}\n`)
}
const worst = Math.max(...labels.map((l) => l.art_under_percent))
console.log(`${outAbs} ${W}x${H}, ${labels.length} labels drawn, worst art under a label ${worst}%, backdrop rgb(${backdrop.join(',')}).`)
console.log(`Cells filled: ${cells.map((c) => `${c.id} ${c.fill_percent}%`).join(', ')}.`)
console.log(`Clear gaps between figures: ${gaps.map((g) => `${g.between} ${g.clear_px} px`).join(', ')}.`)
console.log(`Font: ${fontFile ?? family} (system fonts resolve through fontconfig; pass --font-file and --font for exact type).`)
if (!opts['no-update']) console.log(`Set character.reference to the text-free art and character.sheet to this board in ${opts.character}.`)
console.log(`Next: node scripts/check-sheet.mjs --character ${opts.character} --board ${opts.out}, then open the board and go through references/output-spec.md.`)