#!/usr/bin/env node /** * Render film-look sample frames and build the film gallery page. * * Every frame is produced by the app's own WebGL renderer with the preset's real * edits, so the gallery shows what Luminary actually does rather than a mock-up. * Black and white looks are documented with the contrast filter they carry, and * one stock is rendered through every colour filter the editor offers. * * node scripts/film-samples.mjs --photo sample.jpg * node scripts/film-samples.mjs --photo sample.jpg --out /tmp/film --per-category 2 * * Output stays outside the checkout (default ~/.cache/luminary-film-gallery): * * /original.jpg the untouched frame * /.jpg one frame per sampled stock * /--.jpg the black and white filter demo * /film.html the gallery page * /film-looks.json the catalogue data * * Copy the frames to the site's assets/film/ and film.html to the site root. * Needs Chrome/Chromium with WebGL2 (SwiftShader is used when there is no GPU). */ import { spawn } from 'node:child_process'; import { existsSync } from 'node:fs'; import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import sharp from 'sharp'; import { createServer } from 'vite'; import { FILM_PRESETS } from '../src/lib/presets.ts'; // Filled from Vite's ssrLoadModule below: edits.ts imports './curves' without an // extension, which Node's own resolver cannot follow from a plain import here. let BW_FILTERS = []; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const DIR = path.join(ROOT, '.film-samples'); const PAGE = path.join(DIR, 'index.html'); const PORT = 5201; const RENDER_WIDTH = 1000; const RENDER_HEIGHT = 667; const JPEG_QUALITY = 84; /** The stock used to show what each B&W contrast filter does. */ const BW_DEMO_STOCK = 'film-tri-x-400'; const FILTER_HINTS = { none: 'No filter: the stock as it renders by default', yellow: 'Mild: slightly darker sky, natural skin', orange: 'Stronger: deeper sky, warmer skin separation', red: 'Dramatic: near-black sky, bright skin and foliage highlights', green: 'Lifts foliage, darkens lips and skin blemishes', blue: 'Lightens haze and shadow detail, darkens skin', }; const CATEGORY_ORDER = [ 'Colour Negative', 'Colour Slide', 'Black & White', 'Cinema', 'Instant', 'Redscale', 'Experimental', ]; const CATEGORY_HINTS = { 'Colour Negative': 'C-41 print films: warm skin, open shadows and the colour people mean by "film".', 'Colour Slide': 'E-6 and K-14 reversal films: dense blacks, saturated colour and very little latitude.', 'Black & White': 'Panchromatic stocks and chromogenic B&W, each with its own grain, contrast and colour filter.', Cinema: 'Motion-picture negatives: flat midtones and soft shoulders, built to grade.', Instant: 'Integral and peel-apart instant film: lifted blacks, soft colour, gentle contrast.', Redscale: 'Film exposed through its base: amber highlights, red midtones, deep shadows.', Experimental: 'Cross-process, faded print, infrared and other deliberate departures from a normal negative.', }; /** Three representative stocks per category: the ones people ask for by name. */ const SAMPLE_PICKS = { 'Colour Negative': ['film-portra-400', 'film-gold-200', 'film-ektar-100'], 'Colour Slide': ['film-velvia-50', 'film-provia-100f', 'film-kodachrome-64'], 'Black & White': ['film-tri-x-400', 'film-tmax-100', 'film-hp5-plus-400'], Cinema: ['film-cinestill-800t', 'film-vision3-250d', 'film-cinestill-50d'], Instant: ['film-polaroid-600', 'film-instax-mini', 'film-fp-100c'], Redscale: ['film-redscale-xr', 'film-redscale-deep', 'film-redscale-gold-200'], Experimental: ['film-lomochrome-purple', 'film-xpro-cross-process', 'film-aerochrome'], }; const HELP = `Luminary film gallery generator Usage: node scripts/film-samples.mjs --photo [options] --photo source frame (JPEG/PNG) to render every look onto --out output directory (default: /luminary-film-gallery) --per-category sampled stocks per category (default: 3, max: all picks) --quality <1-100> JPEG quality for the frames (default: ${JPEG_QUALITY}) --help print this text Frames come from the app's own renderer in headless Chrome, so WebGL2 must work there (SwiftShader is fine). ${BW_DEMO_STOCK} is also rendered through every B&W colour filter. The repository is not modified; the temporary render page is deleted at the end. `; const CHROME_CANDIDATES = [ process.env.CHROME_PATH, 'google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', ].filter(Boolean); function fail(message) { process.stderr.write(`film-samples: FAILED: ${message}\n`); process.exit(1); } function log(step, message) { process.stdout.write(`film-samples: ${step.padEnd(9)} ${message}\n`); } function parseArgs(argv) { const options = { photo: null, out: path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-film-gallery'), perCategory: 3, quality: JPEG_QUALITY, help: false, }; const value = (index, flag) => { const next = argv[index + 1]; if (!next || next.startsWith('--')) fail(`${flag} needs a value`); return next; }; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === '--photo') { options.photo = path.resolve(value(i, arg)); i += 1; } else if (arg === '--out') { options.out = path.resolve(value(i, arg)); i += 1; } else if (arg === '--per-category') { options.perCategory = Number(value(i, arg)); i += 1; } else if (arg === '--quality') { options.quality = Number(value(i, arg)); i += 1; } else if (arg === '--help' || arg === '-h') { options.help = true; } else { fail(`unknown option ${arg} (see --help)`); } } if (!Number.isInteger(options.perCategory) || options.perCategory < 1) { fail('--per-category must be a positive integer'); } if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) { fail('--quality must be 1-100'); } if (!options.help && !options.photo) fail('--photo is required (see --help)'); if (options.photo && !existsSync(options.photo)) fail(`photo not found: ${options.photo}`); return options; } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function spawnSyncOk(bin) { const probe = spawn(bin, ['--version'], { stdio: 'ignore' }); return new Promise((resolve) => { probe.on('error', () => resolve(false)); probe.on('exit', (code) => resolve(code === 0)); }); } async function findChrome() { for (const candidate of CHROME_CANDIDATES) { if (candidate.includes(path.sep)) { if (existsSync(candidate)) return candidate; continue; } if (await spawnSyncOk(candidate)) return candidate; } return null; } const PAGE_HTML = `
boot
`; async function drive(chromeBin, url, jobs, outDir, quality) { const port = 9333; const child = spawn( chromeBin, [ '--headless=new', '--no-sandbox', '--disable-gpu-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', `--remote-debugging-port=${port}`, `--user-data-dir=${path.join(DIR, 'profile')}`, 'about:blank', ], { stdio: 'ignore' }, ); try { let target = null; for (let i = 0; i < 120 && !target; i++) { try { const res = await fetch(`http://127.0.0.1:${port}/json/list`); target = (await res.json()).find((t) => t.type === 'page') ?? null; } catch { /* devtools not up yet */ } if (!target) await sleep(250); } if (!target) throw new Error('Chrome DevTools endpoint never came up'); const ws = new WebSocket(target.webSocketDebuggerUrl); await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = () => reject(new Error('DevTools websocket failed')); }); let nextId = 1; const pending = new Map(); ws.onmessage = (event) => { const message = JSON.parse(event.data); if (message.id && pending.has(message.id)) { pending.get(message.id)(message); pending.delete(message.id); } }; const send = (method, params = {}) => { const id = nextId++; return new Promise((resolve) => { pending.set(id, resolve); ws.send(JSON.stringify({ id, method, params })); }); }; const evaluate = async (expression, awaitPromise = false) => { const response = await send('Runtime.evaluate', { expression, awaitPromise, returnByValue: true, }); if (response.result?.exceptionDetails) { throw new Error( response.result.exceptionDetails.exception?.description ?? response.result.exceptionDetails.text, ); } return response.result?.result?.value; }; await send('Page.enable'); await send('Runtime.enable'); await send('Page.navigate', { url }); const deadline = Date.now() + 120000; let status = ''; while (Date.now() < deadline) { status = (await evaluate("document.getElementById('out')?.textContent ?? ''")) ?? ''; if (status.startsWith('READY') || status.startsWith('ERROR')) break; await sleep(400); } if (status.startsWith('ERROR')) throw new Error(status.slice(6)); if (!status.startsWith('READY')) throw new Error('the render page never became ready'); const written = []; for (const job of jobs) { const dataUrl = await evaluate( `window.renderLook(${JSON.stringify(job.id)}, ${JSON.stringify(job.filter ?? null)})`, true, ); if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/jpeg;base64,')) { throw new Error(`renderer returned no JPEG for ${job.file}`); } const buffer = Buffer.from(dataUrl.slice('data:image/jpeg;base64,'.length), 'base64'); const file = path.join(outDir, job.file); // Re-encode so the frames carry consistent metadata and no EXIF bloat. await sharp(buffer).jpeg({ quality, mozjpeg: true }).toFile(file); log('render', `${job.file} (${(buffer.length / 1024).toFixed(0)} KB)`); written.push(job.file); } ws.close(); return written; } finally { child.kill('SIGKILL'); await sleep(400); } } /* ------------------------------------------------------------------ page ---- */ function escapeHtml(value) { return String(value) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function slug(category) { return category .toLowerCase() .replace(/&/g, 'and') .replace(/[^a-z0-9]+/g, '-') .replace(/(^-|-$)/g, ''); } function filterLabel(id) { return BW_FILTERS.find((filter) => filter.id === id)?.label ?? null; } function buildFilterDemo(catalogue) { const group = catalogue.find((entry) => entry.category === 'Black & White'); if (!group) return ''; const withFilter = group.looks.filter((look) => look.filter && look.filter !== 'none').length; const figures = BW_FILTERS.map( (filter) => `
${escapeHtml(
                filter.label,
              )} filter on ${escapeHtml(group.looks.find((look) => look.id === BW_DEMO_STOCK)?.name ?? 'a black and white film')}
