Skip to content
1        10        20        30        40        50        60        70        80        90        100       1101#!/usr/bin/env bun2// Screenshot and smoke-test harness for Torment.3//4// Boots the dev server (unless one is already running), drives the game through5// window.torment, writes a PNG, and reports console errors, page errors and6// failed requests. This is the fast loop for checking a visual change:7//8//   bun scripts/shot.js                      # the title screen -> shots/menu.png9//   bun scripts/shot.js village              # the village       -> shots/village.png10//   bun scripts/shot.js shop                 # the market panel  -> shots/shop.png11//   bun scripts/shot.js battle               # the gate battle   -> shots/battle.png12//   bun scripts/shot.js models               # every GLB -> shots/models.png13//   bun scripts/shot.js battle --headed --scale 214//15// Watch mode: `bun --watch scripts/shot.js village`.1617import { spawn } from 'node:child_process';18import { mkdir } from 'node:fs/promises';19import { dirname, join, resolve } from 'node:path';20import { chromium } from 'playwright';2122const root = resolve(import.meta.dir, '..');23const options = parseArgs(process.argv.slice(2));24const baseUrl = `http://${options.host}:${options.port}`;25const outputPaths = [];2627const scenarioPaths = {28  menu: { path: '/', waitFor: 'game' },29  models: { path: '/tools/model-gallery.html', waitFor: 'gallery' },30};3132const scenario = options.scenario.toLowerCase();33const scenarioSlug = scenario.replace(/[^a-z0-9]+/g, '-');34const basePath = scenarioPaths[scenario]?.path ?? '/';35const waitTarget = scenarioPaths[scenario]?.waitFor ?? 'game';3637const server = await ensureServer();38const browser = await chromium.launch({39  headless: !options.headed,40  args: [41    // Software WebGL: produces the same image on a headless CI box as on a42    // desktop, and still exercises the real Three.js renderer.43    '--use-angle=swiftshader',44    '--enable-unsafe-swiftshader',45    '--ignore-gpu-blocklist',46    '--disable-dev-shm-usage',47    '--hide-scrollbars',48  ],49});5051const diagnostics = { console: [], errors: [], failedRequests: [] };52let exitCode = 0;5354try {55  const context = await browser.newContext({56    viewport: { width: options.width, height: options.height },57    deviceScaleFactor: options.scale,58  });59  const page = await context.newPage();6061  page.on('console', (message) => {62    const type = message.type();63    if (type === 'error' || type === 'warning') {64      diagnostics.console.push(`[${type}] ${message.text()}`);65    }66  });67  page.on('pageerror', (error) => diagnostics.errors.push(error.message));68  page.on('requestfailed', (request) => {69    const reason = request.failure()?.errorText ?? 'unknown';70    // Chromium cancels a pending favicon request when the page closes.71    if (!reason.includes('ERR_ABORTED')) {72      diagnostics.failedRequests.push(`${request.url()} — ${reason}`);73    }74  });7576  const url = new URL(options.url ?? basePath, baseUrl);77  if (waitTarget === 'game' && !url.searchParams.has('seed')) {78    url.searchParams.set('seed', String(options.seed));79  }8081  await page.goto(url.href, { waitUntil: 'domcontentloaded' });8283  if (waitTarget === 'gallery') {84    await page.waitForFunction(() => window.__gallery?.ready === true, null, {85      timeout: options.timeout,86    });87  } else {88    await page.waitForFunction(() => window.torment?.ready === true, null, {89      timeout: options.timeout,90    });91    await page.evaluate(() => document.fonts.ready);92    await runScenario(page);93  }9495  if (options.eval) await page.evaluate(options.eval);9697  await page.waitForTimeout(options.wait);9899  const paths = options.out100    ? options.frames > 1101      ? withFrameSuffix(options.out, options.frames)102      : [options.out]103    : framesOutputPaths(scenarioSlug, options.frames);104  await mkdir(dirname(resolve(root, paths[0])), { recursive: true });105106  for (const [index, path] of paths.entries()) {107    if (index > 0) await page.waitForTimeout(options.every);108    await page.screenshot({109      path: resolve(root, path),110      fullPage: options.full,111    });112    outputPaths.push(resolve(root, path));113  }114115  const summary = await page.evaluate(readSummary);116  report({ summary, diagnostics, options });117118  if (diagnostics.errors.length > 0 || diagnostics.failedRequests.length > 0) exitCode = 1;119  if (options.strict && diagnostics.console.some((line) => line.startsWith('[error]'))) {120    exitCode = 1;121  }122} catch (error) {123  diagnostics.errors.push(String(error?.stack ?? error));124  exitCode = 1;125  try {126    const page = browser.contexts()[0]?.pages()[0];127    if (page) {128      const fallback = resolve(root, 'shots', `${scenarioSlug}-failed.png`);129      await mkdir(dirname(fallback), { recursive: true });130      await page.screenshot({ path: fallback });131      outputPaths.push(fallback);132    }133  } catch {134    // The page may already be gone; the original error is the useful one.135  }136  report({ summary: null, diagnostics, options });137} finally {138  await browser.close();139  if (server.child) server.child.kill();140}141142process.exit(exitCode);143144// ------------------------------------------------------------------ helpers145146async function runScenario(page) {147  if (scenario === 'menu' || scenario === 'models') return;148149  // The village panels, opened over a full campaign so the market and hall150  // have something to show.151  if (['village', 'shop', 'hall', 'save', 'load'].includes(scenario)) {152    // The market shows what is still for sale, so only the shop leaves cards unbought.153    await page.evaluate(`(${setUpCampaign.toString()})(${scenario !== 'shop'})`);154    if (scenario !== 'village') {155      await page.evaluate((kind) => window.torment.open(kind), scenario);156    }157    return;158  }159160  if (scenario === 'battle') {161    await page.evaluate(`(${setUpCampaign.toString()})(true); window.torment.start(0);`);162    await waitForPlayerTurn(page);163    return;164  }165166  if (scenario === 'result') {167    await page.evaluate(`(${setUpCampaign.toString()})(true); window.torment.start(0);`);168    await waitForPlayerTurn(page);169    await page.evaluate(() => {170      const session = window.torment.session;171      for (const unit of session.battle.units) {172        if (unit.team === 'torment') unit.health = 0;173      }174      session.battle.outcome = 'victory';175      session.settle();176      window.torment.refresh();177    });178    return;179  }180181  throw new Error(182    `Unknown scenario "${options.scenario}". Try menu, village, shop, hall, save, battle, result, or models.`,183  );184}185186/**187 * A new game with the whole party recruited and every card bought. Gold and188 * honor are set directly so the panels show a realistic campaign.189 */190function setUpCampaign(buyAll) {191  const torment = window.torment;192  torment.transition({ type: 'newGame', starter: 'aislinn' });193  const profile = torment.session.profile;194  profile.honor = 1000;195  profile.gold = 1000;196  torment.transition({ type: 'recruit', heroine: 'finella' });197  torment.transition({ type: 'recruit', heroine: 'atlanta' });198  if (buyAll) {199    for (const card of torment.cards) {200      if (!profile.cards[card.heroine].includes(card.id)) {201        torment.transition({ type: 'buy', card: card.id });202      }203    }204  }205  profile.gold = 300;206}207208async function waitForPlayerTurn(page) {209  await page.waitForFunction(210    () => {211      const session = window.torment?.session;212      if (!session) return false;213      return session.screen !== 'battle' || !session.needsEnemyTurn();214    },215    null,216    { timeout: options.timeout },217  );218  // Let entrance animations and the enemy turn settle before capturing.219  await page.waitForTimeout(500);220}221222function readSummary() {223  const session = window.torment?.session;224  if (session) {225    const snapshot = session.snapshot();226    const battle = snapshot.battle;227    const current = battle?.units.find((unit) => unit.id === battle.current);228    return {229      kind: 'game',230      screen: snapshot.screen,231      encounter: battle?.name ?? null,232      round: battle?.round ?? null,233      turn: current ? `${current.name}${battle.isPlayerTurn ? ' (player)' : ''}` : null,234      hand: battle?.hand.length ?? null,235      health: battle236        ? battle.units237            .filter((unit) => unit.team === 'allies')238            .map((unit) => `${unit.name} ${unit.health}/${unit.maxHealth}`)239            .join(', ')240        : null,241      outcome: snapshot.outcome,242    };243  }244  if (window.__gallery) {245    return {246      kind: 'gallery',247      models: window.__gallery.total,248      errors: window.__gallery.errors.length,249    };250  }251  return null;252}253254function report({ summary, diagnostics, options }) {255  if (!options.quiet) {256    const problems =257      diagnostics.errors.length +258      diagnostics.failedRequests.length +259      diagnostics.console.filter((line) => line.startsWith('[error]')).length;260    console.log(`\nshot: ${outputPaths.map((path) => path.replace(root + '/', '')).join(', ')}`);261    if (summary) {262      const parts = [summary.kind];263      if (summary.screen) parts.push(summary.screen);264      if (summary.encounter) parts.push(summary.encounter);265      if (summary.round) parts.push(`round ${summary.round}`);266      if (summary.turn) parts.push(summary.turn);267      if (summary.hand !== null && summary.hand !== undefined) parts.push(`${summary.hand} cards`);268      if (summary.health) parts.push(summary.health);269      if (summary.outcome) parts.push(summary.outcome);270      if (summary.kind === 'gallery') parts.push(`${summary.models} models`);271      console.log(`scene: ${parts.join(' · ')}`);272    }273    console.log(problems ? `diagnostics: ${problems} problem(s)` : 'diagnostics: clean');274    for (const line of diagnostics.console) console.log(`  ${line}`);275    for (const line of diagnostics.errors) console.log(`  [pageerror] ${line}`);276    for (const line of diagnostics.failedRequests) console.log(`  [requestfailed] ${line}`);277  }278}279280function framesOutputPaths(slug, frames) {281  if (frames <= 1) return [join('shots', `${slug}.png`)];282  return withFrameSuffix(join('shots', `${slug}.png`), frames);283}284285function withFrameSuffix(path, frames) {286  return Array.from({ length: frames }, (_, index) =>287    path.replace(/(\.png)?$/i, `-${String(index + 1).padStart(2, '0')}$1`),288  );289}290291async function ensureServer() {292  if (await serverResponds(baseUrl)) return { child: null };293  if (!options.server) {294    throw new Error(`No server at ${baseUrl}. Start \`mise run dev\` or drop --no-server.`);295  }296297  const child = spawn(process.execPath, ['scripts/serve.js'], {298    cwd: root,299    env: { ...process.env, HOST: options.host, PORT: String(options.port) },300    stdio: ['ignore', 'pipe', 'pipe'],301  });302  let logs = '';303  child.stdout.on('data', (chunk) => (logs += chunk));304  child.stderr.on('data', (chunk) => (logs += chunk));305  child.on('exit', (code) => {306    if (code !== 0) logs += `\nserver exited with code ${code}`;307  });308309  const deadline = Date.now() + 10_000;310  while (Date.now() < deadline) {311    if (await serverResponds(baseUrl)) return { child };312    if (child.exitCode !== null) break;313    await Bun.sleep(120);314  }315316  child.kill();317  throw new Error(`Server did not start at ${baseUrl}.\n${logs.trim()}`);318}319320async function serverResponds(url) {321  try {322    const response = await fetch(`${url}/index.html`, {323      signal: AbortSignal.timeout(1000),324    });325    return response.ok;326  } catch {327    return false;328  }329}330331function parseArgs(argv) {332  const options = {333    scenario: 'menu',334    out: null,335    url: null,336    eval: null,337    width: 1440,338    height: 900,339    scale: 1,340    wait: 900,341    every: 600,342    frames: 1,343    timeout: 30_000,344    seed: 1234,345    host: process.env.HOST ?? '127.0.0.1',346    port: Number(process.env.PORT ?? 9999),347    headed: false,348    server: true,349    full: false,350    strict: false,351    quiet: false,352  };353354  const aliases = {355    s: 'scenario',356    o: 'out',357    w: 'width',358    h: 'height',359    n: 'frames',360    e: 'eval',361    u: 'url',362  };363  const booleans = {364    headed: 'headed',365    full: 'full',366    strict: 'strict',367    quiet: 'quiet',368  };369370  const args = [...argv];371  while (args.length > 0) {372    let arg = args.shift();373    if (!arg.startsWith('-')) {374      options.scenario = arg;375      continue;376    }377    arg = arg.replace(/^--?/, '');378    let value = null;379    const equals = arg.indexOf('=');380    if (equals !== -1) {381      value = arg.slice(equals + 1);382      arg = arg.slice(0, equals);383    }384    if (arg === 'help') {385      printHelp();386      process.exit(0);387    }388    if (arg === 'no-server') {389      options.server = false;390      continue;391    }392    if (arg in booleans) {393      options[booleans[arg]] = true;394      continue;395    }396    const key = aliases[arg] ?? arg;397    if (!(key in options)) {398      throw new Error(`Unknown option --${arg}. Try --help.`);399    }400    if (value === null) value = args.shift();401    if (value === undefined) throw new Error(`Missing value for --${arg}.`);402    if (['width', 'height', 'scale', 'wait', 'every', 'frames', 'timeout', 'seed', 'port'].includes(key)) {403      options[key] = Number(value);404    } else {405      options[key] = value;406    }407  }408409  return options;410}411412function printHelp() {413  console.log(`Screenshot harness for Torment.414415Usage: bun scripts/shot.js [scenario] [options]416417Scenarios418  menu          title screen (default)419  village       the village over a full campaign420  shop          the market panel open in the village421  hall          the hall panel open in the village422  save          the save panel open in the village423  battle        start the gate battle and wait for the player's turn424  result        force a victory screen425  models        contact sheet of every GLB under assets/426427Options428  -o, --out <path>     output PNG (default: shots/<scenario>.png)429  -u, --url <path>     load an arbitrary page instead of a scenario430  -e, --eval <js>      run JS in the page before capturing431  -w, --width <px>     viewport width (default 1440)432  -h, --height <px>    viewport height (default 900)433      --scale <n>      device pixel ratio (default 1)434      --seed <n>       game seed appended to the URL (default 1234)435      --wait <ms>      settle time before capture (default 900)436      --frames <n>     capture n frames437      --every <ms>     delay between frames (default 600)438      --headed         use a real window (GPU rendering)439      --full           capture the full scrollable page440      --no-server      reuse an already running server441      --port <n>       dev server port (default 9999)442      --strict         fail on console errors as well as page errors443      --quiet          only print on failure444  -n                   alias for --frames445`);446}