The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Cinema Studio: director data from the research, compileDirector, route planning, grid and palette math
Claudee8c30ee3d6ae
diff --git a/src/components/cinema/color-math.ts b/src/components/cinema/color-math.tsnew file mode 100644index 00000000..06119e33--- /dev/null+++ b/src/components/cinema/color-math.ts@@ -0,0 +1,161 @@+/** Colour helpers for the palette editor (pure): conversions, harmonies and k-means extraction. */++export type RGB = [number, number, number];++export function hexToRgb(hex: string): RGB {+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());+ const n = m ? parseInt(m[1], 16) : 0;+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];+}++export function rgbToHex([r, g, b]: RGB): string {+ return `#${[r, g, b].map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")).join("")}`;+}++export function rgbToHsl([r, g, b]: RGB): [number, number, number] {+ const rr = r / 255;+ const gg = g / 255;+ const bb = b / 255;+ const max = Math.max(rr, gg, bb);+ const min = Math.min(rr, gg, bb);+ const l = (max + min) / 2;+ const d = max - min;+ if (!d) return [0, 0, l];+ const s = d / (1 - Math.abs(2 * l - 1));+ let h = max === rr ? ((gg - bb) / d) % 6 : max === gg ? (bb - rr) / d + 2 : (rr - gg) / d + 4;+ h = (h * 60 + 360) % 360;+ return [h, s, l];+}++export function hslToHex(h: number, s: number, l: number): string {+ const hh = ((h % 360) + 360) % 360;+ const c = (1 - Math.abs(2 * l - 1)) * s;+ const x = c * (1 - Math.abs(((hh / 60) % 2) - 1));+ const m = l - c / 2;+ const [r, g, b] = hh < 60 ? [c, x, 0] : hh < 120 ? [x, c, 0] : hh < 180 ? [0, c, x] : hh < 240 ? [0, x, c] : hh < 300 ? [x, 0, c] : [c, 0, x];+ return rgbToHex([(r + m) * 255, (g + m) * 255, (b + m) * 255]);+}++export const luminance = ([r, g, b]: RGB) => 0.2126 * r + 0.7152 * g + 0.0722 * b;++export type Harmony = "analogous" | "complementary" | "monochromatic" | "split-complementary" | "triad" | "square";++export const HARMONIES: { id: Harmony; name: string; offsets: number[] }[] = [+ { id: "analogous", name: "Analogous", offsets: [-56, -28, 0, 28, 56] },+ { id: "complementary", name: "Complementary", offsets: [0, 180] },+ { id: "monochromatic", name: "Monochromatic", offsets: [0] },+ { id: "split-complementary", name: "Split complementary", offsets: [0, 150, 210] },+ { id: "triad", name: "Triad", offsets: [0, 120, 240] },+ { id: "square", name: "Square", offsets: [0, 90, 180, 270] },+];++/**+ * A palette around a base colour: the harmony's hues, each in a dark → light ramp, sorted dark → light+ * like Cinema Studio's palettes, with the base colour itself last (the accent).+ */+export function harmonyPalette(baseHex: string, harmony: Harmony, count = 6): string[] {+ const [h, s, l] = rgbToHsl(hexToRgb(baseHex));+ const def = HARMONIES.find((x) => x.id === harmony) ?? HARMONIES[0];+ const n = Math.max(2, Math.min(12, count));+ const out: { hex: string; l: number }[] = [];+ for (let i = 0; i < n - 1; i++) {+ const hue = h + def.offsets[i % def.offsets.length];+ const t = n > 2 ? i / (n - 2) : 0.5;+ const light = 0.1 + t * 0.78;+ const sat = harmony === "monochromatic" ? Math.max(0.08, s * (0.45 + 0.55 * (1 - Math.abs(t - 0.5) * 2))) : Math.max(0.12, Math.min(0.85, s * (0.7 + 0.3 * Math.sin(t * Math.PI))));+ out.push({ hex: hslToHex(hue, sat, light), l: light });+ }+ out.sort((a, b) => a.l - b.l);+ return [...out.map((o) => o.hex), hslToHex(h, s, l)];+}++/** Deterministic PRNG (mulberry32) so the same image gives the same palette. */+export function rng(seed = 1): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const dist2 = (a: RGB, b: RGB) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;++/** RGBA pixels → at most `max` RGB samples (evenly strided, transparent pixels skipped). */+export function samplePixels(data: Uint8ClampedArray | number[], max = 6000): RGB[] {+ const total = data.length / 4;+ const step = Math.max(1, Math.floor(total / max));+ const out: RGB[] = [];+ for (let i = 0; i < total; i += step) {+ const o = i * 4;+ if (data[o + 3] < 128) continue;+ out.push([data[o], data[o + 1], data[o + 2]]);+ }+ return out;+}++/**+ * k-means++ colour clustering. Returns the centres, dark → light, with the share of pixels each+ * covers; clusters that end up empty are dropped.+ */+export function kmeans(pixels: RGB[], k: number, iterations = 14, seed = 7): { color: string; share: number; rgb: RGB }[] {+ if (!pixels.length) return [];+ const rand = rng(seed);+ const kk = Math.max(1, Math.min(k, pixels.length));+ const centres: RGB[] = [pixels[Math.floor(rand() * pixels.length)]];+ while (centres.length < kk) {+ const d = pixels.map((p) => Math.min(...centres.map((c) => dist2(p, c))));+ const sum = d.reduce((a, b) => a + b, 0);+ if (!sum) break;+ let r = rand() * sum;+ let idx = 0;+ while (idx < d.length - 1 && r > d[idx]) r -= d[idx++];+ centres.push([...pixels[idx]] as RGB);+ }+ const assign = new Array<number>(pixels.length).fill(0);+ for (let it = 0; it < iterations; it++) {+ let moved = false;+ for (let i = 0; i < pixels.length; i++) {+ let best = 0;+ let bd = Infinity;+ for (let c = 0; c < centres.length; c++) {+ const dd = dist2(pixels[i], centres[c]);+ if (dd < bd) {+ bd = dd;+ best = c;+ }+ }+ if (assign[i] !== best) {+ assign[i] = best;+ moved = true;+ }+ }+ const sums = centres.map(() => [0, 0, 0, 0]);+ pixels.forEach((p, i) => {+ const s = sums[assign[i]];+ s[0] += p[0];+ s[1] += p[1];+ s[2] += p[2];+ s[3]++;+ });+ sums.forEach((s, c) => {+ if (s[3]) centres[c] = [s[0] / s[3], s[1] / s[3], s[2] / s[3]];+ });+ if (!moved && it > 0) break;+ }+ const counts = centres.map((_, c) => assign.filter((a) => a === c).length);+ return centres+ .map((c, i) => ({ rgb: c.map(Math.round) as RGB, color: rgbToHex(c), share: counts[i] / pixels.length }))+ .filter((c) => c.share > 0)+ .sort((a, b) => luminance(a.rgb) - luminance(b.rgb));+}++/** A Cinema-Studio-style palette from an image: k clusters dark → light, the most saturated sizeable one repeated last as the accent. */+export function paletteFromPixels(pixels: RGB[], count = 12): string[] {+ const clusters = kmeans(pixels, Math.max(2, count - 1));+ if (!clusters.length) return [];+ const accent = [...clusters].filter((c) => c.share > 0.02).sort((a, b) => rgbToHsl(b.rgb)[1] - rgbToHsl(a.rgb)[1])[0] ?? clusters[clusters.length - 1];+ return [...clusters.map((c) => c.color), accent.color];+}diff --git a/src/components/cinema/grid-math.ts b/src/components/cinema/grid-math.tsnew file mode 100644index 00000000..31609ce7--- /dev/null+++ b/src/components/cinema/grid-math.ts@@ -0,0 +1,118 @@+/**+ * Cutting a grid contact sheet into its tiles (pure; the browser feeds it canvas pixels).+ *+ * Image models draw the gutters between panels where they like, a few pixels off the even split, so+ * the cut lines are searched near each expected position: a band of rows/columns that is flat (low+ * spread) and near white or black. If an axis has no clear gutters, it falls back to an equal split.+ */++export interface Rect {+ x: number;+ y: number;+ w: number;+ h: number;+ row: number;+ col: number;+}++export interface LineStats {+ /** Mean luminance (0–255) of each line. */+ mean: number[];+ /** Standard deviation of the luminance along each line. */+ std: number[];+}++/** Luminance statistics of every column (axis "x") or row (axis "y") of RGBA pixels. */+export function lineStats(data: Uint8ClampedArray | number[], width: number, height: number, axis: "x" | "y"): LineStats {+ const n = axis === "x" ? width : height;+ const m = axis === "x" ? height : width;+ const mean = new Array<number>(n).fill(0);+ const std = new Array<number>(n).fill(0);+ // Sample at most ~400 pixels per line: plenty to tell a gutter from a picture.+ const step = Math.max(1, Math.floor(m / 400));+ for (let i = 0; i < n; i++) {+ let s = 0;+ let s2 = 0;+ let c = 0;+ for (let j = 0; j < m; j += step) {+ const x = axis === "x" ? i : j;+ const y = axis === "x" ? j : i;+ const o = (y * width + x) * 4;+ const l = 0.2126 * data[o] + 0.7152 * data[o + 1] + 0.0722 * data[o + 2];+ s += l;+ s2 += l * l;+ c++;+ }+ mean[i] = s / c;+ std[i] = Math.sqrt(Math.max(0, s2 / c - (s / c) ** 2));+ }+ return { mean, std };+}++const isGutter = (st: LineStats, i: number) => st.std[i] < 14 && (st.mean[i] > 215 || st.mean[i] < 30);++/**+ * Where to cut one axis into `parts`: [start, end) spans of the panels, gutters excluded.+ * Returns null when the gutters can't be found (the caller then splits evenly).+ */+export function findCuts(st: LineStats, parts: number): [number, number][] | null {+ const len = st.mean.length;+ if (parts <= 1) return [[0, len]];+ // Outer margin: gutter lines running in from either edge.+ let lo = 0;+ while (lo < len * 0.1 && isGutter(st, lo)) lo++;+ let hi = len;+ while (hi > len * 0.9 && isGutter(st, hi - 1)) hi--;+ const span = hi - lo;+ const bands: [number, number][] = [];+ for (let k = 1; k < parts; k++) {+ const center = lo + Math.round((k * span) / parts);+ const window = Math.max(2, Math.round((span / parts) * 0.18));+ let best: [number, number] | null = null;+ let bestScore = Infinity;+ for (let i = Math.max(lo + 1, center - window); i <= Math.min(hi - 2, center + window); i++) {+ if (!isGutter(st, i) || (i > 0 && isGutter(st, i - 1) && i - 1 >= center - window)) continue;+ // The whole run of flat lines, even where it starts before the search window.+ let a = i;+ while (a > lo + 1 && isGutter(st, a - 1)) a--;+ let j = i;+ while (j < hi && isGutter(st, j)) j++;+ // A band near the expected spot wins; a wider band beats a stray flat line.+ const mid = (a + j) / 2;+ const score = Math.abs(mid - center) - (j - a) * 0.5;+ if (score < bestScore) {+ bestScore = score;+ best = [a, j];+ }+ }+ if (!best) return null;+ bands.push(best);+ }+ const spans: [number, number][] = [];+ let start = lo;+ for (const [a, b] of bands) {+ spans.push([start, a]);+ start = b;+ }+ spans.push([start, hi]);+ // Panels of a contact sheet are about the same size: reject wild cuts.+ const sizes = spans.map(([a, b]) => b - a);+ const avg = sizes.reduce((x, y) => x + y, 0) / sizes.length;+ if (sizes.some((s) => s < avg * 0.6 || s > avg * 1.4)) return null;+ return spans;+}++export function equalSpans(len: number, parts: number): [number, number][] {+ return Array.from({ length: parts }, (_, i) => [Math.round((i * len) / parts), Math.round(((i + 1) * len) / parts)] as [number, number]);+}++/** The tile rectangles of a rows × cols sheet, from detected gutters or an equal split. */+export function tileRects(width: number, height: number, rows: number, cols: number, stats?: { x?: LineStats; y?: LineStats }): { rects: Rect[]; detected: boolean } {+ const xs = (stats?.x && findCuts(stats.x, cols)) || null;+ const ys = (stats?.y && findCuts(stats.y, rows)) || null;+ const cx = xs ?? equalSpans(width, cols);+ const cy = ys ?? equalSpans(height, rows);+ const rects: Rect[] = [];+ cy.forEach(([y0, y1], row) => cx.forEach(([x0, x1], col) => rects.push({ x: x0, y: y0, w: x1 - x0, h: y1 - y0, row, col })));+ return { rects, detected: !!xs && !!ys };+}diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.tsnew file mode 100644index 00000000..74b9454d--- /dev/null+++ b/src/lib/catalog/cinema.ts@@ -0,0 +1,1390 @@+import { getModel, getPreset } from "./index";+import { composeShots, estimateCost, planGeneration } from "./plan";+import type { Engine, GenerationRequest, GenParams, LoraRef, ModelDef, Operation } from "./types";++/*+ * Cinema Studio 4.0: the director's data and the pure planning step shared by the browser+ * (live cost, previews) and the server (src/server/cinema-generate.ts).+ *+ * Everything below the "Research data" line is copied from docs/research/higgsfield-studios.json →+ * cinemaStudio (genres, eras, tempos, camera bodies, lenses, apertures, the 33 camera moves the API+ * accepts, the 50 public palettes with their 12 hex colours, the 7 lighting presets, the Emotion Wheel)+ * and higgsfield-image-studios.json → characterSheet.soulCast (the 17 Soul Cast fields).+ * tests/cinema.test.ts checks the copy against the JSON, so a research update shows up as a failing test.+ *+ * Routes (fuobeBuild in the research):+ * - Cloud video: Higgsfield `cinema-studio-4` reads genre / era / pacing / camera / lens / aperture /+ * light / color_palette / camera_movement natively; without a Higgsfield key (or when another model+ * is picked) Seedance 2.5, Kling 3.0 or Veo 3.1 get the same settings compiled into the prompt.+ * - Open video: Wan 2.2 14B Lightning with the compiled prompt; camera moves become a camera LoRA or a+ * Wan Fun Camera pose where motions.ts has one; a palette becomes a palette-transfer post-step.+ */++// ---------------------------------------------------------------------------+// Types++export interface DirectorOption {+ name: string;+ /** API slug; null = Auto (the field is left out and the model decides). */+ slug: string | null;+ description: string;+}++export interface CinemaPalette {+ name: string;+ slug: string;+ /** 12 colours, dark → light, the last one is the accent (= Higgsfield's background colour). */+ hex: string[];+}++export interface EmotionStep {+ name: string;+ /** Exact fragment Higgsfield adds after the character. */+ prompt: string;+ intensity: number;+}++export interface EmotionFamily {+ name: string;+ /** Chip colour per intensity (10 / 50 / 100). */+ colors: string[];+ steps: EmotionStep[];+}++export interface CameraMove {+ slug: string;+ name: string;+ /** What the move does (shown in the picker). */+ hint: string;+ /** Display name confirmed in Higgsfield's UI (else title-cased from the slug). */+ confirmed: boolean;+ /** Camera-language phrase used when the move is written into the prompt. */+ phrase: string;+ /** Fuobe camera-motion preset with the same move (its open route may carry a camera LoRA). */+ motionId?: string;+ /** Wan 2.2 Fun Camera pose for the same move (open engine, needs a start frame). */+ funCamera?: string;+}++export type LightDirection = string;++export interface LightSource {+ direction: LightDirection;+ /** #RRGGBB */+ color: string;+ /** 0–100 */+ brightness: number;+ /** 0–100: hard → soft. */+ diffuse: number;+}++export type PaletteChoice = { kind: "preset"; slug: string } | { kind: "custom"; name: string; hex: string[] };+export type LightingChoice = { kind: "preset"; slug: string } | { kind: "custom"; lights: LightSource[] };++/** One emotion per @character, keyed by the element's handle (lower case). */+export interface EmotionChoice {+ family: string;+ /** 0, 1 or 2 = intensity 10 / 50 / 100. */+ step: number;+}++/** The Director's Panel, persisted per project. Missing / null fields mean Auto. */+export interface DirectorSettings {+ genre?: string | null;+ era?: string | null;+ tempo?: string | null;+ camera?: string | null;+ lens?: string | null;+ focal?: string | null;+ aperture?: string | null;+ palette?: PaletteChoice | null;+ /** Open engine: recolour the result to the palette with a palette-transfer step (default on). */+ paletteLock?: boolean;+ lighting?: LightingChoice | null;+ emotions?: Record<string, EmotionChoice>;+}++export interface CinemaProject {+ id: string;+ name: string;+ description: string | null;+ cover: string | null;+ /** Estimate guard: generating is refused when the project's estimated spend would pass it. */+ costCapUsd: number | null;+ director: DirectorSettings;+ /** Palettes saved in the editor. */+ palettes: { name: string; hex: string[] }[];+ brief: { title: string; body: string };+ pinned: boolean;+ createdAt: number;+ updatedAt: number;+ /** Filled by the list endpoint. */+ stats?: { items: number; spentUsd: number; cover?: string | null };+}++export interface CinemaFolder {+ id: string;+ projectId: string;+ parentId: string | null;+ name: string;+ color: string | null;+ pinned: boolean;+ position: number;+ createdAt: number;+ updatedAt: number;+}++export interface CinemaTile {+ url: string;+ row: number;+ col: number;+}++/** A generation's membership in a project (and its folder = scene). */+export interface CinemaItem {+ generationId: string;+ folderId: string | null;+ createdAt: number;+ /** Grid contact sheets: the tiles cut from it in the browser, saved as uploads. */+ tiles?: CinemaTile[];+}++/** One shot the AI Director proposes; "Load into prompt bar" copies it into the composer. */+export interface DirectorShot {+ title: string;+ prompt: string;+ duration: number;+ moves: string[];+ settings: Partial<DirectorSettings>;+}++export interface DirectorMessage {+ id: string;+ role: "user" | "assistant";+ text: string;+ shots?: DirectorShot[];+ /** A proposed project brief (the user applies it). */+ brief?: string;+ /** "llm" when a model wrote it, "offline" for the heuristic fallback. */+ source?: "llm" | "offline";+ createdAt: number;+}++export type CinemaMode = "video" | "image";+export type CinemaAction = "generate" | "extend-forward" | "extend-backward" | "edit" | "grid" | "cast" | "location" | "location-view";+export type GridSize = "2x2" | "3x3" | "4x4";+export type GridType = "freeform" | "zooms" | "shots" | "next_shots" | "prev_shots";+export type CastValues = Record<string, string | number | string[] | undefined>;++export interface CinemaGenerateInput {+ engine: Engine;+ mode: CinemaMode;+ action: CinemaAction;+ /** Explicit pick from the model menu (else the studio's default for the engine). */+ modelId?: string;+ prompt: string;+ /** # camera moves, in order. */+ moves?: string[];+ settings: DirectorSettings;+ brief?: string;+ /** Reference images (the first one is the start frame). @elements add theirs on the server. */+ images?: string[];+ videos?: string[];+ audios?: string[];+ duration?: number;+ resolution?: string;+ aspectRatio?: string;+ batch?: number;+ audio?: boolean;+ multiShot?: { mode: "off" | "auto" | "manual"; shots?: { prompt: string; duration: number }[] };+ /** The selected take (extend, edit, another view of a location). */+ source?: { url: string; kind: "image" | "video"; firstFrame?: string };+ grid?: { size: GridSize; type: GridType };+ cast?: CastValues;+ /** Soul Location: which extra view to render. */+ view?: string;+}++export interface CinemaContext {+ /** A Higgsfield key is configured (cinema-studio-4 and Soul run for real). */+ higgsfield: boolean;+ /** Cloud models are allowed (engine mode isn't "open only"): extract-frame fallbacks need it. */+ cloudAllowed?: boolean;+ /** Models that exist in this build (open-engine adds the grid / Soul Cast / restyle workflows). */+ has?: (modelId: string) => boolean;+}++export interface CinemaStep {+ key: string;+ request: GenerationRequest;+ /** Keys of earlier steps this one waits for (chain slots in request.chain, in this order). */+ after?: string[];+ /** Run once per output job of that step (palette lock after a batch of 4). */+ perJobOf?: string;+ /** Server fills inputs.images[0] with a swatch PNG of these colours. */+ swatch?: string[];+}++export interface CinemaPlan {+ model: ModelDef;+ steps: CinemaStep[];+ /** Adjustments made to fit the model (shown under the prompt bar). */+ notes: string[];+ /** Why it can't run yet (shown on the Generate button). */+ blocker?: string;+ costUsd: number | null;+ /** Number of results the user will get. */+ outputs: number;+}++// ---------------------------------------------------------------------------+// Research data (docs/research/higgsfield-studios.json → cinemaStudio.directorsPanel)++export const GENRES: DirectorOption[] = [+ { name: "General", slug: null, description: "No genre-specific visual logic; the prompt drives the look" },+ { name: "Action", slug: "action", description: "Camera tied to the moving subject, tighter framing around motion" },+ { name: "Epic", slug: "epic", description: "Wide compositions, environment as part of the subject, light across the frame" },+ { name: "Drama", slug: "drama", description: "Camera closer and longer, held moments, light directed onto faces" },+ { name: "Comedy", slug: "comedy", description: "Open framing, comic timing at shot level, room to react" },+ { name: "Horror", slug: "horror", description: "Off-angle framing and withheld light" },+ { name: "Noir", slug: "noir", description: "Hard shadow and high contrast" },+];++export const ERAS: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses from scene context" },+ { name: "60s", slug: "1960s", description: "Grain, colour response and lens character of 1960s film stock" },+ { name: "80s", slug: "1980s", description: "Saturation and lens character of 1980s production" },+ { name: "90s", slug: "1990s", description: "Flatter colour, video-adjacent texture" },+ { name: "2000s", slug: "2000s", description: "Digital colour response of early-2000s production" },+ { name: "2020s", slug: "2020s", description: "Contemporary, unmodified digital look" },+];++export const TEMPOS: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses pacing from scene context and genre" },+ { name: "Chaotic", slug: "chaotic", description: "Faster-than-expected cuts from unresolved angles" },+ { name: "Dynamic", slug: "dynamic", description: "Forward momentum without losing the viewer (commercials, music videos)" },+ { name: "Calm", slug: "calm", description: "Long takes, cut only once a moment has played out" },+ { name: "Single Shot", slug: "single-shot", description: "No editing: one continuous take" },+];++export const CAMERA_BODIES: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses from scene context" },+ { name: "Modern", slug: "modern", description: "Clean, high-resolution contemporary digital" },+ { name: "35mm Film", slug: "35mm-film", description: "Grain, tonal response, analog warmth" },+ { name: "8mm Film", slug: "8mm-film", description: "Soft, low-resolution home-movie texture" },+ { name: "DV Camcorder", slug: "dv-camcorder", description: "Flat colour and tape compression artefacts" },+];++export const LENSES: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses from scene context" },+ { name: "Clean Sharp", slug: "clean-sharp", description: "Maximum resolution, minimum aberration" },+ { name: "Anamorphic", slug: "anamorphic", description: "Oval bokeh, horizontal flares, slight barrel distortion" },+ { name: "Vintage Anamorphic", slug: "vintage-anamorphic", description: "Lower contrast, more chromatic aberration" },+ { name: "Warm Vintage", slug: "warm-vintage", description: "Diffusion, warmth, blooming highlights, gentle skin" },+ { name: "Halation Vintage", slug: "halation-vintage", description: "Red-tinged halo around highlights" },+];++export const APERTURES: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses from scene context" },+ { name: "f/1.4 Wide Open", slug: "f14-wide-open", description: "Background almost fully out of focus" },+ { name: "f/4 Moderate", slug: "f4-moderate", description: "Subject sharp, gentle falloff" },+ { name: "f/11 Deep Focus", slug: "f11-deep-focus", description: "Whole scene sharp front to back" },+];++const RAW_MOVES: [slug: string, name: string, hint: string, confirmed: boolean][] = [+ ["snorricam", "Snorricam", "Body-mounted rig: the subject stays locked in frame while the world moves around them", false],+ ["robot-arm", "Robot Arm", "Fast, precise motion-control arm move (product reveals, whip-arounds)", true],+ ["tilt-up", "Tilt Up", "Camera pivots upward on a fixed point", false],+ ["rack-focus", "Rack Focus", "Focus pulls from one subject/plane to another", false],+ ["tilt-down", "Tilt Down", "Camera pivots downward on a fixed point", false],+ ["pov", "POV", "First-person point of view of a character", true],+ ["pan-left", "Pan Left", "Horizontal pivot to the left", true],+ ["crane-up", "Crane Up", "Camera rises on a crane/jib", false],+ ["pan-right", "Pan Right", "Horizontal pivot to the right", false],+ ["crane-down", "Crane Down", "Camera lowers on a crane/jib", false],+ ["side-tracking", "Side Tracking", "Camera travels sideways alongside a moving subject", false],+ ["pedestal-up", "Pedestal Up", "Whole camera rises vertically without tilting", false],+ ["pedestal-down", "Pedestal Down", "Whole camera lowers vertically without tilting", true],+ ["handheld", "Handheld", "Organic handheld shake and drift", true],+ ["tracking", "Tracking", "Camera follows the subject through space", true],+ ["drone-orbit", "Drone Orbit", "Aerial orbit around the subject", false],+ ["dolly-zoom", "Dolly Zoom", "Vertigo effect: dolly and zoom in opposite directions", false],+ ["aerial-pullback", "Aerial Pullback", "Aerial shot pulling back to reveal the scene", false],+ ["static-shot", "Static", "Locked-off camera, no movement", true],+ ["bullet-time", "Bullet Time", "Frozen/slowed action while the camera sweeps around", true],+ ["whip-pan", "Whip Pan", "Very fast pan with motion blur, often a transition", false],+ ["slow-zoom-in", "Slow Zoom In", "Slow optical push in", false],+ ["arc-left", "Arc Left", "Camera arcs around the subject to the left", false],+ ["slow-zoom-out", "Slow Zoom Out", "Slow optical pull out", false],+ ["arc-right", "Arc Right", "Camera arcs around the subject to the right", false],+ ["truck-right", "Truck Right", "Camera moves laterally right", false],+ ["dolly-in", "Dolly In", "Camera physically moves toward the subject", true],+ ["truck-left", "Truck Left", "Camera moves laterally left", false],+ ["dolly-out", "Dolly Out", "Camera physically moves away from the subject", true],+ ["slider-right", "Slider Right", "Short, smooth slider move to the right", false],+ ["crush-zoom", "Crush Zoom", "Snap/crash zoom into the subject (API spells it 'crush')", false],+ ["slider-left", "Slider Left", "Short, smooth slider move to the left", false],+ ["helicopter-shot", "Helicopter Shot", "Wide aerial helicopter pass", true],+];++export const PALETTES: CinemaPalette[] = [+ { name: "Static Noon", slug: "static-noon", hex: ["#0c0c0c", "#28292a", "#4e4f51", "#626263", "#a25955", "#7b7b7b", "#939548", "#a7a7a6", "#c1c2c2", "#b6c6b7", "#ededed", "#69483b"] },+ { name: "Twilight Fable", slug: "twilight-fable", hex: ["#040605", "#1e4f59", "#5d4623", "#7b5d35", "#36797f", "#948052", "#b2a24a", "#56afae", "#88b2c9", "#dac593", "#f3f4ea", "#764019"] },+ { name: "Back Row Kissing Seats", slug: "back-row-kissing-seats", hex: ["#070405", "#4e1311", "#1a4388", "#875046", "#b26a38", "#6079c3", "#2da744", "#b89892", "#846e69", "#9ccd8a", "#c4c7d2", "#881913"] },+ { name: "On the Other Side of the Porthole", slug: "on-the-other-side-of-the-porthole", hex: ["#090709", "#720b11", "#474548", "#3d537d", "#933542", "#776343", "#71726e", "#969c9e", "#9dbbd8", "#c6bfb5", "#a3cba9", "#b82d1c"] },+ { name: "The Emerald Ambush", slug: "the-emerald-ambush", hex: ["#101210", "#4b4d2d", "#3c4c7b", "#64574b", "#3d703b", "#6986a7", "#959b87", "#ca9e80", "#bebec1", "#98d0d5", "#f0f7f0", "#1d481b"] },+ { name: "Highway Standoff", slug: "highway-standoff", hex: ["#0d110c", "#36463f", "#69351a", "#635a39", "#215ca7", "#607765", "#867660", "#9b9c85", "#beb389", "#adc7ae", "#eee6c2", "#0f1c79"] },+ { name: "The Faded Fresco", slug: "the-faded-fresco", hex: ["#14120e", "#4b4536", "#6d443e", "#5b544d", "#646864", "#7a6b62", "#8c877d", "#a2957f", "#b4b8a1", "#cbd196", "#c9e1c7", "#b8b592"] },+ { name: "Oil & Ochre", slug: "oil-ochre", hex: ["#0d0d0a", "#342619", "#524628", "#654e38", "#6d6932", "#636962", "#93896f", "#aea483", "#d0a681", "#e0d0a7", "#e1dcc8", "#8d7941"] },+ { name: "The Mountain Convent", slug: "the-mountain-convent", hex: ["#0a0a07", "#342f1f", "#464d47", "#695037", "#405e2d", "#646257", "#7e8079", "#7ea1c7", "#b29e73", "#b1b7b9", "#c6d7de", "#942417"] },+ { name: "Ghost in the Code", slug: "ghost-in-the-code", hex: ["#040605", "#1b331d", "#664836", "#3c6052", "#696747", "#818380", "#928363", "#6a9387", "#b8ad9a", "#bfe1c8", "#e6ebe9", "#638a63"] },+ { name: "Pink Velvet", slug: "pink-velvet", hex: ["#0d0c0f", "#682f1d", "#205279", "#7c5144", "#3078a3", "#996d73", "#7f818d", "#d29d9f", "#dda780", "#d7c5c8", "#efdcd5", "#9f140b"] },+ { name: "Two Days to the Horizon", slug: "two-days-to-the-horizon", hex: ["#060805", "#254850", "#55482c", "#774c18", "#696c53", "#558085", "#828767", "#c0a875", "#a7baa6", "#ccc9a4", "#e2e5cb", "#988357"] },+ { name: "Industrial Fog", slug: "industrial-fog", hex: ["#121012", "#300d0b", "#4d4840", "#6e4f42", "#5d5857", "#6e6e70", "#7f8180", "#989a99", "#adb2b1", "#c4b09a", "#ccced0", "#561b11"] },+ { name: "Stairs Go Up", slug: "stairs-go-up", hex: ["#050b0e", "#3d301f", "#375133", "#50574d", "#705b44", "#557c76", "#9f8865", "#87a290", "#4cb9a3", "#bebe9b", "#b2d0b5", "#814f21"] },+ { name: "Field Post", slug: "field-post", hex: ["#040505", "#514e28", "#295860", "#3e5b46", "#716538", "#5f8681", "#65a1d2", "#a9a668", "#d9b388", "#e3e39f", "#f8faf4", "#0a5a0e"] },+ { name: "Home Is the Next Gas Station", slug: "home-is-the-next-gas-station", hex: ["#0d0907", "#14182f", "#434145", "#57514e", "#766360", "#596d8a", "#8c868a", "#7d92bd", "#a57852", "#878ba1", "#b2aeb2", "#20345c"] },+ { name: "Glossy Flesh", slug: "glossy-flesh", hex: ["#0c0b11", "#223750", "#5b4747", "#785753", "#797074", "#b37092", "#92919d", "#d28c60", "#89c2df", "#b1bcce", "#d2c5ce", "#8b2926"] },+ { name: "The Crimson Ballet", slug: "the-crimson-ballet", hex: ["#0b0509", "#291c7d", "#621418", "#805442", "#475be0", "#d3184e", "#807d8b", "#b59c93", "#c5bfd9", "#70ddf8", "#f2e322", "#d20c25"] },+ { name: "Neon Rain at Midnight", slug: "neon-rain-at-midnight", hex: ["#0c0c0e", "#334d4e", "#7b3612", "#655254", "#676650", "#497197", "#708986", "#b3978e", "#95b0c2", "#bebc9d", "#f3e04e", "#446bc7"] },+ { name: "The Morning After Rain", slug: "the-morning-after-rain", hex: ["#0b0b0b", "#3c3228", "#404845", "#5e6459", "#3e6f81", "#7c7670", "#458f83", "#8ba1af", "#a8bccc", "#6ec9ce", "#c1d4e0", "#255e54"] },+ { name: "The Iron Borough", slug: "the-iron-borough", hex: ["#0a0604", "#2b0f07", "#613926", "#893d10", "#555461", "#756664", "#87858b", "#ad887c", "#d3aa6b", "#acb6c2", "#f5f8f9", "#b02610"] },+ { name: "The Ground", slug: "the-ground", hex: ["#0a0708", "#4b3e35", "#3f4b72", "#675b52", "#757f5f", "#907a66", "#ad9e92", "#82a9de", "#d2b48b", "#c7bfbb", "#e2e7f5", "#688ad2"] },+ { name: "The Investigation", slug: "the-investigation", hex: ["#0b0c0f", "#1a303d", "#515346", "#3a5b58", "#845931", "#6a7d78", "#e06b84", "#6c9ca0", "#8cb8b1", "#b3d1bc", "#d5e6c2", "#2a7c8e"] },+ { name: "Turquoise Mirage", slug: "turquoise-mirage", hex: ["#161614", "#054503", "#4c4a43", "#66635a", "#9a6941", "#6a8474", "#4aa290", "#9c9e72", "#87bc90", "#59cec2", "#cad7a2", "#0d8b06"] },+ { name: "A Dream in Color", slug: "a-dream-in-color", hex: ["#0c0b0a", "#5a3723", "#354d30", "#6d4d37", "#4d5e45", "#5d5c67", "#a78672", "#8d8db1", "#b7a9a1", "#b0b4cc", "#eac94a", "#cb9336"] },+ { name: "Breakfast on Schedule", slug: "breakfast-on-schedule", hex: ["#111217", "#732419", "#494637", "#6e5133", "#416c87", "#68734a", "#7b796b", "#91a5b0", "#a6b1aa", "#aac2c8", "#cadcd6", "#533115"] },+ { name: "Favela Gold", slug: "favela-gold", hex: ["#0a0807", "#563322", "#464969", "#57594d", "#765636", "#586f93", "#867b7e", "#aca389", "#85b1f7", "#acb4b5", "#f3f7f3", "#d3ac74"] },+ { name: "A Hotel for One", slug: "a-hotel-for-one", hex: ["#07070c", "#1f1414", "#362e25", "#094b27", "#494b4b", "#2c5354", "#584e3c", "#686664", "#423b30", "#314041", "#4f3a2f", "#101821"] },+ { name: "After Dark", slug: "after-dark", hex: ["#0a090c", "#651113", "#1d2d6c", "#794f3d", "#575a67", "#118d65", "#5b8aa0", "#a99a93", "#ba9569", "#919faf", "#cfcbc6", "#1d1885"] },+ { name: "Crimson Vigi", slug: "crimson-vigi", hex: ["#0b080a", "#483125", "#98261c", "#654f46", "#4870ca", "#926b51", "#e95531", "#bf9982", "#f0854a", "#fec17b", "#dbd6d4", "#c72f1f"] },+ { name: "The Neighbors Saw Everything", slug: "the-neighbors-saw-everything", hex: ["#0f1116", "#2e1c11", "#644727", "#76554a", "#3b6084", "#646058", "#948676", "#9d9fa4", "#778082", "#6293b2", "#b7bcc9", "#5b3b29"] },+ { name: "The Grey Channel", slug: "the-grey-channel", hex: ["#081214", "#164942", "#494d3e", "#6b533b", "#30706c", "#787b61", "#5b8f82", "#9aa491", "#b1b898", "#a4c8b0", "#e7ddb3", "#cecfa5"] },+ { name: "Mirage at Noon", slug: "mirage-at-noon", hex: ["#0c0b0c", "#403733", "#5d463b", "#7f503e", "#695d5a", "#707e9b", "#a47e70", "#b2a3a1", "#a5b9b3", "#d5ced3", "#f4ddaf", "#954924"] },+ { name: "Bubblegum Boulevard", slug: "bubblegum-boulevard", hex: ["#181415", "#2f3973", "#62382f", "#6b524e", "#957a70", "#878894", "#b48f60", "#65b0cb", "#c3b0a9", "#81d7f9", "#e5e0df", "#aa637e"] },+ { name: "Yellow Room", slug: "yellow-room", hex: ["#0e0606", "#222e2a", "#513d1a", "#884f1e", "#6a6a67", "#388516", "#a3a59c", "#67b5ae", "#d0b32b", "#5ac99c", "#e3eccb", "#ebd41a"] },+ { name: "The Earth Keeps Things, Reluctantly", slug: "the-earth-keeps-things-reluctantly", hex: ["#110f11", "#34221f", "#474547", "#55565a", "#6a755f", "#807a7a", "#9b949c", "#9eaf9f", "#beb0b8", "#aeb7d4", "#eae1f5", "#282a48"] },+ { name: "Tropic Fever Dream", slug: "tropic-fever-dream", hex: ["#090c0c", "#6b111a", "#584d54", "#305a6e", "#96414b", "#7c7c88", "#65949b", "#ca8a5e", "#df877a", "#f3b32b", "#c8bda3", "#8d4f28"] },+ { name: "Bioluminescent Night", slug: "bioluminescent-night", hex: ["#0d0f12", "#1f2574", "#2f473f", "#8d421f", "#3d667c", "#54988a", "#83a6bd", "#c099a0", "#b8a3ed", "#d7b06d", "#c0d5db", "#564abb"] },+ { name: "Don't Turn It Off, I'm Watching", slug: "dont-turn-it-off-im-watching", hex: ["#0c0b0c", "#132669", "#16433e", "#245986", "#973911", "#31706c", "#82797f", "#a49051", "#6097b2", "#46b291", "#aba8a3", "#0c1640"] },+ { name: "The Silk Curtain Falls", slug: "the-silk-curtain-falls", hex: ["#1f0303", "#2b313d", "#5f4f36", "#6a512a", "#3a596c", "#ce5838", "#a89062", "#77b2ba", "#c6b395", "#89ece9", "#f7e9d4", "#672a0e"] },+ { name: "The Butterfly", slug: "the-butterfly", hex: ["#0d0c08", "#52463b", "#415747", "#6c604b", "#5c686a", "#708a87", "#918461", "#8694a6", "#bcc5d2", "#efe990", "#eceef2", "#771c1e"] },+ { name: "Playtime", slug: "playtime", hex: ["#12160f", "#4e3921", "#3e4b50", "#4f5451", "#626f6f", "#876b57", "#868f86", "#a8ac9d", "#afbdb3", "#cbd0be", "#c0e1cf", "#725738"] },+ { name: "Wallpaper Romance", slug: "wallpaper-romance", hex: ["#121010", "#741313", "#4a4b58", "#435e6d", "#69605e", "#8b5952", "#787e7b", "#a6997f", "#9fa796", "#bbb192", "#dfd0a4", "#883063"] },+ { name: "Overtime", slug: "overtime", hex: ["#080502", "#1f2a08", "#66450d", "#ac3510", "#746931", "#97611c", "#8f8e6c", "#cb983b", "#a7bc89", "#dfc178", "#edeedf", "#866b22"] },+ { name: "The Way Home Is Longer", slug: "the-way-home-is-longer", hex: ["#0c0a0a", "#2b3352", "#484042", "#525776", "#69544b", "#587ad4", "#c4836c", "#91a6ef", "#b0c0f5", "#dfbcb0", "#e3e1f1", "#6c93f4"] },+ { name: "Everyone Speaks in Whispers", slug: "everyone-speaks-in-whispers", hex: ["#0f0c0b", "#65370d", "#4d4b47", "#724c31", "#5a6661", "#916d4c", "#9a896a", "#7e9689", "#acbb9e", "#c6be94", "#f2f1c4", "#865517"] },+ { name: "Runaway Summer", slug: "runaway-summer", hex: ["#0f0f0d", "#5d1610", "#4e523a", "#595452", "#277540", "#7c745f", "#8a939a", "#b8a590", "#adb1b0", "#d6cc6a", "#c6dfe3", "#be1205"] },+ { name: "Amber Wasteland", slug: "amber-wasteland", hex: ["#0b0b0b", "#294446", "#7b3a07", "#a04003", "#5b6866", "#a8792d", "#798b82", "#9baa95", "#72833f", "#c0b981", "#dad5bc", "#bf6909"] },+ { name: "The Circus", slug: "the-circus", hex: ["#090a0b", "#900304", "#1d5768", "#58554a", "#8e5917", "#627163", "#979d7e", "#7daca6", "#7f907d", "#add3c0", "#ccebd8", "#b70204"] },+ { name: "Gasoline Sunset", slug: "gasoline-sunset", hex: ["#0e0d0c", "#4e2a15", "#0d4486", "#65565d", "#894f29", "#3478a9", "#a09296", "#d38846", "#dab4a2", "#ccb8bd", "#ecd6dd", "#b36521"] },+];++export const LIGHTING_PRESETS: DirectorOption[] = [+ { name: "Silhouette", slug: "silhouette", description: "Backlights the subject into a dark outline against a bright background" },+ { name: "Practicals", slug: "practicals", description: "Lights the scene only from visible in-frame sources (lamps, candles, signage)" },+ { name: "Window", slug: "window", description: "Single directional daylight source through a window; architecture decides light and shadow" },+ { name: "Overhead fall", slug: "overhead-fall", description: "Soft source from above and behind: light on crown and shoulders, eyes in shadow" },+ { name: "Contre jour", slug: "contre-jour", description: "Shooting into the light, like Silhouette but with more spill and flare" },+ { name: "Soft cross", slug: "soft-cross", description: "Two soft sources crossing at an angle; half the face in light, smooth transition" },+ { name: "Auto", slug: null, description: "Lets the model choose the lighting from scene context" },+];++export const EMOTION_FAMILIES: EmotionFamily[] = [+ { name: "Anger", colors: ["#C86058", "#A83028", "#801818"], steps: [{"name": "Annoyance", "prompt": "(with frustrated emotion)", "intensity": 10}, {"name": "Anger", "prompt": "(with mad and angry emotions)", "intensity": 50}, {"name": "Rage", "prompt": "(with extremely enraged emotions loudly)", "intensity": 100}] },+ { name: "Joy", colors: ["#D0C060", "#C0A820", "#B09018"], steps: [{"name": "Serenity", "prompt": "(relaxed emotion)", "intensity": 10}, {"name": "Joy", "prompt": "(happy and joyful emotion)", "intensity": 50}, {"name": "Ecstasy", "prompt": "(happy and smiling emotion)", "intensity": 100}] },+ { name: "Trust", colors: ["#80C070", "#4C9840", "#2E7828"], steps: [{"name": "Acceptance", "prompt": "(welcoming emotion)", "intensity": 10}, {"name": "Trust", "prompt": "(faithful and trust emotion)", "intensity": 50}, {"name": "Admiration", "prompt": "(with admiration)", "intensity": 100}] },+ { name: "Fear", colors: ["#58A880", "#2E7C58", "#186040"], steps: [{"name": "Apprehension", "prompt": "(nervously)", "intensity": 10}, {"name": "Fear", "prompt": "(with strong fear and shock)", "intensity": 50}, {"name": "Terror", "prompt": "(with extreme terror emotion and panic)", "intensity": 100}] },+ { name: "Surprise", colors: ["#4098B0", "#1878A0", "#085870"], steps: [{"name": "Distraction", "prompt": "(with confused emotion)", "intensity": 10}, {"name": "Surprise", "prompt": "(with surprised face)", "intensity": 50}, {"name": "Amazement", "prompt": "(with stunned and amazed emotion)", "intensity": 100}] },+ { name: "Sadness", colors: ["#5878B0", "#284888", "#182868"], steps: [{"name": "Pensiveness", "prompt": "(with thoughtful emotion)", "intensity": 10}, {"name": "Sadness", "prompt": "(with sad emotion)", "intensity": 50}, {"name": "Grief", "prompt": "(with grief emotion)", "intensity": 100}] },+ { name: "Disgust", colors: ["#8868A0", "#5C3880", "#401860"], steps: [{"name": "Boredom", "prompt": "(with bored emotion)", "intensity": 10}, {"name": "Disgust", "prompt": "(with disgusted emotion)", "intensity": 50}, {"name": "Loathing", "prompt": "(with hateful and loathing emotion)", "intensity": 100}] },+ { name: "Hope", colors: ["#F0B060", "#E88C28", "#D07010"], steps: [{"name": "Interest", "prompt": "(with intrigued and curious emotions)", "intensity": 10}, {"name": "Hope", "prompt": "(with hopeful and expectant emotions)", "intensity": 50}, {"name": "Vigilance", "prompt": "(with watchful and on-guard emotions)", "intensity": 100}] },+];+++/**+ * Focal lengths. The research confirms the field (`camera_focal_length_id`, required for stills) but+ * Higgsfield's value list needs a login, so these are the standard cine primes.+ */+export const FOCAL_LENGTHS: DirectorOption[] = [+ { name: "Auto", slug: null, description: "Model chooses from scene context" },+ { name: "14mm", slug: "14mm", description: "Ultra-wide: vast spaces, strong perspective" },+ { name: "24mm", slug: "24mm", description: "Wide: the place is part of the shot" },+ { name: "35mm", slug: "35mm", description: "Wide-normal: the classic storytelling lens" },+ { name: "50mm", slug: "50mm", description: "Normal: close to the human eye, honest proportions" },+ { name: "85mm", slug: "85mm", description: "Portrait: flattering faces, soft compressed background" },+ { name: "135mm", slug: "135mm", description: "Telephoto: strong compression, isolated subject" },+];++/** Fuobe's camera-motion presets for the same moves (their open routes carry the camera LoRAs). */+const MOVE_MOTION: Record<string, string> = {+ snorricam: "motion-snorricam",+ "robot-arm": "motion-robot-arm",+ "tilt-up": "motion-tilt-up",+ "rack-focus": "motion-focus-change",+ "tilt-down": "motion-tilt-down",+ pov: "motion-pov",+ "pan-left": "motion-pan-left",+ "crane-up": "motion-crane-up",+ "pan-right": "motion-pan-right",+ "crane-down": "motion-crane-down",+ "side-tracking": "motion-tracking",+ "pedestal-up": "motion-jib-up",+ "pedestal-down": "motion-pedestal-down",+ handheld: "motion-handheld",+ tracking: "motion-tracking",+ "drone-orbit": "motion-360-orbit",+ "dolly-zoom": "motion-dolly-zoom-in",+ "aerial-pullback": "motion-aerial-pullback",+ "static-shot": "motion-static",+ "bullet-time": "motion-bullet-time",+ "whip-pan": "motion-whip-pan",+ "slow-zoom-in": "motion-zoom-in",+ "arc-left": "motion-arc-left",+ "slow-zoom-out": "motion-zoom-out",+ "arc-right": "motion-arc-right",+ "truck-right": "motion-truck-right",+ "dolly-in": "motion-dolly-in",+ "truck-left": "motion-truck-left",+ "dolly-out": "motion-dolly-out",+ "slider-right": "motion-dolly-right",+ "crush-zoom": "motion-crash-zoom-in",+ "slider-left": "motion-dolly-left",+ "helicopter-shot": "motion-helicopter-shot",+};++/** Poses Wan 2.2 Fun Camera understands (wan22-fun-camera-14b `cameraMotion`), as in catalog/index.ts. */+const MOVE_FUN_CAMERA: Record<string, string> = {+ "pan-left": "Pan Left",+ "pan-right": "Pan Right",+ "tilt-up": "Pan Up",+ "tilt-down": "Pan Down",+ "slow-zoom-in": "Zoom In",+ "slow-zoom-out": "Zoom Out",+ "dolly-in": "Zoom In",+ "dolly-out": "Zoom Out",+ "crush-zoom": "Zoom In",+ "static-shot": "Static",+};++const lcFirst = (s: string) => (s ? s.charAt(0).toLowerCase() + s.slice(1) : s);+const tidy = (s: string | undefined) => (s ?? "").trim().replace(/[.\s]+$/, "");++/** All 33 camera moves Cinema Studio 4.0 accepts, in the API's order. */+export const CAMERA_MOVES: CameraMove[] = RAW_MOVES.map(([slug, name, hint, confirmed]) => {+ const motionId = MOVE_MOTION[slug];+ const preset = motionId ? getPreset(motionId) : undefined;+ // The preset's camera-language prompt is tuned for video models; fall back to the research hint.+ const phrase = preset ? tidy(preset.promptTemplate.replace(/^\{prompt\}\.\s*/, "")) : hint;+ return { slug, name, hint, confirmed, phrase: lcFirst(phrase), motionId: preset ? motionId : undefined, funCamera: MOVE_FUN_CAMERA[slug] };+});++const MOVE_INDEX = new Map(CAMERA_MOVES.map((m) => [m.slug, m]));+export const moveBySlug = (slug: string) => MOVE_INDEX.get(slug);+export const paletteBySlug = (slug: string) => PALETTES.find((p) => p.slug === slug);++/** The 26 light directions the custom rig accepts: 6 faces, 12 edges, 8 corners. */+export const LIGHT_DIRECTIONS: LightDirection[] = (() => {+ const fb = ["front", "back"];+ const tb = ["top", "bottom"];+ const lr = ["left", "right"];+ const out = [...fb, ...tb, ...lr];+ for (const a of fb) for (const b of tb) out.push(`${a}-${b}`);+ for (const a of fb) for (const b of lr) out.push(`${a}-${b}`);+ for (const a of tb) for (const b of lr) out.push(`${a}-${b}`);+ for (const a of fb) for (const b of tb) for (const c of lr) out.push(`${a}-${b}-${c}`);+ return out;+})();+export const QUICK_LIGHT_DIRECTIONS: LightDirection[] = ["top", "front", "right", "left", "bottom"];+export const MAX_LIGHTS = 2;++// ---------------------------------------------------------------------------+// Generation settings (cinemaStudio.videoModes, imageMode, references)++export const VIDEO_ASPECTS = ["21:9", "16:9", "4:3", "1:1", "3:4", "9:16"];+export const IMAGE_ASPECTS = ["16:9", "21:9", "3:2", "4:3", "1:1", "3:4", "2:3", "9:16"];+export const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"];+export const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"];+export const DURATION = { min: 4, max: 30, default: 5 } as const;+export const BATCH = { min: 1, max: 4 } as const;+export const REFERENCE_LIMITS = { images: 30, videos: 10, audios: 10, total: 50, clipMin: 2, clipMax: 30, totalVideo: 30, totalAudio: 30 } as const;++/** Models offered in the prompt bar, per mode and engine. The first is the default. */+export const CINEMA_MODELS: Record<CinemaMode, Record<Engine, string[]>> = {+ video: { cloud: ["cinema-studio-4", "seedance-2-5", "kling-3", "veo-3-1"], open: ["oss-wan22-14b-fast", "oss-wan22-14b"] },+ image: { cloud: ["nano-banana-pro", "seedream-5-pro", "soul-cinema"], open: ["oss-z-image-turbo", "oss-qwen-image"] },+};+/** Models that need a Higgsfield key to run for real. */+export const HIGGSFIELD_ONLY = new Set(["cinema-studio-4", "soul-cinema", "soul-2"]);++export interface ReferenceCheck {+ images: number;+ videos: number[];+ audios: number[];+ elements: number;+}++/** Higgsfield's reference limits, with its own messages. Durations in seconds (NaN = unknown yet). */+export function checkReferences(r: ReferenceCheck): string | null {+ const L = REFERENCE_LIMITS;+ if (r.images > L.images) return `You can add a maximum of ${L.images} images`;+ if (r.videos.length > L.videos) return `You can add a maximum of ${L.videos} videos`;+ if (r.audios.length > L.audios) return `You can add a maximum of ${L.audios} audios`;+ if (r.images + r.videos.length + r.audios.length + r.elements > L.total) return `You can add a maximum of ${L.total} input media items, including Elements`;+ const known = (xs: number[]) => xs.filter((d) => Number.isFinite(d));+ if (known(r.videos).some((d) => d < L.clipMin || d > L.clipMax)) return `Each reference video must be at least ${L.clipMin} seconds and no more than ${L.clipMax} seconds`;+ if (known(r.audios).some((d) => d < L.clipMin || d > L.clipMax)) return `Each reference audio file must be at least ${L.clipMin} seconds and no more than ${L.clipMax} seconds`;+ if (known(r.videos).reduce((a, b) => a + b, 0) > L.totalVideo) return `The total video duration limit is ${L.totalVideo} seconds`;+ if (known(r.audios).reduce((a, b) => a + b, 0) > L.totalAudio) return `The total audio duration limit is ${L.totalAudio} seconds`;+ return null;+}++// ---------------------------------------------------------------------------+// Grid generation (cinemaStudio.imageMode.grid)++export const GRID_SIZES: { id: GridSize; name: string }[] = [+ { id: "2x2", name: "2×2" },+ { id: "3x3", name: "3×3" },+ { id: "4x4", name: "4×4" },+];++export const GRID_TYPES: { id: GridType; name: string; description: string; instruction: string }[] = [+ { id: "freeform", name: "Freeform", description: "Different frames from the same scene", instruction: "different, distinct frames from the same scene, each with its own composition" },+ { id: "zooms", name: "Zooms", description: "The same moment, from wide to extreme close-up", instruction: "the same moment at progressively tighter framing, from an extreme wide shot in the first panel to an extreme close-up in the last" },+ { id: "shots", name: "Shots", description: "Coverage: the moment from many angles", instruction: "the same moment covered from different camera angles: wide, medium, close-up, over-the-shoulder, low angle, high angle, profile, insert detail and point of view" },+ { id: "next_shots", name: "Next shots", description: "What happens next, shot by shot", instruction: "consecutive shots that continue the story forward in time, one beat per panel" },+ { id: "prev_shots", name: "Previous shots", description: "What led up to this moment", instruction: "the shots that lead up to this moment, one beat per panel, the last panel being the moment itself" },+];++export function gridDims(size: GridSize): { rows: number; cols: number } {+ const n = Number(size[0]);+ return { rows: n, cols: n };+}++/** One prompt for the whole contact sheet; every panel shares the same context. */+export function gridPrompt(scene: string, size: GridSize, type: GridType): string {+ const { rows, cols } = gridDims(size);+ const t = GRID_TYPES.find((g) => g.id === type) ?? GRID_TYPES[0];+ return [+ `A cinematic contact sheet: a ${cols}×${rows} grid of ${rows * cols} equally sized film stills separated by thin, straight white gutters, no text, no numbers, no borders around the sheet`,+ `The panels, in reading order (left to right, top to bottom), show ${t.instruction}`,+ `Same characters, wardrobe, location, lighting and colour grade in every panel`,+ `Scene: ${tidy(scene)}`,+ ].join(". ") + ".";+}++// ---------------------------------------------------------------------------+// Soul Cast (cinemaStudio.soulCast, higgsfield-image-studios.json → characterSheet.soulCast)++export interface CastField {+ key: string;+ label: string;+ tab: string;+ question?: string;+ kind: "list" | "ruler" | "multi";+ options: (string | number)[];+ default?: string | number;+ /** "${v}M", "{v}s", "{v}yo" */+ format?: string;+ /** Also takes a free-text description (≤ 300 characters). */+ manual?: boolean;+ /** Shown only when this returns true. */+ when?: (v: CastValues) => boolean;+}++const BEARDED = ["Beard", "Long beard", "Mustache", "Short beard"];++export const SOUL_CAST_FIELDS: CastField[] = [+ { key: "genre", label: "Genre", tab: "Genre", question: "Select the genre of your movie", kind: "list", options: ["Action", "Adventure", "Comedy", "Drama", "Thriller", "Horror", "Detective", "Romance", "Sci-Fi", "Fantasy", "War", "Western", "Historical", "Sitcom"] },+ { key: "budget", label: "Budget", tab: "Budget", question: "What's your production budget?", kind: "ruler", options: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 350, 400, 450, 500], default: 250, format: "${v}M" },+ { key: "era", label: "Era", tab: "Era", question: "What period is your film set in?", kind: "ruler", options: [1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020], default: 2020, format: "{v}s" },+ { key: "archetype", label: "Archetype", tab: "Archetype", question: "Select the archetype of your character", kind: "list", options: ["Innocent", "Everyman", "Hero", "Caregiver", "Explorer", "Rebel", "Lover", "Creator", "Jester", "Sage", "Magician", "Ruler"] },+ { key: "gender", label: "Gender", tab: "Identity", kind: "list", options: ["Male", "Female"] },+ { key: "race", label: "Race", tab: "Identity", kind: "list", options: ["White", "Black", "Asian", "Latino", "Indigenous", "Mixed"] },+ { key: "age", label: "Age", tab: "Identity", kind: "ruler", options: [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70], format: "{v}yo" },+ { key: "build", label: "Build", tab: "Physical Appearance", kind: "list", options: ["Slim", "Average", "Athletic", "Muscular", "Stocky", "Plus-size"] },+ { key: "height", label: "Height", tab: "Physical Appearance", kind: "ruler", options: ["Very short", "Short", "Average", "Tall", "Very tall"] },+ { key: "eye_color", label: "Eye Color", tab: "Physical Appearance", kind: "list", options: ["Brown", "Blue", "Green", "Hazel", "Gray", "Amber"], manual: true },+ { key: "hair_style", label: "Hair Style", tab: "Physical Appearance", kind: "list", options: ["Short", "Medium", "Long", "Very long", "Ponytail", "Bun", "Braids", "Dreadlocks", "Afro", "Fringe/Bangs", "Undercut", "Slick back", "Messy", "Shaved sides", "Bald"] },+ { key: "hair_texture", label: "Hair Texture", tab: "Physical Appearance", kind: "list", options: ["Straight", "Wavy", "Curly", "Coily"] },+ { key: "hair_color", label: "Hair Color", tab: "Physical Appearance", kind: "list", options: ["Black", "Brown", "Blonde", "Red", "Gray", "White", "Auburn"], manual: true },+ { key: "facial_hair", label: "Facial Hair", tab: "Physical Appearance", kind: "list", options: ["Clean-shaven", "Stubble", "Beard", "Short beard", "Mustache", "Long beard"], when: (v) => v.gender !== "Female" },+ { key: "facial_hair_color", label: "Facial Hair Color", tab: "Physical Appearance", kind: "list", options: ["Black", "Brown", "Blonde", "Red", "Gray", "White", "Light brown", "Auburn"], manual: true, when: (v) => v.gender !== "Female" && BEARDED.includes(String(v.facial_hair)) },+ { key: "imperfections", label: "Details", tab: "Details", question: "Add details to your character", kind: "multi", options: ["Facial scar", "Freckles", "Tattoos", "Eye patch"], manual: true },+ { key: "outfit", label: "Outfit", tab: "Outfit", question: "Select or describe your character's outfit", kind: "list", options: ["Casual", "Formal", "High Fashion", "Military", "Sporty", "Workwear", "Vintage", "Punk"], manual: true },+];++export const SOUL_CAST_TABS = [...new Set(SOUL_CAST_FIELDS.map((f) => f.tab))];+export const castDefaults = (): CastValues => ({ budget: 250, era: 2020 });++/** Higgsfield's Randomize: genre, era, race, gender, age and archetype. */+export function randomizeCast(values: CastValues, rand: () => number = Math.random): CastValues {+ const pick = (key: string) => {+ const f = SOUL_CAST_FIELDS.find((x) => x.key === key)!;+ return f.options[Math.floor(rand() * f.options.length) % f.options.length];+ };+ const next: CastValues = { ...values };+ for (const k of ["genre", "era", "race", "gender", "age", "archetype"]) next[k] = pick(k);+ if (next.gender === "Female") {+ delete next.facial_hair;+ delete next.facial_hair_color;+ }+ return next;+}++/** Only the fields that are visible for these values (facial hair hides for women, its colour without a beard). */+export function visibleCast(values: CastValues): CastValues {+ const out: CastValues = {};+ for (const f of SOUL_CAST_FIELDS) {+ if (f.when && !f.when(values)) continue;+ if (values[f.key] !== undefined && values[f.key] !== "") out[f.key] = values[f.key];+ const manual = values[`${f.key}_text`];+ if (f.manual && typeof manual === "string" && manual.trim()) out[`${f.key}_text`] = manual.trim().slice(0, 300);+ }+ return out;+}++const castText = (v: CastValues, key: string) => {+ const manual = v[`${key}_text`];+ if (typeof manual === "string" && manual.trim()) return manual.trim().slice(0, 300);+ const val = v[key];+ return Array.isArray(val) ? val.join(", ") : val === undefined || val === "" ? undefined : String(val);+};++/** The casting prompt: a turnaround character sheet from the Soul Cast choices. */+export function castPrompt(values: CastValues, description?: string): string {+ const v = visibleCast(values);+ const t = (k: string) => castText(v, k)?.toLowerCase();+ const film = [t("genre") && `${t("genre")} film`, v.budget && `with a $${v.budget}M budget`, v.era && `set in the ${v.era}s`].filter(Boolean).join(" ");+ const who = [v.age && `${v.age}-year-old`, t("race"), t("gender") === "male" ? "man" : t("gender") === "female" ? "woman" : "person"].filter(Boolean).join(" ");+ const looks = [+ t("archetype") && `the ${t("archetype")} archetype`,+ t("build") && `${t("build")} build`,+ t("height") && `${t("height")} height`,+ t("eye_color") && `${t("eye_color")} eyes`,+ (t("hair_style") || t("hair_color") || t("hair_texture")) &&+ (t("hair_style") === "bald" ? "bald" : `${[t("hair_texture"), t("hair_color")].filter(Boolean).join(" ")} hair${t("hair_style") ? ` (${t("hair_style")})` : ""}`.trim()),+ t("facial_hair") && (t("facial_hair_color") && t("facial_hair") !== "clean-shaven" ? `${t("facial_hair_color")} ${t("facial_hair")}` : t("facial_hair")),+ t("imperfections") && `distinguishing details: ${t("imperfections")}`,+ t("outfit") && `wearing a ${t("outfit")} outfit`,+ ].filter(Boolean);+ return [+ `Casting turnaround sheet for an original film character${film ? ` in a ${film}` : ""}: a ${who}${looks.length ? `, ${looks.join(", ")}` : ""}`,+ tidy(description) || undefined,+ "Full-body front view, three-quarter view, side profile and back view side by side, plus a close-up portrait of the face, on a seamless neutral studio backdrop with soft, even lighting",+ "The same person, face and wardrobe in every view; photorealistic, natural skin texture, no text",+ ]+ .filter(Boolean)+ .join(". ") + ".";+}++/** A starting name for the saved element ("Rebel, 30s"); renamed on the element page. */+export function castName(values: CastValues): string {+ const archetype = values.archetype ? String(values.archetype) : "Cast member";+ return values.age ? `${archetype} ${values.age}` : archetype;+}++// ---------------------------------------------------------------------------+// Soul Location (cinemaStudio.soulLocation)++export const LOCATION_VIEWS: { id: string; name: string; prompt: string }[] = [+ { id: "reverse", name: "Reverse angle", prompt: "Show the same location from the opposite direction (a reverse angle), as if the camera turned around" },+ { id: "wide", name: "Wider", prompt: "Show the same location from further back, a wider establishing view that reveals more of it" },+ { id: "close", name: "Closer, eye level", prompt: "Show the same location from closer in, at eye level, framing the most interesting part of the set" },+ { id: "high", name: "High angle", prompt: "Show the same location from a high angle looking down, as from a crane or a balcony" },+];++/** An empty 16:9 set: no people, the place itself is the subject. */+export function locationPrompt(description: string, settings: DirectorSettings): string {+ const camera = cameraWords(settings, true);+ const palette = paletteWords(settings.palette);+ const light = lightingWords(settings.lighting);+ return [+ `Establishing shot of a film location: ${tidy(description)}`,+ "An empty set with no people, wide 16:9 composition with depth, production-designed detail, cinematic lighting",+ camera,+ light,+ palette,+ ]+ .filter(Boolean)+ .join(". ") + ".";+}++export function locationViewPrompt(view: string, description?: string): string {+ const v = LOCATION_VIEWS.find((x) => x.id === view) ?? LOCATION_VIEWS[0];+ return `${v.prompt}. Keep everything about the place the same: architecture, props, materials, time of day, lighting and colour grade. No people${tidy(description) ? `. ${tidy(description)}` : ""}.`;+}++// ---------------------------------------------------------------------------+// Compile: Director settings → model fields and/or prompt words++const find = (list: DirectorOption[], slug: string | null | undefined) => (slug ? list.find((o) => o.slug === slug) : undefined);+export const optionName = (list: DirectorOption[], slug: string | null | undefined) => find(list, slug)?.name ?? "Auto";++export function paletteHex(choice: PaletteChoice | null | undefined): string[] | undefined {+ if (!choice) return undefined;+ if (choice.kind === "preset") return paletteBySlug(choice.slug)?.hex;+ return choice.hex.length ? choice.hex : undefined;+}++export function paletteLabel(choice: PaletteChoice | null | undefined): string | undefined {+ if (!choice) return undefined;+ return choice.kind === "preset" ? paletteBySlug(choice.slug)?.name : choice.name || "Custom palette";+}++export function emotionStep(choice: EmotionChoice | undefined): (EmotionStep & { family: EmotionFamily; color: string }) | undefined {+ if (!choice) return undefined;+ const family = EMOTION_FAMILIES.find((f) => f.name === choice.family);+ const i = Math.max(0, Math.min(2, Math.round(choice.step)));+ const step = family?.steps[i];+ return family && step ? { ...step, family, color: family.colors[i] } : undefined;+}++const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/** "@maya walks in" + Sadness → "@maya (with sad emotion) walks in" (first mention of each character). */+export function applyEmotions(prompt: string, emotions: DirectorSettings["emotions"]): string {+ let out = prompt;+ for (const [handle, choice] of Object.entries(emotions ?? {})) {+ const step = emotionStep(choice);+ if (!step) continue;+ const re = new RegExp(`@${escapeRe(handle)}(?![\\p{L}\\p{N}_-])`, "iu");+ const m = re.exec(out);+ if (!m) continue;+ const at = m.index + m[0].length;+ if (out.slice(at).trimStart().startsWith(step.prompt)) continue;+ out = `${out.slice(0, at)} ${step.prompt}${out.slice(at)}`;+ }+ return out;+}++function eraWords(era: DirectorOption): string {+ return /^\d{4}s$/.test(era.slug ?? "") ? era.slug! : era.name;+}++/** "Shot on 35mm film with an anamorphic lens, 50mm, f/1.4" (only the parts that are set). */+export function cameraWords(s: DirectorSettings, includeAperture = true, skip: { body?: boolean; lens?: boolean; aperture?: boolean } = {}): string | undefined {+ const body = skip.body ? undefined : find(CAMERA_BODIES, s.camera);+ const lens = skip.lens ? undefined : find(LENSES, s.lens);+ const focal = find(FOCAL_LENGTHS, s.focal);+ const aperture = !includeAperture || skip.aperture ? undefined : find(APERTURES, s.aperture);+ const bits = [+ body && `shot on ${body.name === "Modern" ? "a modern digital cinema camera" : body.name === "DV Camcorder" ? "a DV camcorder" : body.name} (${lcFirst(body.description)})`,+ lens && `${body ? "with" : "shot with"} ${/^[aeiou]/i.test(lens.name) ? "an" : "a"} ${lens.name.toLowerCase()} lens (${lcFirst(lens.description)})`,+ focal && `${focal.name} focal length (${lcFirst(focal.description)})`,+ aperture && `${aperture.name.replace(/ .*/, "")} aperture (${lcFirst(aperture.description)})`,+ ].filter(Boolean) as string[];+ if (!bits.length) return undefined;+ const text = bits.join(", ");+ return text.charAt(0).toUpperCase() + text.slice(1);+}++const HUE_NAMES: [number, string][] = [+ [15, "red"],+ [40, "orange"],+ [65, "amber"],+ [80, "yellow"],+ [160, "green"],+ [195, "teal"],+ [250, "blue"],+ [290, "violet"],+ [335, "magenta"],+ [360, "red"],+];++/** A rough colour name for prompt text ("warm orange", "pale blue", "white"). */+export function colorName(hex: string): string {+ const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());+ if (!m) return hex;+ const n = parseInt(m[1], 16);+ const r = ((n >> 16) & 255) / 255;+ const g = ((n >> 8) & 255) / 255;+ const b = (n & 255) / 255;+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ if (d < 0.08) return l > 0.85 ? "white" : l < 0.15 ? "black" : "neutral grey";+ let h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;+ h = (h * 60 + 360) % 360;+ const name = HUE_NAMES.find(([limit]) => h < limit)?.[1] ?? "red";+ const tone = l > 0.75 ? "pale " : l < 0.3 ? "deep " : "";+ const temp = h < 70 || h >= 335 ? "warm " : h >= 160 && h < 290 ? "cool " : "";+ return `${tone || temp}${name}`.trim();+}++export function rigError(lights: LightSource[]): string | null {+ if (!lights.length) return "A custom light rig needs at least one light source";+ if (lights.length > MAX_LIGHTS) return `A custom rig supports at most ${MAX_LIGHTS} light sources`;+ for (const l of lights) {+ if (!/^#[0-9a-f]{6}$/i.test(l.color)) return "color must be a #RRGGBB hex value";+ if (!Number.isInteger(l.brightness) || l.brightness < 0 || l.brightness > 100) return "brightness must be an integer between 0 and 100";+ if (!Number.isInteger(l.diffuse) || l.diffuse < 0 || l.diffuse > 100) return "diffuse must be an integer between 0 and 100";+ if (!LIGHT_DIRECTIONS.includes(l.direction)) return "Pick a direction for every light";+ }+ return null;+}++export function lightingWords(choice: LightingChoice | null | undefined): string | undefined {+ if (!choice) return undefined;+ if (choice.kind === "preset") {+ const p = find(LIGHTING_PRESETS, choice.slug);+ return p ? `Lighting: ${p.name.toLowerCase()}, ${lcFirst(p.description)}` : undefined;+ }+ if (rigError(choice.lights)) return undefined;+ const names = ["key light", "second light"];+ const lights = choice.lights.map(+ (l, i) =>+ `${names[i]} from the ${l.direction.replace(/-/g, " ")}, ${colorName(l.color)} (${l.color.toLowerCase()}) at ${l.brightness}% brightness, ${l.diffuse >= 60 ? "soft and diffuse" : l.diffuse >= 30 ? "semi-soft" : "hard"} (${l.diffuse}% diffusion)`,+ );+ return `Lighting rig: ${lights.join("; ")}`;+}++export function paletteWords(choice: PaletteChoice | null | undefined): string | undefined {+ const hex = paletteHex(choice);+ if (!hex) return undefined;+ const name = choice?.kind === "preset" ? ` "${paletteLabel(choice)}"` : "";+ return `Colour grade following the${name} palette ${hex.map((h) => h.toLowerCase()).join(", ")} (shadows to highlights, accent ${hex[hex.length - 1].toLowerCase()})`;+}++export function movesWords(moves: string[]): string | undefined {+ const ms = moves.map((m) => moveBySlug(m)).filter((m): m is CameraMove => !!m);+ if (!ms.length) return undefined;+ if (ms.length === 1) return `Camera: ${ms[0].phrase}`;+ return `Camera moves, in this order: ${ms.map((m, i) => `${i === 0 ? "first" : i === ms.length - 1 ? "finally" : "then"} ${m.phrase}`).join("; ")}`;+}++/** The brief rides along with every prompt; long briefs are cut at a sentence. */+export function briefWords(brief: string | undefined): string | undefined {+ const b = (brief ?? "").replace(/\s+/g, " ").trim();+ if (!b) return undefined;+ const cut = b.length > 900 ? `${b.slice(0, 900).replace(/[^.!?]*$/, "").trim() || b.slice(0, 900)}` : b;+ return `Project brief: ${tidy(cut)}`;+}++export interface CompileInput {+ prompt: string;+ settings: DirectorSettings;+ moves?: string[];+ brief?: string;+ mode: CinemaMode;+ /** "native": Cinema Studio 4.0 reads the Director fields itself; "prompt": everything goes into words. */+ target: "native" | "prompt";+}++export interface CompiledDirector {+ prompt: string;+ /** Cinema Studio 4.0 fields (params.extra): genre, era, pacing, camera_model, camera_lens, camera_aperture, light, color_palette, camera_movement. */+ extra: Record<string, string>;+}++/**+ * Turn the Director's Panel into what a model understands. Auto fields are left out. On the native+ * target only what Cinema Studio 4.0 can't take as a field (focal length, the moves after the first,+ * a custom palette or light rig) is written into the prompt; on the prompt target, everything is.+ */+export function compileDirector(input: CompileInput): CompiledDirector {+ const s = input.settings ?? {};+ const native = input.target === "native";+ const video = input.mode === "video";+ const extra: Record<string, string> = {};+ const parts: (string | undefined)[] = [];++ const genre = find(GENRES, s.genre);+ const era = find(ERAS, s.era);+ const tempo = video ? find(TEMPOS, s.tempo) : undefined;+ if (native) {+ if (genre) extra.genre = genre.slug!;+ if (era) extra.era = era.slug!;+ if (tempo) extra.pacing = tempo.slug!;+ } else {+ if (genre) parts.push(`${genre.name} film: ${lcFirst(genre.description)}`);+ if (era) parts.push(`Set in the ${eraWords(era)}: ${lcFirst(era.description)}`);+ if (tempo) parts.push(`Montage pacing: ${tempo.name.toLowerCase()}, ${lcFirst(tempo.description)}`);+ }++ const body = find(CAMERA_BODIES, s.camera);+ const lens = find(LENSES, s.lens);+ const aperture = find(APERTURES, s.aperture);+ if (native) {+ if (body) extra.camera_model = body.slug!;+ if (lens) extra.camera_lens = lens.slug!;+ if (aperture) extra.camera_aperture = aperture.slug!;+ }+ parts.push(cameraWords(s, true, native ? { body: true, lens: true, aperture: true } : {}));++ const moves = video ? (input.moves ?? []).filter((m) => moveBySlug(m)) : [];+ if (native && moves.length) {+ extra.camera_movement = moves[0];+ if (moves.length > 1) parts.push(`${movesWords(moves)}`);+ } else parts.push(movesWords(moves));++ if (native && s.lighting?.kind === "preset" && find(LIGHTING_PRESETS, s.lighting.slug)) extra.light = s.lighting.slug;+ else parts.push(lightingWords(s.lighting));++ if (native && s.palette?.kind === "preset" && paletteBySlug(s.palette.slug)) extra.color_palette = s.palette.slug;+ else parts.push(paletteWords(s.palette));++ const scene = tidy(applyEmotions(input.prompt ?? "", s.emotions));+ const text = [briefWords(input.brief), scene, ...parts]+ .filter((p): p is string => !!p && !!p.trim())+ .map((p) => tidy(p))+ .join(". ");+ return { prompt: text ? `${text}.` : "", extra };+}++/** "Noir · 80s · Calm" — the Director chips' summary. */+export function directorSummary(s: DirectorSettings): string[] {+ return [+ find(GENRES, s.genre)?.name,+ find(ERAS, s.era)?.name,+ find(TEMPOS, s.tempo)?.name,+ find(CAMERA_BODIES, s.camera)?.name,+ find(LENSES, s.lens)?.name,+ find(FOCAL_LENGTHS, s.focal)?.name,+ find(APERTURES, s.aperture)?.name.replace(/ .*/, ""),+ s.lighting?.kind === "preset" ? find(LIGHTING_PRESETS, s.lighting.slug)?.name : s.lighting ? "Custom light" : undefined,+ paletteLabel(s.palette),+ ].filter((x): x is string => !!x);+}++/** Cinematic stills need the camera, lens and focal length (Higgsfield: "Camera settings are required"). */+export function stillCameraMissing(s: DirectorSettings): string | null {+ const missing = [!s.camera && "camera", !s.lens && "lens", !s.focal && "focal length"].filter(Boolean);+ return missing.length ? `Camera settings are required — pick a ${missing.join(", ")}` : null;+}++// ---------------------------------------------------------------------------+// Planning: which model, which steps++/**+ * Open camera route for a move: a camera LoRA (from the motion preset), else a Fun Camera pose, else+ * prompt only. Both need a start frame: the camera LoRAs are trained on Wan 2.2 image-to-video.+ */+export function openCameraRoute(slug: string, hasStartFrame: boolean): { via: "lora" | "fun-camera" | "prompt"; loras?: LoraRef[]; trigger?: string; pose?: string } {+ const move = moveBySlug(slug);+ if (!move) return { via: "prompt" };+ const preset = move.motionId ? getPreset(move.motionId) : undefined;+ const loras = preset?.open?.loras;+ if (loras?.length && hasStartFrame) return { via: "lora", loras, trigger: loras.find((l) => l.trigger)?.trigger };+ if (move.funCamera && hasStartFrame) return { via: "fun-camera", pose: move.funCamera };+ return { via: "prompt" };+}++/** The chain-slot placeholder a planned step uses for the palette swatch (the server swaps in the real PNG). */+export const SWATCH_PLACEHOLDER = "/api/files/placeholder.png";++const PLACEHOLDER = { image: "/api/files/placeholder.png", video: "/api/files/placeholder.mp4", audio: "/api/files/placeholder.wav" };++/** A dependent step's request with placeholder inputs in its chain slots (to plan and price it before its inputs exist). */+export function withPlaceholders(step: CinemaStep): GenerationRequest {+ const req = step.request;+ if (!req.chain?.length) return req;+ const inputs = { ...req.inputs };+ for (const c of req.chain) {+ if (c.slot === "images") inputs.images = c.position === "first" ? [PLACEHOLDER.image, ...(inputs.images ?? [])] : [...(inputs.images ?? []), PLACEHOLDER.image];+ else if (c.slot === "videos") inputs.videos = [...(inputs.videos ?? []), PLACEHOLDER.video];+ else if (c.slot === "endImage") inputs.endImage = PLACEHOLDER.image;+ else if (c.slot === "video") inputs.video = PLACEHOLDER.video;+ else if (c.slot === "audio" || c.slot === "voiceAudio") inputs[c.slot] = PLACEHOLDER.audio;+ }+ return { ...req, inputs };+}++function nearest<T extends number>(values: T[], want: number): T {+ return [...values].sort((a, b) => Math.abs(a - want) - Math.abs(b - want) || a - b)[0];+}++/** Fit ratio, resolution, duration and batch to what the model takes, saying what changed. */+function fitParams(model: ModelDef, input: CinemaGenerateInput, notes: string[], kind: CinemaMode): GenParams {+ const o = model.options;+ const params: GenParams = {};+ const ar = input.aspectRatio ?? (kind === "video" ? "16:9" : "16:9");+ if (o.aspectRatios?.length && !o.aspectRatios.includes(ar)) {+ params.aspectRatio = model.defaults?.aspectRatio && o.aspectRatios.includes(model.defaults.aspectRatio) ? model.defaults.aspectRatio : o.aspectRatios[0];+ notes.push(`${model.name} doesn't make ${ar} — using ${params.aspectRatio}`);+ } else if (o.aspectRatios?.length || ar) params.aspectRatio = ar;+ const res = input.resolution;+ if (res && o.resolutions?.length) {+ if (o.resolutions.includes(res)) params.resolution = res;+ else {+ const order = kind === "video" ? VIDEO_RESOLUTIONS : [...IMAGE_RESOLUTIONS, "0.5K", "1.5K", "720p", "1080p"];+ const below = o.resolutions.filter((r) => order.indexOf(r) <= order.indexOf(res) && order.indexOf(r) >= 0);+ params.resolution = below.sort((a, b) => order.indexOf(b) - order.indexOf(a))[0] ?? o.resolutions[0];+ notes.push(`${model.name} renders up to ${params.resolution} here`);+ }+ }+ if (kind === "video" && model.kind === "video") {+ const want = Math.max(DURATION.min, Math.min(DURATION.max, Math.round(input.duration ?? DURATION.default)));+ const allowed = o.durations;+ params.duration = allowed?.length ? nearest(allowed, want) : want;+ if (params.duration !== want) notes.push(`${model.name} makes ${params.duration}s clips — use Extend for longer scenes`);+ if (o.audio === true) params.generateAudio = input.audio !== false;+ }+ params.numOutputs = Math.max(BATCH.min, Math.min(BATCH.max, Math.round(input.batch ?? 1)));+ return params;+}++function pickModel(kind: CinemaMode, input: CinemaGenerateInput, ctx: CinemaContext, notes: string[]): ModelDef {+ const list = CINEMA_MODELS[kind][input.engine];+ const fallback = kind === "video" && input.engine === "cloud" ? (ctx.higgsfield ? "cinema-studio-4" : "seedance-2-5") : list[0];+ let id = input.modelId && list.includes(input.modelId) ? input.modelId : fallback;+ if (HIGGSFIELD_ONLY.has(id) && !ctx.higgsfield) {+ const instead = kind === "video" ? "seedance-2-5" : "nano-banana-pro";+ if (input.modelId === id) notes.push(`${getModel(id)?.name ?? id} needs a Higgsfield key — ${getModel(instead)?.name} runs it with the Director in the prompt`);+ id = instead;+ }+ return getModel(id) ?? getModel(fallback)!;+}++function stepCost(req: GenerationRequest, jobsOf: Record<string, number>, step: CinemaStep): { cost: number | null; jobs: number; outputs: number } {+ const p = planGeneration(withPlaceholders({ ...step, request: req }), getModel, getPreset);+ const waits = !!step.after?.length;+ const jobs = waits ? 1 : p.jobs;+ let cost = estimateCost(p.model, p.params, jobs);+ // Cinema Studio 4.0 is token-metered: 480p costs less per second than the 720p list price.+ if (cost !== null && p.model.id === "cinema-studio-4" && p.params.resolution === "480p") cost = Math.round(cost * (0.2057 / 0.4623) * 1000) / 1000;+ const times = step.perJobOf ? (jobsOf[step.perJobOf] ?? 1) : 1;+ return { cost: cost === null ? null : cost * times, jobs: jobs * times, outputs: jobs * times * p.perJobOutputs };+}++function finish(model: ModelDef, steps: CinemaStep[], notes: string[], blocker?: string, outputsOf = "main"): CinemaPlan {+ let total = 0;+ let known = true;+ let outputs = 0;+ let first: string | undefined = blocker;+ const jobsOf: Record<string, number> = {};+ if (!blocker) {+ for (const s of steps) {+ try {+ const c = stepCost(s.request, jobsOf, s);+ jobsOf[s.key] = c.jobs;+ if (c.cost === null) known = false;+ else total += c.cost;+ if (s.key === outputsOf) outputs = c.outputs;+ } catch (e) {+ first ??= (e as Error).message;+ }+ }+ }+ return { model, steps, notes, blocker: first, costUsd: known ? Math.round(total * 1000) / 1000 : null, outputs };+}++const feature = (action: CinemaAction, mode: CinemaMode) =>+ action === "grid" ? "cinema-grid" : action === "cast" ? "cinema-cast" : action === "location" || action === "location-view" ? "cinema-location" : mode === "image" ? "cinema-image" : "cinema";++/** Prefix the project brief (cast and location prompts are built without the Director). */+function withBrief(brief: string | undefined, prompt: string): string {+ const b = briefWords(brief);+ return b ? `${tidy(b)}. ${prompt}` : prompt;+}++function planVideo(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ let model = pickModel("video", input, ctx, notes);+ const open = input.engine === "open";+ const moves = (input.moves ?? []).filter((m) => moveBySlug(m));+ let images = [...(input.images ?? [])];+ let trigger: string | undefined;+ let loras: LoraRef[] | undefined;+ let cameraMotion: string | undefined;+ if (open && moves.length) {+ const cam = openCameraRoute(moves[0], images.length > 0);+ const name = moveBySlug(moves[0])!.name;+ if (cam.via === "lora") {+ loras = cam.loras;+ trigger = cam.trigger;+ notes.push(`${name} adds the ${cam.loras!.map((l) => l.file.replace(/\.safetensors$/, "")).join(" + ")} camera LoRA`);+ } else if (cam.via === "fun-camera") {+ model = getModel("oss-wan22-fun-camera") ?? model;+ cameraMotion = cam.pose;+ notes.push(`${name} runs on Wan 2.2 Fun Camera (the “${cam.pose}” pose)`);+ } else {+ const better = !images.length && (moveBySlug(moves[0])!.funCamera || openCameraRoute(moves[0], true).via !== "prompt");+ notes.push(`${name} is written into the prompt${better ? " — add a start frame to drive it with a camera LoRA or Fun Camera" : ""}`);+ }+ }+ const native = model.id === "cinema-studio-4";+ const compiled = compileDirector({ prompt: input.prompt, settings: input.settings, moves, brief: input.brief, mode: "video", target: native ? "native" : "prompt" });+ let prompt = trigger ? `${trigger}. ${compiled.prompt}` : compiled.prompt;+ const params = fitParams(model, input, notes, "video");+ const extra: Record<string, unknown> = { ...compiled.extra, ...(cameraMotion ? { cameraMotion } : {}) };+ if (Object.keys(extra).length) params.extra = extra;++ const ms = input.multiShot;+ const shots = (ms?.shots ?? []).filter((s) => s.prompt.trim());+ if (ms?.mode === "auto") {+ if (model.options.multiShot?.mode === "prompt") params.multiShot = "auto";+ else if (native) notes.push("Cinema Studio 4.0 cuts by Tempo — pick Chaotic, Dynamic or Calm in Film setup");+ else notes.push(`${model.name} can't plan its own cuts — switch Multi-shot to Manual and write the shots`);+ } else if (ms?.mode === "manual" && shots.length) {+ const concat = model.options.multiShot?.mode === "concat";+ const fitted = concat && model.options.durations?.length ? shots.map((s) => ({ ...s, duration: nearest(model.options.durations!, s.duration) })) : shots;+ if (model.options.multiShot) params.shots = fitted;+ else {+ // Cinema Studio 4.0 and Veo have no shot list: the shots go into one prompt.+ const total = Math.min(DURATION.max, fitted.reduce((n, s) => n + s.duration, 0));+ prompt = composeShots(prompt, fitted);+ if (model.options.durations?.length) params.duration = nearest(model.options.durations, total);+ notes.push(`The ${fitted.length} shots are written into one ${params.duration}s prompt`);+ }+ }++ const max = open ? 1 : (model.options.maxImages ?? 1);+ if (images.length > max) {+ notes.push(max === 1 ? `${model.name} uses the first image as the start frame` : `${model.name} takes up to ${max} reference images`);+ images = images.slice(0, max);+ }+ if ((input.videos?.length || input.audios?.length) && input.action === "generate")+ notes.push(`${model.name} reads image references; video and audio references are used by Extend and Edit`);++ const blocker = !input.prompt.trim() && !images.length ? "Describe your scene first" : undefined;+ const steps: CinemaStep[] = [+ { key: "main", request: { feature: "cinema", modelId: model.id, prompt, inputs: images.length ? { images } : undefined, params, loras } },+ ];+ const hex = paletteHex(input.settings.palette);+ if (open && hex && input.settings.paletteLock !== false) {+ steps[0].request.step = { label: "Take", index: 0, of: 2 };+ steps.push({+ key: "palette",+ after: ["main"],+ perJobOf: "main",+ swatch: hex,+ request: {+ feature: "cinema",+ modelId: "oss-palette-video",+ op: "color-match",+ prompt: `Palette lock · ${paletteLabel(input.settings.palette)}`,+ inputs: { images: [SWATCH_PLACEHOLDER] },+ chain: [{ slot: "video" }],+ step: { label: `Palette · ${paletteLabel(input.settings.palette)}`, index: 1, of: 2 },+ },+ });+ notes.push(`The grade is locked to ${paletteLabel(input.settings.palette)} with a palette transfer`);+ }+ return finish(model, steps, notes, blocker);+}++function editModel(engine: Engine): ModelDef {+ return getModel(engine === "open" ? "oss-qwen-edit" : "nano-banana-pro")!;+}++function planStill(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ let model = pickModel("image", input, ctx, notes);+ const images = (input.images ?? []).slice(0, input.engine === "open" ? 3 : 10);+ if (images.length && !model.routes.some((r) => r.op === "edit")) {+ const instead = editModel(input.engine);+ notes.push(`Stills with references run on ${instead.name}`);+ model = instead;+ }+ const compiled = compileDirector({ prompt: input.prompt, settings: input.settings, brief: input.brief, mode: "image", target: "prompt" });+ const params = fitParams(model, { ...input, resolution: input.resolution ?? "1K" }, notes, "image");+ const blocker = stillCameraMissing(input.settings) ?? (!input.prompt.trim() ? "Describe your scene first" : undefined);+ const steps: CinemaStep[] = [+ { key: "main", request: { feature: "cinema-image", modelId: model.id, prompt: compiled.prompt, inputs: images.length ? { images } : undefined, params } },+ ];+ const hex = paletteHex(input.settings.palette);+ if (input.engine === "open" && hex && input.settings.paletteLock !== false) {+ steps[0].request.step = { label: "Still", index: 0, of: 2 };+ steps.push({+ key: "palette",+ after: ["main"],+ perJobOf: "main",+ swatch: hex,+ request: {+ feature: "cinema-image",+ modelId: "oss-palette-image",+ op: "color-match",+ prompt: `Palette lock · ${paletteLabel(input.settings.palette)}`,+ inputs: { images: [SWATCH_PLACEHOLDER] },+ chain: [{ slot: "images", position: "first" }],+ step: { label: `Palette · ${paletteLabel(input.settings.palette)}`, index: 1, of: 2 },+ },+ });+ }+ return finish(model, steps, notes, blocker);+}++function planGrid(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ const has = ctx.has ?? ((id: string) => !!getModel(id));+ const size = input.grid?.size ?? "2x2";+ const type = input.grid?.type ?? "freeform";+ const images = (input.images ?? []).slice(0, input.engine === "open" ? 3 : 10);+ let model: ModelDef;+ const extra: Record<string, unknown> = {};+ if (images.length) model = editModel(input.engine);+ else if (input.engine === "open" && has("oss-zimage-grid")) {+ model = getModel("oss-zimage-grid")!;+ const { rows, cols } = gridDims(size);+ Object.assign(extra, { rows, columns: cols });+ } else model = input.engine === "cloud" ? getModel("nano-banana-pro")! : pickModel("image", input, ctx, notes);+ const compiled = compileDirector({ prompt: input.prompt, settings: input.settings, brief: input.brief, mode: "image", target: "prompt" });+ const params = fitParams(model, { ...input, batch: 1, resolution: input.resolution ?? "2K" }, notes, "image");+ if (Object.keys(extra).length) params.extra = extra;+ const blocker = !input.prompt.trim() ? "Describe your scene first" : undefined;+ return finish(model, [{ key: "main", request: { feature: "cinema-grid", modelId: model.id, prompt: gridPrompt(compiled.prompt, size, type), inputs: images.length ? { images } : undefined, params } }], notes, blocker);+}++function planCast(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ const has = ctx.has ?? ((id: string) => !!getModel(id));+ const open = input.engine === "open";+ const id = open ? (has("oss-zimage-soul-cast") ? "oss-zimage-soul-cast" : "oss-z-image-turbo") : ctx.higgsfield ? "soul-2" : "nano-banana-pro";+ const model = getModel(input.modelId && CAST_MODELS[input.engine].includes(input.modelId) && (ctx.higgsfield || !HIGGSFIELD_ONLY.has(input.modelId)) ? input.modelId : id)!;+ const params = fitParams(model, { ...input, aspectRatio: "16:9", resolution: model.options.resolutions?.includes("2K") ? "2K" : model.options.resolutions?.includes("1080p") ? "1080p" : undefined }, notes, "image");+ const prompt = withBrief(input.brief, castPrompt(input.cast ?? {}, input.prompt));+ return finish(model, [{ key: "main", request: { feature: "cinema-cast", modelId: model.id, prompt, params } }], notes);+}++export const CAST_MODELS: Record<Engine, string[]> = { cloud: ["soul-2", "nano-banana-pro"], open: ["oss-zimage-soul-cast", "oss-z-image-turbo"] };+export const LOCATION_MODELS: Record<Engine, string[]> = { cloud: ["soul-cinema", "nano-banana-pro", "seedream-5-pro"], open: ["oss-z-image-turbo", "oss-qwen-image"] };++function planLocation(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ if (input.action === "location-view") {+ const model = editModel(input.engine);+ const src = input.source?.kind === "image" ? input.source.url : undefined;+ const prompt = withBrief(input.brief, locationViewPrompt(input.view ?? "reverse", input.prompt));+ return finish(model, [{ key: "main", request: { feature: "cinema-location", modelId: model.id, op: "edit", prompt, inputs: src ? { images: [src] } : undefined, params: { numOutputs: 1 } } }], notes, src ? undefined : "Pick the location image to re-angle");+ }+ const fallback = input.engine === "open" ? "oss-z-image-turbo" : ctx.higgsfield ? "soul-cinema" : "nano-banana-pro";+ const pick = input.modelId && LOCATION_MODELS[input.engine].includes(input.modelId) && (ctx.higgsfield || !HIGGSFIELD_ONLY.has(input.modelId)) ? input.modelId : fallback;+ const model = getModel(pick)!;+ const params = fitParams(model, { ...input, aspectRatio: "16:9", resolution: model.options.resolutions?.includes("2K") ? "2K" : model.options.resolutions?.includes("1080p") ? "1080p" : undefined }, notes, "image");+ const prompt = withBrief(input.brief, locationPrompt(input.prompt, input.settings));+ return finish(model, [{ key: "main", request: { feature: "cinema-location", modelId: model.id, prompt, params } }], notes, input.prompt.trim() ? undefined : "Describe your location first");+}++/** The video model an extend/prequel runs on: the picked one when it can, else Seedance 2.5 (Higgsfield's engine). */+function videoModelFor(op: Operation, input: CinemaGenerateInput, ctx: CinemaContext, notes: string[]): ModelDef {+ if (input.engine === "open") return getModel(op === "extend" ? "oss-wan22-vace-extend" : "oss-wan22-14b-fast")!;+ const picked = pickModel("video", input, ctx, []);+ if (picked.routes.some((r) => r.op === op)) return picked;+ const seedance = getModel("seedance-2-5")!;+ notes.push(`${picked.name} ${op === "extend" ? "extends" : "makes prequels"} through ${seedance.name}`);+ return seedance;+}++function planExtend(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ const src = input.source?.kind === "video" ? input.source : undefined;+ const settings = input.settings;+ const moves = input.moves ?? [];+ if (input.action === "extend-forward") {+ const model = videoModelFor("extend", input, ctx, notes);+ const scene = input.prompt.trim() || "Continue the shot naturally: the same characters, location and camera language, picking up exactly where it ends";+ const compiled = compileDirector({ prompt: scene, settings, moves, brief: input.brief, mode: "video", target: "prompt" });+ const params = fitParams(model, input, notes, "video");+ params.numOutputs = 1;+ return finish(+ model,+ [{ key: "main", request: { feature: "cinema", modelId: model.id, op: "extend", prompt: compiled.prompt, inputs: src ? { video: src.url } : undefined, params, step: { label: "Extended · sequel", index: 0, of: 1 } } }],+ notes,+ src ? undefined : "Select a video take to extend",+ );+ }+ // Backward (prequel): a still of the moment before, then a clip from it that ends on the take's first frame.+ const video = videoModelFor("flf2v", input, ctx, notes);+ const edit = editModel(input.engine);+ const frame = src?.firstFrame;+ const steps: CinemaStep[] = [];+ let blocker = src ? undefined : "Select a video take to extend";+ if (src && !frame) {+ if (ctx.cloudAllowed === false) blocker = "Couldn't read this take's first frame — open it in a browser that can play it, then try again";+ else+ steps.push({+ key: "frame",+ request: { feature: "cinema", modelId: "extract-frame", op: "frame", inputs: { video: src.url }, params: { extra: { frame_type: "first" } }, step: { label: "First frame", index: 0, of: 3 } },+ });+ }+ const scene = tidy(input.prompt) || "the moments right before this shot";+ const n = frame ? 2 : 3;+ steps.push({+ key: "before",+ after: frame ? undefined : ["frame"],+ request: {+ feature: "cinema",+ modelId: edit.id,+ op: "edit",+ prompt: `The same shot a few seconds earlier: ${scene}. Same characters, wardrobe, location, lighting, lens and colour grade; only time has moved back.`,+ inputs: frame ? { images: [frame] } : undefined,+ chain: frame ? undefined : [{ slot: "images", position: "first" }],+ params: { numOutputs: 1 },+ step: { label: "The moment before", index: n - 2, of: n },+ },+ });+ const compiled = compileDirector({ prompt: `Prequel: ${scene}. The clip ends exactly on the opening frame of the next shot`, settings, moves, brief: input.brief, mode: "video", target: "prompt" });+ const params = fitParams(video, input, notes, "video");+ params.numOutputs = 1;+ steps.push({+ key: "main",+ after: frame ? ["before"] : ["before", "frame"],+ request: {+ feature: "cinema",+ modelId: video.id,+ op: "flf2v",+ prompt: compiled.prompt,+ inputs: frame ? { endImage: frame } : undefined,+ chain: frame ? [{ slot: "images", position: "first" }] : [{ slot: "images", position: "first" }, { slot: "endImage" }],+ params,+ step: { label: "Extended · prequel", index: n - 1, of: n },+ },+ });+ return finish(video, steps, notes, blocker);+}++function planEdit(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const notes: string[] = [];+ const has = ctx.has ?? ((id: string) => !!getModel(id));+ const src = input.source?.kind === "video" ? input.source : undefined;+ const prompt = withBrief(input.brief, tidy(applyEmotions(input.prompt, input.settings.emotions)));+ let blocker = !src ? "Select a video take to edit" : !input.prompt.trim() ? "Describe the change" : undefined;+ if (input.engine === "cloud") {+ const model = getModel(ctx.higgsfield ? "seedance-2-5" : "kling-o3")!;+ const images = (input.images ?? []).slice(0, 4);+ return finish(+ model,+ [{ key: "main", request: { feature: "cinema", modelId: model.id, op: "v2v", prompt, inputs: src ? { video: src.url, ...(images.length ? { images } : {}) } : undefined, params: { numOutputs: 1 }, step: { label: "Edited take", index: 0, of: 1 } } }],+ notes,+ blocker,+ );+ }+ const restyle = has("oss-wan22-vace-restyle") ? getModel("oss-wan22-vace-restyle") : undefined;+ if (!restyle) return finish(editModel("open"), [], notes, blocker ?? "Open-source video edit needs the Wan 2.2 Fun VACE Restyle workflow — switch to Cloud for this one");+ if (src && !src.firstFrame) blocker ??= "Couldn't read this take's first frame — open it in a browser that can play it, then try again";+ const edit = editModel("open");+ return finish(+ restyle,+ [+ { key: "frame-edit", request: { feature: "cinema", modelId: edit.id, op: "edit", prompt, inputs: src?.firstFrame ? { images: [src.firstFrame] } : undefined, params: { numOutputs: 1 }, step: { label: "Edited first frame", index: 0, of: 2 } } },+ { key: "main", after: ["frame-edit"], request: { feature: "cinema", modelId: restyle.id, op: "v2v", prompt, inputs: src ? { video: src.url } : undefined, chain: [{ slot: "images", position: "first" }], step: { label: "Edited take", index: 1, of: 2 } } },+ ],+ notes,+ blocker,+ );+}++/** Everything a Generate press would run, priced, without running it (the browser shows it live). */+export function planCinema(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {+ const i = { ...input, settings: input.settings ?? {}, prompt: input.prompt ?? "" };+ switch (i.action) {+ case "grid":+ return planGrid(i, ctx);+ case "cast":+ return planCast(i, ctx);+ case "location":+ case "location-view":+ return planLocation(i, ctx);+ case "extend-forward":+ case "extend-backward":+ return planExtend(i, ctx);+ case "edit":+ return planEdit(i, ctx);+ default:+ return i.mode === "image" ? planStill(i, ctx) : planVideo(i, ctx);+ }+}++export { feature as cinemaFeature };diff --git a/tests/cinema.test.ts b/tests/cinema.test.tsnew file mode 100644index 00000000..6eedf361--- /dev/null+++ b/tests/cinema.test.ts@@ -0,0 +1,381 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { getModel } from "@/lib/catalog";+import {+ APERTURES,+ CAMERA_BODIES,+ CAMERA_MOVES,+ EMOTION_FAMILIES,+ ERAS,+ GENRES,+ LENSES,+ LIGHTING_PRESETS,+ LIGHT_DIRECTIONS,+ PALETTES,+ SOUL_CAST_FIELDS,+ TEMPOS,+ applyEmotions,+ castPrompt,+ checkReferences,+ compileDirector,+ gridPrompt,+ openCameraRoute,+ planCinema,+ randomizeCast,+ rigError,+ visibleCast,+ type CinemaGenerateInput,+ type DirectorSettings,+} from "@/lib/catalog/cinema";+import { buildPayload } from "@/lib/catalog/payload";+import { HARMONIES, harmonyPalette, hexToRgb, kmeans, paletteFromPixels, rgbToHsl, type RGB } from "@/components/cinema/color-math";+import { equalSpans, findCuts, lineStats, tileRects } from "@/components/cinema/grid-math";++const research = JSON.parse(fs.readFileSync(path.join(__dirname, "../docs/research/higgsfield-studios.json"), "utf8")).cinemaStudio;+const imageResearch = JSON.parse(fs.readFileSync(path.join(__dirname, "../docs/research/higgsfield-image-studios.json"), "utf8"));+const dp = research.directorsPanel;++describe("Cinema Studio data matches the research", () => {+ it("film setup, camera and lighting options", () => {+ const strip = (xs: { name: string; apiSlug?: string | null }[]) => xs.map((x) => [x.name, x.apiSlug ?? null]);+ expect(GENRES.map((g) => [g.name, g.slug])).toEqual(strip(dp.filmSetup.genre));+ expect(ERAS.map((g) => [g.name, g.slug])).toEqual(strip(dp.filmSetup.era));+ expect(TEMPOS.map((g) => [g.name, g.slug])).toEqual(strip(dp.filmSetup.tempo));+ expect(CAMERA_BODIES.map((g) => [g.name, g.slug])).toEqual(strip(dp.camera.camera));+ expect(LENSES.map((g) => [g.name, g.slug])).toEqual(strip(dp.camera.lens));+ expect(APERTURES.map((g) => [g.name, g.slug])).toEqual(strip(dp.camera.aperture));+ expect(LIGHTING_PRESETS.map((g) => [g.name, g.slug])).toEqual(strip(dp.lighting.presets));+ expect(GENRES[1].description).toBe(dp.filmSetup.genre[1].description);+ });++ it("all 33 camera moves, 50 palettes with 12 hex colours each, and the Emotion Wheel fragments", () => {+ expect(CAMERA_MOVES).toHaveLength(33);+ expect(CAMERA_MOVES.map((m) => m.slug)).toEqual(dp.camera.movements.map((m: { apiSlug: string }) => m.apiSlug));+ expect(PALETTES).toHaveLength(50);+ expect(PALETTES.map((p) => [p.slug, p.hex])).toEqual(dp.colorPalette.presets.map((p: { apiSlug: string; hexColors: string[] }) => [p.apiSlug, p.hexColors]));+ expect(PALETTES.every((p) => p.hex.length === 12)).toBe(true);+ expect(EMOTION_FAMILIES).toHaveLength(8);+ expect(EMOTION_FAMILIES.flatMap((f) => f.steps.map((s) => s.prompt))).toEqual(+ dp.emotionWheel.families.flatMap((f: { steps: { prompt: string }[] }) => f.steps.map((s) => s.prompt)),+ );+ expect(LIGHT_DIRECTIONS).toHaveLength(26);+ expect(new Set(LIGHT_DIRECTIONS).size).toBe(26);+ expect(LIGHT_DIRECTIONS).toContain("back-bottom-left");+ });++ it("every native value is one cinema-studio-4 accepts", () => {+ const cs4 = getModel("cinema-studio-4")!;+ const values = (param: string) => cs4.options.controls!.find((c) => c.param === param)!.values;+ expect(values("genre")).toEqual(expect.arrayContaining(GENRES.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("era")).toEqual(expect.arrayContaining(ERAS.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("pacing")).toEqual(expect.arrayContaining(TEMPOS.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("camera_model")).toEqual(expect.arrayContaining(CAMERA_BODIES.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("camera_lens")).toEqual(expect.arrayContaining(LENSES.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("camera_aperture")).toEqual(expect.arrayContaining(APERTURES.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("light")).toEqual(expect.arrayContaining(LIGHTING_PRESETS.flatMap((g) => (g.slug ? [g.slug] : []))));+ expect(values("camera_movement")).toEqual(CAMERA_MOVES.map((m) => m.slug));+ expect(values("color_palette")).toEqual(PALETTES.map((p) => p.slug));+ });++ it("the 17 Soul Cast fields with their options and defaults", () => {+ expect(SOUL_CAST_FIELDS).toHaveLength(17);+ const f = imageResearch.characterSheet.soulCast.fields as Record<string, (string | number)[]>;+ const byKey = Object.fromEntries(SOUL_CAST_FIELDS.map((x) => [x.key, x]));+ for (const [k, opts] of Object.entries(f)) {+ const key = k === "budget_millions" ? "budget" : k;+ expect(byKey[key], key).toBeDefined();+ expect(byKey[key].options.map((o) => String(o).toLowerCase()), key).toEqual(opts.map((o) => String(o).toLowerCase()));+ }+ expect(byKey.budget.default).toBe(250);+ expect(byKey.era.default).toBe(2020);+ });+});++const NOIR: DirectorSettings = {+ genre: "noir",+ era: "1980s",+ tempo: "calm",+ camera: "35mm-film",+ lens: "anamorphic",+ focal: "50mm",+ aperture: "f14-wide-open",+ lighting: { kind: "preset", slug: "window" },+ palette: { kind: "preset", slug: "neon-rain-at-midnight" },+ emotions: { maya: { family: "Sadness", step: 1 } },+};++describe("compileDirector", () => {+ it("sends Cinema Studio 4.0 its own fields and writes only the rest into the prompt", () => {+ const c = compileDirector({ prompt: "@maya waits at the bus stop in the rain", settings: NOIR, moves: ["dolly-in", "whip-pan"], brief: "A quiet neo-noir about loss.", mode: "video", target: "native" });+ expect(c.extra).toEqual({+ genre: "noir",+ era: "1980s",+ pacing: "calm",+ camera_model: "35mm-film",+ camera_lens: "anamorphic",+ camera_aperture: "f14-wide-open",+ camera_movement: "dolly-in",+ light: "window",+ color_palette: "neon-rain-at-midnight",+ });+ expect(c.prompt.startsWith("Project brief: A quiet neo-noir about loss. @maya (with sad emotion) waits at the bus stop in the rain.")).toBe(true);+ // Focal length has no API field; the second move goes into words, in order.+ expect(c.prompt).toContain("50mm focal length");+ expect(c.prompt).toMatch(/first .*dolly in.*finally .*whip pan/i);+ expect(c.prompt).not.toMatch(/noir film|1980s|anamorphic|window|#0c0c0e/i);+ });++ it("compiles everything into words for other models, Auto fields left out", () => {+ const c = compileDirector({ prompt: "@maya waits at the bus stop", settings: NOIR, moves: ["dolly-in"], mode: "video", target: "prompt" });+ expect(c.extra).toEqual({});+ expect(c.prompt).toContain("Noir film: hard shadow and high contrast");+ expect(c.prompt).toContain("Set in the 1980s");+ expect(c.prompt).toContain("Montage pacing: calm");+ expect(c.prompt).toMatch(/Shot on 35mm Film .*anamorphic lens.*50mm focal length.*f\/1\.4 aperture/);+ expect(c.prompt).toContain("Camera: the camera performs a smooth, steady dolly in");+ expect(c.prompt).toContain("Lighting: window");+ expect(c.prompt).toContain('"Neon Rain at Midnight" palette #0c0c0e, #334d4e');+ const bare = compileDirector({ prompt: "A lighthouse at dawn", settings: {}, mode: "video", target: "prompt" });+ expect(bare.prompt).toBe("A lighthouse at dawn.");+ });++ it("stills skip tempo and moves; custom palettes and light rigs are always words", () => {+ const c = compileDirector({+ prompt: "a diner at night",+ settings: { ...NOIR, palette: { kind: "custom", name: "Mine", hex: ["#101010", "#ff8800"] }, lighting: { kind: "custom", lights: [{ direction: "front-top-left", color: "#ffaa55", brightness: 80, diffuse: 70 }] } },+ moves: ["whip-pan"],+ mode: "image",+ target: "native",+ });+ expect(c.extra.pacing).toBeUndefined();+ expect(c.extra.camera_movement).toBeUndefined();+ expect(c.extra.color_palette).toBeUndefined();+ expect(c.extra.light).toBeUndefined();+ expect(c.prompt).toContain("palette #101010, #ff8800");+ expect(c.prompt).toContain("key light from the front top left");+ expect(c.prompt).toContain("80% brightness, soft and diffuse");+ });++ it("puts the emotion fragment after the first mention only, once", () => {+ const e = { kai: { family: "Anger", step: 2 } };+ expect(applyEmotions("@Kai turns. @kai shouts", e)).toBe("@Kai (with extremely enraged emotions loudly) turns. @kai shouts");+ expect(applyEmotions("@Kai (with extremely enraged emotions loudly) turns", e)).toBe("@Kai (with extremely enraged emotions loudly) turns");+ expect(applyEmotions("@kaiser turns", e)).toBe("@kaiser turns");+ });++ it("validates the custom rig and references with Higgsfield's messages", () => {+ const l = { direction: "front", color: "#ffffff", brightness: 50, diffuse: 50 };+ expect(rigError([l, l, l])).toBe("A custom rig supports at most 2 light sources");+ expect(rigError([{ ...l, color: "white" }])).toBe("color must be a #RRGGBB hex value");+ expect(rigError([{ ...l, brightness: 101 }])).toBe("brightness must be an integer between 0 and 100");+ expect(rigError([l])).toBeNull();+ expect(checkReferences({ images: 31, videos: [], audios: [], elements: 0 })).toBe("You can add a maximum of 30 images");+ expect(checkReferences({ images: 2, videos: [12, 20], audios: [], elements: 0 })).toBe("The total video duration limit is 30 seconds");+ expect(checkReferences({ images: 2, videos: [1], audios: [], elements: 0 })).toMatch(/at least 2 seconds/);+ expect(checkReferences({ images: 30, videos: [5, 5, 5], audios: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5], elements: 8 })).toMatch(/50 input media/);+ expect(checkReferences({ images: 3, videos: [5], audios: [3], elements: 2 })).toBeNull();+ });+});++const base = (over: Partial<CinemaGenerateInput>): CinemaGenerateInput => ({+ engine: "cloud",+ mode: "video",+ action: "generate",+ prompt: "@maya waits at the bus stop in the rain",+ settings: NOIR,+ moves: ["dolly-in", "whip-pan"],+ duration: 10,+ resolution: "1080p",+ aspectRatio: "21:9",+ batch: 2,+ ...over,+});++describe("planCinema", () => {+ it("runs Cinema Studio 4.0 natively with a Higgsfield key, fitted to what the API takes", () => {+ const plan = planCinema(base({}), { higgsfield: true });+ expect(plan.model.id).toBe("cinema-studio-4");+ expect(plan.blocker).toBeUndefined();+ const req = plan.steps[0].request;+ expect(req.params).toMatchObject({ aspectRatio: "21:9", resolution: "720p", duration: 10, numOutputs: 2, generateAudio: true });+ expect(req.params!.extra).toMatchObject({ genre: "noir", camera_movement: "dolly-in", color_palette: "neon-rain-at-midnight" });+ expect(plan.notes.join(" ")).toMatch(/up to 720p/);+ // 2 takes × 10 s × $0.4623.+ expect(plan.costUsd).toBeCloseTo(9.246, 2);+ // The payload Higgsfield receives.+ const route = getModel("cinema-studio-4")!.routes.find((r) => r.op === "t2v")!;+ const payload = buildPayload(route.map!, { ...req.params, prompt: req.prompt });+ expect(payload).toMatchObject({ aspect_ratio: "21:9", resolution: "720p", duration: 10, genre: "noir", era: "1980s", pacing: "calm", light: "window", camera_movement: "dolly-in" });+ });++ it("falls back to Seedance 2.5 with the Director in the prompt without a Higgsfield key", () => {+ const plan = planCinema(base({ modelId: "cinema-studio-4" }), { higgsfield: false });+ expect(plan.model.id).toBe("seedance-2-5");+ expect(plan.notes[0]).toMatch(/needs a Higgsfield key/);+ const req = plan.steps[0].request;+ expect(req.params!.extra).toBeUndefined();+ expect(req.prompt).toContain("Noir film");+ expect(req.params!.duration).toBe(10);+ // Kling 3.0 and Veo 3.1 fit the duration to what they make.+ expect(planCinema(base({ modelId: "kling-3", duration: 30 }), { higgsfield: false }).steps[0].request.params!.duration).toBe(15);+ expect(planCinema(base({ modelId: "veo-3-1", duration: 30 }), { higgsfield: false }).steps[0].request.params!.duration).toBe(8);+ });++ it("open engine: Wan 2.2 Lightning, camera LoRA or Fun Camera, then a palette lock per take", () => {+ const plan = planCinema(base({ engine: "open", moves: ["arc-left"], images: ["/api/files/a.png", "/api/files/b.png"] }), { higgsfield: false });+ expect(plan.model.id).toBe("oss-wan22-14b-fast");+ expect(plan.steps[0].request.loras?.length).toBeGreaterThan(0);+ expect(plan.steps[0].request.prompt).toMatch(/^orbit 360\. /);+ expect(plan.steps[0].request.inputs).toEqual({ images: ["/api/files/a.png"] });+ // Without a start frame the move is camera language in the prompt.+ const t2v = planCinema(base({ engine: "open", moves: ["arc-left"] }), { higgsfield: false });+ expect(t2v.steps[0].request.loras).toBeUndefined();+ expect(t2v.notes.join(" ")).toMatch(/add a start frame/);+ expect(plan.steps[0].request.params!.duration).toBe(5);+ expect(plan.steps[1]).toMatchObject({ key: "palette", perJobOf: "main", after: ["main"] });+ expect(plan.steps[1].request).toMatchObject({ modelId: "oss-palette-video", op: "color-match", chain: [{ slot: "video" }] });+ expect(plan.steps[1].swatch).toEqual(PALETTES.find((p) => p.slug === "neon-rain-at-midnight")!.hex);+ expect(plan.costUsd).toBe(0);++ // A Fun Camera pose needs a start frame; without one the move goes into the prompt.+ expect(openCameraRoute("pan-left", true)).toMatchObject({ via: "fun-camera", pose: "Pan Left" });+ const withFrame = planCinema(base({ engine: "open", moves: ["pan-left"], images: ["/api/files/a.png"], settings: {} }), { higgsfield: false });+ expect(withFrame.model.id).toBe("oss-wan22-fun-camera");+ expect(withFrame.steps[0].request.params!.extra).toMatchObject({ cameraMotion: "Pan Left" });+ expect(withFrame.steps).toHaveLength(1);+ const noLock = planCinema(base({ engine: "open", settings: { ...NOIR, paletteLock: false } }), { higgsfield: false });+ expect(noLock.steps).toHaveLength(1);+ });++ it("multi-shot: Auto on Seedance, Manual into one prompt on Cinema Studio 4.0", () => {+ const auto = planCinema(base({ multiShot: { mode: "auto" } }), { higgsfield: false });+ expect(auto.steps[0].request.params!.multiShot).toBe("auto");+ const manual = planCinema(+ base({ multiShot: { mode: "manual", shots: [{ prompt: "wide of the street", duration: 4 }, { prompt: "close on @maya", duration: 6 }] } }),+ { higgsfield: true },+ );+ expect(manual.steps[0].request.prompt).toMatch(/Shot 1 \[0-4s\]: wide of the street\. Shot 2 \[4-10s\]: close on @maya/);+ expect(manual.steps[0].request.params!.duration).toBe(10);+ });++ it("image mode: stills need the camera; grids are one contact sheet", () => {+ const blocked = planCinema(base({ mode: "image", settings: { genre: "noir" } }), { higgsfield: false });+ expect(blocked.blocker).toMatch(/Camera settings are required/);+ const still = planCinema(base({ mode: "image", resolution: undefined }), { higgsfield: false });+ expect(still.blocker).toBeUndefined();+ expect(still.model.id).toBe("nano-banana-pro");+ expect(still.steps[0].request).toMatchObject({ feature: "cinema-image", params: { aspectRatio: "21:9", resolution: "1K", numOutputs: 2 } });+ const grid = planCinema(base({ mode: "image", action: "grid", grid: { size: "3x3", type: "zooms" } }), { higgsfield: false });+ expect(grid.steps[0].request.params!.numOutputs).toBe(1);+ expect(grid.steps[0].request.prompt).toMatch(/3×3 grid of 9 equally sized film stills/);+ expect(grid.steps[0].request.prompt).toMatch(/extreme wide shot/);+ expect(gridPrompt("x", "4x4", "next_shots")).toMatch(/4×4 grid of 16/);+ });++ it("extend forward / backward and edit on a selected take", () => {+ const source = { url: "/api/files/take.mp4", kind: "video" as const };+ const fwd = planCinema(base({ action: "extend-forward", source }), { higgsfield: true });+ expect(fwd.model.id).toBe("seedance-2-5");+ expect(fwd.steps[0].request).toMatchObject({ op: "extend", inputs: { video: source.url } });+ expect(planCinema(base({ engine: "open", action: "extend-forward", source }), { higgsfield: false }).model.id).toBe("oss-wan22-vace-extend");++ const back = planCinema(base({ action: "extend-backward", source }), { higgsfield: false });+ expect(back.steps.map((s) => s.key)).toEqual(["frame", "before", "main"]);+ expect(back.steps[0].request).toMatchObject({ modelId: "extract-frame", params: { extra: { frame_type: "first" } } });+ expect(back.steps[2]).toMatchObject({ after: ["before", "frame"], request: { op: "flf2v", chain: [{ slot: "images", position: "first" }, { slot: "endImage" }] } });+ const backOpen = planCinema(base({ engine: "open", action: "extend-backward", source: { ...source, firstFrame: "/api/files/f.png" } }), { higgsfield: false });+ expect(backOpen.steps.map((s) => s.request.modelId)).toEqual(["oss-qwen-edit", "oss-wan22-14b-fast"]);+ expect(backOpen.steps[1].request.inputs).toEqual({ endImage: "/api/files/f.png" });++ expect(planCinema(base({ action: "edit", source, prompt: "make it snow" }), { higgsfield: false }).steps[0].request).toMatchObject({ modelId: "kling-o3", op: "v2v" });+ expect(planCinema(base({ action: "edit", source, prompt: "make it snow" }), { higgsfield: true }).steps[0].request.modelId).toBe("seedance-2-5");+ expect(planCinema(base({ action: "edit", source: undefined }), { higgsfield: false }).blocker).toBe("Select a video take to edit");+ });++ it("Soul Cast and Soul Location prompts", () => {+ const values = { genre: "Western", budget: 150, era: 1880, archetype: "Rebel", gender: "Female", race: "Latino", age: 35, facial_hair: "Beard", imperfections: ["Freckles", "Facial scar"], outfit: "Workwear" };+ expect(visibleCast(values).facial_hair).toBeUndefined();+ const p = castPrompt(values);+ expect(p).toMatch(/western film with a \$150M budget/);+ expect(p).toMatch(/35-year-old latino woman, the rebel archetype/);+ expect(p).toMatch(/freckles, facial scar/);+ expect(p).toMatch(/Full-body front view, three-quarter view, side profile and back view/);+ const r = randomizeCast({}, () => 0.5);+ expect(Object.keys(r).sort()).toEqual(["age", "archetype", "era", "gender", "genre", "race"]);+ const cast = planCinema(base({ action: "cast", mode: "image", cast: values, prompt: "" }), { higgsfield: false });+ expect(cast.blocker).toBeUndefined();+ expect(cast.steps[0].request).toMatchObject({ feature: "cinema-cast", modelId: "nano-banana-pro", params: { aspectRatio: "16:9" } });+ expect(planCinema(base({ action: "cast", mode: "image", cast: values }), { higgsfield: true }).model.id).toBe("soul-2");+ const loc = planCinema(base({ action: "location", mode: "image", prompt: "an abandoned diner on Route 66", brief: "" }), { higgsfield: false });+ expect(loc.steps[0].request.prompt).toMatch(/^Establishing shot of a film location: an abandoned diner on Route 66\. An empty set with no people/);+ });+});++describe("grid crop math", () => {+ /** A white sheet with rows × cols grey noise panels at uneven positions. */+ function sheet(width: number, height: number, xs: [number, number][], ys: [number, number][]) {+ const data = new Uint8ClampedArray(width * height * 4).fill(255);+ let seed = 3;+ const noise = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) % 160) + 40;+ for (const [y0, y1] of ys)+ for (const [x0, x1] of xs)+ for (let y = y0; y < y1; y++)+ for (let x = x0; x < x1; x++) {+ const o = (y * width + x) * 4;+ data[o] = data[o + 1] = data[o + 2] = noise();+ }+ return data;+ }++ it("finds gutters a few pixels off the even split", () => {+ const xs: [number, number][] = [[4, 98], [106, 200], [208, 296]];+ const ys: [number, number][] = [[0, 61], [69, 120], [128, 180]];+ const data = sheet(300, 180, xs, ys);+ const x = lineStats(data, 300, 180, "x");+ const y = lineStats(data, 300, 180, "y");+ expect(findCuts(x, 3)).toEqual(xs);+ expect(findCuts(y, 3)).toEqual(ys);+ const { rects, detected } = tileRects(300, 180, 3, 3, { x, y });+ expect(detected).toBe(true);+ expect(rects).toHaveLength(9);+ expect(rects[4]).toEqual({ x: 106, y: 69, w: 94, h: 51, row: 1, col: 1 });+ });++ it("falls back to an equal split when there are no gutters", () => {+ const data = sheet(200, 100, [[0, 200]], [[0, 100]]);+ const x = lineStats(data, 200, 100, "x");+ expect(findCuts(x, 2)).toBeNull();+ const { rects, detected } = tileRects(200, 100, 2, 2, { x, y: lineStats(data, 200, 100, "y") });+ expect(detected).toBe(false);+ expect(rects.map((r) => [r.x, r.y, r.w, r.h])).toEqual([[0, 0, 100, 50], [100, 0, 100, 50], [0, 50, 100, 50], [100, 50, 100, 50]]);+ expect(equalSpans(10, 3)).toEqual([[0, 3], [3, 7], [7, 10]]);+ });+});++describe("palette editor colour math", () => {+ it("k-means finds the colours of an image, dark to light", () => {+ const px: RGB[] = [];+ for (let i = 0; i < 300; i++) px.push([10 + (i % 5), 12, 14], [200, 40 + (i % 7), 30], [240, 240, 235 - (i % 4)]);+ const c = kmeans(px, 3);+ expect(c).toHaveLength(3);+ expect(c[0].rgb[0]).toBeLessThan(20);+ expect(c[1].rgb[0]).toBeGreaterThan(190);+ expect(c[2].rgb[1]).toBeGreaterThan(230);+ expect(c.reduce((s, x) => s + x.share, 0)).toBeCloseTo(1);+ const pal = paletteFromPixels(px, 4);+ expect(pal).toHaveLength(4);+ expect(pal[3]).toBe(c[1].color);+ });++ it("harmonies place their hues at the research's angles", () => {+ expect(HARMONIES.map((h) => h.name)).toEqual(["Analogous", "Complementary", "Monochromatic", "Split complementary", "Triad", "Square"]);+ const tri = harmonyPalette("#d03030", "triad", 7);+ expect(tri).toHaveLength(7);+ expect(tri[6]).toBe("#d03030");+ const hues = tri.slice(0, 6).map((h) => Math.round(rgbToHsl(hexToRgb(h))[0] / 10) * 10);+ expect(new Set(hues.map((h) => h % 360))).toEqual(new Set([0, 120, 240]));+ const mono = harmonyPalette("#3060d0", "monochromatic", 5).map((h) => Math.round(rgbToHsl(hexToRgb(h))[0]));+ expect(Math.max(...mono) - Math.min(...mono)).toBeLessThan(6);+ });+});