${escapeHtml(filter.label)}

${escapeHtml(FILTER_HINTS[filter.id] ?? '')}

`, ).join('\n '); return `

Colour filters, the way they were used on the lens

Before digital, contrast in black and white came from screwing a coloured filter onto the lens: it held back its own colour, so a red filter turned a blue sky nearly black while leaving skin bright, and a green one lifted foliage. Each monochrome look here records the filter it was built with, and ${withFilter} of the ${group.looks.length} name one. The same Tri-X 400 frame through every filter:

${figures}

Filter strength is adjustable in the editor, so a look can be dialled back from the full strength shown here.

`; } function buildPage(catalogue, framesByCategory) { const total = catalogue.reduce((sum, group) => sum + group.looks.length, 0); const chips = catalogue .map( (group) => `${escapeHtml(group.category)} ${group.looks.length}`, ) .join('\n '); const sections = catalogue .map((group) => { const frames = framesByCategory[group.category] ?? []; const figures = frames .map( (frame) => `
${escapeHtml(frame.name)} applied to the sample photograph
${escapeHtml(frame.name)}${frame.iso ? ` · ISO ${frame.iso}` : ''}${ frame.process ? ` · ${escapeHtml(frame.process)}` : '' }
`, ) .join('\n '); const looks = group.looks .map( (look) => `
  • ${escapeHtml(look.name)} ${[ look.iso ? `ISO ${look.iso}` : '', look.process ?? '', look.filter && look.filter !== 'none' ? `${filterLabel(look.filter)} filter` : '', ] .filter(Boolean) .join(' · ')} ${look.note ? `${escapeHtml(look.note)}` : ''}
  • `, ) .join('\n '); return `

    ${escapeHtml(group.category)} · ${group.looks.length} looks

    ${escapeHtml(group.category)}

    ${escapeHtml(CATEGORY_HINTS[group.category] ?? '')}

    ${group.category === 'Black & White' ? buildFilterDemo(catalogue) : ''}
    ${figures}
      ${looks}
    `; }) .join('\n\n'); return ` Luminary film looks: ${total} documented film emulations

    Film pack · ${total} looks

    ${total} film looks.
    One frame, one engine.

    Every frame below was rendered by Luminary's own editor with the look applied to the same photograph — no screenshots from another app, no pasted LUTs. Each entry lists the stock it emulates, its ISO and process, and a note on what it does.

    ${chips}

    Sample frame: a digital photograph, unedited, rendered at ${RENDER_WIDTH}×${RENDER_HEIGHT}. Grain and colour come from the look itself.

    The sample photograph with no film look applied
    The starting frame: no look, no crop, no colour work.

    The black and white section also shows the colour-filter technique: the same stock rendered through yellow, orange, red, green and blue filters, the way contrast was shaped on film before digital.

    ${sections}
    `; } /* ------------------------------------------------------------------ main ---- */ function filterDemoJobs() { return BW_FILTERS.map((filter) => ({ id: BW_DEMO_STOCK, filter: filter.id, file: `${BW_DEMO_STOCK}--${filter.id}.jpg`, })); } async function main() { const options = parseArgs(process.argv.slice(2)); if (options.help) { process.stdout.write(HELP); return 0; } const chromeBin = await findChrome(); if (!chromeBin) { fail('no Chrome/Chromium found; set CHROME_PATH or install one (WebGL2 is required)'); } const categories = CATEGORY_ORDER.filter((category) => FILM_PRESETS.some((preset) => preset.category === category), ); const catalogue = categories.map((category, index) => ({ category, index, looks: FILM_PRESETS.filter((preset) => preset.category === category).map((preset) => ({ id: preset.id, name: preset.name, iso: preset.film?.speed ?? null, process: preset.film?.process ?? null, filter: preset.edits.bw ? preset.edits.bwFilter ?? 'none' : null, note: preset.description ?? null, })), })); const framesByCategory = {}; const jobs = [{ id: 'original', file: 'original.jpg' }]; for (const group of catalogue) { const picks = (SAMPLE_PICKS[group.category] ?? []) .filter((id) => group.looks.some((look) => look.id === id)) .slice(0, options.perCategory); framesByCategory[group.category] = picks.map((id) => { const look = group.looks.find((entry) => entry.id === id); return { id, name: look.name, iso: look.iso, process: look.process }; }); for (const id of picks) jobs.push({ id, file: `${id}.jpg` }); } await mkdir(options.out, { recursive: true }); await rm(DIR, { recursive: true, force: true }); await mkdir(DIR, { recursive: true }); // A 3:2 frame keeps every look comparable; the page states the source size. await sharp(options.photo) .rotate() .resize(RENDER_WIDTH, RENDER_HEIGHT, { fit: 'cover', position: 'centre' }) .jpeg({ quality: 95, chromaSubsampling: '4:4:4' }) .toFile(path.join(DIR, 'photo.jpg')); const server = await createServer({ root: ROOT, logLevel: 'error', server: { host: '127.0.0.1', port: PORT, strictPort: false }, }); await server.listen(); const base = (server.resolvedUrls?.local?.[0] ?? `http://127.0.0.1:${PORT}/`).replace(/\/$/, ''); // The editor's own filter list, so the page cannot drift from the app. BW_FILTERS = (await server.ssrLoadModule('/src/lib/edits.ts')).BW_FILTERS; jobs.push(...filterDemoJobs()); await writeFile(PAGE, PAGE_HTML); log('photo', `${path.relative(process.cwd(), options.photo)} → ${RENDER_WIDTH}×${RENDER_HEIGHT}`); log('render', `${jobs.length} frames through the editor's renderer`); let written; try { written = await drive(chromeBin, `${base}/.film-samples/`, jobs, options.out, options.quality); } finally { await server.close(); await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {}); } if (written.length !== jobs.length) fail(`only ${written.length} of ${jobs.length} frames rendered`); await writeFile( path.join(options.out, 'film-looks.json'), `${JSON.stringify({ total: FILM_PRESETS.length, categories: catalogue }, null, 2)}\n`, ); await writeFile(path.join(options.out, 'film.html'), buildPage(catalogue, framesByCategory)); const bytes = ( await Promise.all(written.map((file) => readFile(path.join(options.out, file)))) ).reduce((sum, buffer) => sum + buffer.length, 0); process.stdout.write( [ '', 'film gallery PASSED', ` frames ${written.length} JPEGs, ${(bytes / 1024 / 1024).toFixed(1)} MB`, ` looks ${FILM_PRESETS.length} across ${catalogue.length} categories`, ` filters ${BW_FILTERS.length} on ${BW_DEMO_STOCK}`, ` page ${path.join(options.out, 'film.html')}`, ` data ${path.join(options.out, 'film-looks.json')}`, '', 'Copy the frames to assets/film/ and film.html to the site root.', '', ].join('\n'), ); return 0; } main().then( (code) => { process.exitCode = code; }, (error) => { fail(error instanceof Error ? error.message : String(error)); }, );