Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Storyboard: One sheet draws every panel together on MOSS-Image, then shows each panel as a frame

Claude79a63f671ed9
diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsx
index 3a0c080a..132b4c6e 100644
--- a/src/components/storyboard-view.tsx
+++ b/src/components/storyboard-view.tsx
@@ -1,9 +1,10 @@
"use client";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { ArrowUp, Clapperboard, Film, ImagePlus, Loader2, Minus, Plus, Sparkles, Trash2, Wand2, X } from "lucide-react";
+import { ArrowUp, Clapperboard, Film, ImagePlus, LayoutGrid, Loader2, Minus, Plus, Sparkles, Trash2, Wand2, X } from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
+import { useRouter } from "next/navigation";
import { useMemo, useState, useSyncExternalStore } from "react";
import { nanoid } from "nanoid";
import { toast } from "sonner";
@@ -18,13 +19,25 @@ import { finishGaveUp, useSoulFinish } from "@/components/studio/soul-finish";
import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";
import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { Viewer } from "@/components/studio/viewer";
-import { useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsVisitor, useStatus } from "@/lib/api";
-import { MAX_FRAMES, STORYBOARD_ASPECTS, STORYBOARD_PARTNER_IDS, type StoryboardNextScene, type StoryboardPartner } from "@/lib/catalog/storyboard";
+import { useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsVisitor, useStatus, useViewer, uploadFile } from "@/lib/api";
+import {
+ MAX_FRAMES,
+ ONE_SHEET_GPU_TEST,
+ sheetCrop,
+ sheetPanelLimit,
+ sheetPanelStyle,
+ STORYBOARD_ASPECTS,
+ STORYBOARD_PARTNER_IDS,
+ type SheetFrames,
+ type StoryboardNextScene,
+ type StoryboardPartner,
+} from "@/lib/catalog/storyboard";
import { lookCard } from "@/lib/catalog/soul-cards";
import type { Engine, Generation } from "@/lib/catalog/types";
import { timeAgo } from "@/lib/format";
import { BOARD_TITLES_KEY, boardTitle, filmReady, rememberTitle } from "@/lib/storyboard-board";
import { cn } from "@/lib/utils";
+import { ratioValue } from "@/lib/format";
import { responseError, toastError } from "@/lib/refusals";
const ASPECTS: readonly string[] = STORYBOARD_ASPECTS;
@@ -142,6 +155,32 @@ function NextScenePill({ value, onChange }: { value?: StoryboardNextScene; onCha
);
}
+/** How the board is drawn: frame by frame (each from the last), or every panel together on one sheet. */
+function SheetPill({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }) {
+ const options = [
+ { v: false, label: "Frame by frame", title: "Each frame is made from the one before" },
+ { v: true, label: "One sheet", title: "Every panel drawn together on one page, then cut into frames" },
+ ];
+ return (
+ <div role="radiogroup" aria-label="How the board is drawn" className="flex flex-wrap gap-1 rounded-full bg-muted p-0.5">
+ {options.map((o) => (
+ <button
+ key={String(o.v)}
+ type="button"
+ role="radio"
+ aria-checked={value === o.v}
+ title={o.title}
+ onClick={() => onChange(o.v)}
+ className={cn("inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap text-muted-foreground transition", value === o.v && "bg-background text-foreground shadow-soft")}
+ >
+ {o.v && <LayoutGrid className="size-3.5" />}
+ {o.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
/** The film made from a board: the joined video big, its shots small underneath. */
function FilmStrip({ items, ratio, onOpen }: { items: Generation[]; ratio: number; onOpen: (g: Generation) => void }) {
const create = useCreateGeneration();
@@ -213,6 +252,84 @@ function FrameTile({ g, index, ratio, onOpen }: { g: Generation; index: number;
);
}
+/** A panel of a one-sheet board cut out of the sheet in the browser, stored as a picture of its own (its URL). */
+async function cropPanel(url: string, box: SheetFrames["panels"][number]["box"], name: string): Promise<string> {
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.src = url;
+ await img.decode();
+ const [x, y, w, h] = sheetCrop(box, img.naturalWidth, img.naturalHeight);
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ c.getContext("2d")!.drawImage(img, x, y, w, h, 0, 0, w, h);
+ const blob = await new Promise<Blob>((ok, fail) => c.toBlob((b) => (b ? ok(b) : fail(new Error("Couldn't cut the panel out"))), "image/png"));
+ return (await uploadFile(new File([blob], `${name}.png`, { type: "image/png" }))).url;
+}
+
+/** A one-sheet board: the page as it came out, then each panel shown from it as a frame (cut out when it is used). */
+function SheetPanels({ g, sheet, onOpen }: { g: Generation; sheet: SheetFrames; onOpen: (g: Generation) => void }) {
+ const create = useCreateGeneration();
+ const router = useRouter();
+ const [busy, setBusy] = useState<string | null>(null);
+ const o = g.status === "succeeded" ? g.outputs[0] : undefined;
+ const panelRatio = ratioValue(sheet.aspect, 16 / 9);
+ const sheetRatio = tileRatio(g);
+ const use = async (i: number, to: "video" | "edit") => {
+ if (!o) return;
+ const key = `${to}-${i}`;
+ setBusy(key);
+ try {
+ const url = await cropPanel(o.url, sheet.panels[i].box, `storyboard-panel-${i + 1}`);
+ router.push(to === "video" ? `/video?image=${encodeURIComponent(url)}&prompt=${encodeURIComponent(sheet.panels[i].scene)}` : `/edit?image=${encodeURIComponent(url)}`);
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setBusy(null);
+ }
+ };
+ if (!o) {
+ return (
+ <div className="max-w-xl">
+ {g.status === "failed" || g.status === "canceled" ? (
+ <FailedTile g={g} ratio={sheetRatio} onRetry={() => create.mutate(g.request, { onError: (e) => toastError(e) })} />
+ ) : (
+ <PendingTile g={g} ratio={sheetRatio} />
+ )}
+ </div>
+ );
+ }
+ const action = "pointer-events-auto inline-flex h-7 items-center gap-1 rounded-full bg-white/20 px-2.5 text-[12px] font-medium whitespace-nowrap text-white backdrop-blur hover:bg-white/30 disabled:opacity-60";
+ return (
+ <div className="space-y-3">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-[repeat(auto-fill,minmax(220px,1fr))]">
+ {sheet.panels.map((p, i) => (
+ <figure key={i} className="min-w-0 space-y-1.5">
+ <div className="group/tile relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: panelRatio }}>
+ <button
+ onClick={() => onOpen(g)}
+ className="block size-full cursor-zoom-in bg-no-repeat"
+ style={{ backgroundImage: `url("${o.url}")`, ...sheetPanelStyle(p.box) }}
+ aria-label={`Open the sheet at panel ${i + 1}`}
+ />
+ <span className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-end gap-1 bg-gradient-to-t from-black/60 to-transparent p-2 pt-8 transition-opacity group-focus-within/tile:opacity-100 sm:opacity-0 sm:group-hover/tile:opacity-100">
+ <button type="button" className={action} disabled={!!busy} onClick={() => void use(i, "video")}>
+ {busy === `video-${i}` ? <Loader2 className="size-3.5 animate-spin" /> : <Clapperboard className="size-3.5" />} Animate
+ </button>
+ <button type="button" className={action} disabled={!!busy} onClick={() => void use(i, "edit")}>
+ {busy === `edit-${i}` ? <Loader2 className="size-3.5 animate-spin" /> : <Wand2 className="size-3.5" />} Edit
+ </button>
+ </span>
+ <span className="pointer-events-none absolute top-2 left-2 grid size-6 place-items-center rounded-full bg-background/90 font-mono text-[11px] font-semibold shadow-soft">{i + 1}</span>
+ </div>
+ <figcaption className="line-clamp-2 px-0.5 text-[12px] leading-snug text-muted-foreground">{p.scene}</figcaption>
+ </figure>
+ ))}
+ </div>
+ </div>
+ );
+}
+
function Board({
frames,
film,
@@ -233,6 +350,7 @@ function Board({
// A look board's frames are graded (and cropped) here first: the film starts from them as they look.
const ready = filmReady(frames, finishGaveUp);
const ratio = tileRatio(first);
+ const sheet = first.request.frame?.sheet;
const makeFilm = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/storyboards/${first.batchId}/film`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
@@ -257,7 +375,10 @@ function Board({
<div className="min-w-0 flex-1 basis-60">
<h3 className="line-clamp-2 font-heading text-[19px] leading-snug">{boardTitle(frames, idea)}</h3>
<p className="text-[12px] text-muted-foreground">
- {frames.length} frames · {done === frames.length ? "done" : `${done}/${frames.length} ready`} · {modelName(first, names)} · {timeAgo(first.createdAt)}
+ {sheet
+ ? `${sheet.panels.length} panels on one sheet · ${done ? "done" : "on the way"}`
+ : `${frames.length} frames · ${done === frames.length ? "done" : `${done}/${frames.length} ready`}`}{" "}
+ · {modelName(first, names)} · {timeAgo(first.createdAt)}
</p>
</div>
<div className="flex shrink-0 items-center gap-1">
@@ -284,11 +405,15 @@ function Board({
</Button>
</div>
</header>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-[repeat(auto-fill,minmax(220px,1fr))]">
- {frames.map((g, i) => (
- <FrameTile key={g.id} g={g} index={i} ratio={ratio} onOpen={onOpen} />
- ))}
- </div>
+ {sheet ? (
+ <SheetPanels g={first} sheet={sheet} onOpen={onOpen} />
+ ) : (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-[repeat(auto-fill,minmax(220px,1fr))]">
+ {frames.map((g, i) => (
+ <FrameTile key={g.id} g={g} index={i} ratio={ratio} onOpen={onOpen} />
+ ))}
+ </div>
+ )}
{film.length > 0 && <FilmStrip items={film} ratio={ratio} onOpen={onOpen} />}
</section>
);
@@ -317,6 +442,11 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
const [partner, setPartner] = useState<StoryboardPartner | undefined>();
// Your GPU only: the next frames' model (Qwen-Image 2.1 unless the classic recipe is picked).
const [nextScene, setNextScene] = useState<StoryboardNextScene | undefined>();
+ // One sheet: every panel on one MOSS-Image page, offered up to the panels a GPU render showed (the owner's until then).
+ const owner = !!useViewer().data?.owner;
+ const sheetLimit = sheetPanelLimit(owner);
+ const [sheetPicked, setSheet] = useState(false);
+ const sheet = sheetPicked && sheetLimit > 0;
const [open, setOpen] = useState<Generation | null>(null);
const feed = useGenerations({ features: ["storyboard", "storyboard-film"], limit: 240 });
const titles = useBoardTitles();
@@ -347,16 +477,19 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
const boardNextScene = engine === "open" ? nextScene : undefined;
const lookName = look ? lookCard(look)?.name : undefined;
const filled = scenes.filter((s) => s.trim());
- const boardBody = {
- engine,
- ...(boardPartner && { partner: boardPartner }),
- ...(boardNextScene && { nextScene: boardNextScene }),
- ...(mode === "auto" ? { story, frames: count } : { scenes: filled }),
- references: refs.filter((r) => r.ref && !r.uploading).map((r) => r.ref),
- style: style || undefined,
- ...(look && { look, lookStrength }),
- aspectRatio: aspect,
- };
+ const sheetCount = Math.min(count, sheetLimit || MAX_FRAMES);
+ const boardBody = sheet
+ ? { engine, sheet: true, ...(mode === "auto" ? { story, frames: sheetCount } : { scenes: filled.slice(0, sheetLimit) }), references: [] as string[], style: style || undefined, aspectRatio: aspect }
+ : {
+ engine,
+ ...(boardPartner && { partner: boardPartner }),
+ ...(boardNextScene && { nextScene: boardNextScene }),
+ ...(mode === "auto" ? { story, frames: count } : { scenes: filled }),
+ references: refs.filter((r) => r.ref && !r.uploading).map((r) => r.ref),
+ style: style || undefined,
+ ...(look && { look, lookStrength }),
+ aspectRatio: aspect,
+ };
// The price before it runs: the words don't change it, so typing doesn't ask again.
const priceKey = useDebounced(JSON.stringify({ ...boardBody, story: undefined, scenes: mode === "auto" ? undefined : filled.map(() => "·") }), 300);
const estimate = useQuery({
@@ -378,7 +511,7 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
const res = await fetch("/api/storyboards", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ...boardBody, references: refs.filter((r) => r.ref).map((r) => r.ref) }),
+ body: JSON.stringify(sheet ? boardBody : { ...boardBody, references: refs.filter((r) => r.ref).map((r) => r.ref) }),
});
const body = await res.json();
if (!res.ok) throw responseError(res, body.error);
@@ -387,13 +520,13 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
onSuccess: (b) => {
const idea = mode === "auto" ? story : scenes.find((s) => s.trim());
if (b.batchId && idea?.trim()) saveTitle(b.batchId, idea);
- toast.success(`${b.scenes.length} frames on the way — each one builds on the last`);
+ toast.success(sheet ? `${b.scenes.length} panels on the way, drawn together on one sheet` : `${b.scenes.length} frames on the way — each one builds on the last`);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
onError: (e) => toastError(e),
});
- const ready = (mode === "auto" ? story.trim().length > 3 : scenes.some((s) => s.trim())) && !refs.some((r) => r.uploading);
+ const ready = (mode === "auto" ? story.trim().length > 3 : scenes.some((s) => s.trim())) && (sheet || !refs.some((r) => r.uploading));
const addRef = (f: File) => {
const id = nanoid(6);
void fileToSlot(f, (v) =>
@@ -469,7 +602,7 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
</button>
</div>
))}
- {scenes.length < MAX_FRAMES && (
+ {scenes.length < (sheet ? sheetLimit : MAX_FRAMES) && (
<button type="button" onClick={() => setScenes((xs) => [...xs, ""])} className="inline-flex items-center gap-1 px-1 text-[12px] font-medium text-brand-text hover:underline">
<Plus className="size-3" /> Add frame
</button>
@@ -484,7 +617,7 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
className="mt-2 h-9 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary"
/>
<div className="mt-3 flex flex-wrap items-center gap-2">
- {refs.map((r) => (
+ {!sheet && refs.map((r) => (
<div key={r.id} className="relative size-12 overflow-hidden rounded-lg border bg-muted">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={r.preview} alt="" className="size-full object-cover" />
@@ -499,24 +632,25 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
</button>
</div>
))}
- {refs.length < 4 && <MediaSlot label="Look ref" kind="image" value={null} onChange={(v) => v && setRefs((rs) => [...rs, { ...v, id: nanoid(6) }])} onFile={addRef} />}
+ {!sheet && refs.length < 4 && <MediaSlot label="Look ref" kind="image" value={null} onChange={(v) => v && setRefs((rs) => [...rs, { ...v, id: nanoid(6) }])} onFile={addRef} />}
{mode === "auto" && (
<div className="flex items-center gap-1 rounded-full bg-secondary px-1 py-0.5 text-[13px] font-medium">
<button type="button" onClick={() => setCount((c) => Math.max(2, c - 1))} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label="Fewer frames">
<Minus className="size-3.5" />
</button>
<span className="w-16 text-center whitespace-nowrap tabular-nums" aria-live="polite">
- {count} frames
+ {sheet ? `${sheetCount} panels` : `${count} frames`}
</span>
- <button type="button" onClick={() => setCount((c) => Math.min(MAX_FRAMES, c + 1))} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label="More frames">
+ <button type="button" onClick={() => setCount((c) => Math.min(sheet ? sheetLimit : MAX_FRAMES, c + 1))} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label="More frames">
<Plus className="size-3.5" />
</button>
</div>
)}
- <LookChip value={look} strength={lookStrength} onChange={(id) => setLook(id)} onStrength={setLookStrength} none="No look" />
+ {sheetLimit > 0 && <SheetPill value={sheet} onChange={setSheet} />}
+ {!sheet && <LookChip value={look} strength={lookStrength} onChange={(id) => setLook(id)} onStrength={setLookStrength} none="No look" />}
<RatioPill value={aspect} onChange={setAspect} />
- {engine === "cloud" && <PartnerPill value={partner} onChange={setPartner} names={modelNames} />}
- {engine === "open" && <NextScenePill value={nextScene} onChange={setNextScene} />}
+ {!sheet && engine === "cloud" && <PartnerPill value={partner} onChange={setPartner} names={modelNames} />}
+ {!sheet && engine === "open" && <NextScenePill value={nextScene} onChange={setNextScene} />}
<div className="ml-auto flex shrink-0 items-center gap-2">
<span className="text-right text-[12px] leading-tight tabular-nums text-muted-foreground" aria-live="polite">
{visitor ? (
@@ -526,7 +660,7 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
) : (
<>
<span className="block font-semibold text-foreground">{costText(est, engine as Engine)}</span>
- {est && `${est.frames} frame${est.frames === 1 ? "" : "s"}`}
+ {est && (sheet ? `${est.frames} panels · 1 sheet` : `${est.frames} frame${est.frames === 1 ? "" : "s"}`)}
</>
)}
</span>
@@ -542,7 +676,8 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s
? "Fuobe splits your story into frames."
: "Fuobe splits your story into frames."
: "One prompt per frame. References keep the cast consistent."}
- {lookName && ` Every frame gets the ${lookName} look's grade${aspect === "21:9" ? ", made at 16:9 and cropped to 21:9" : ""}.`}
+ {sheet && ` One sheet draws every panel at once on MOSS-Image, then cuts it into frames.${ONE_SHEET_GPU_TEST ? "" : " Not yet tested on a GPU (shown to you as the owner)."}`}
+ {!sheet && lookName && ` Every frame gets the ${lookName} look's grade${aspect === "21:9" ? ", made at 16:9 and cropped to 21:9" : ""}.`}
</p>
</div>
</div>
diff --git a/src/lib/catalog/storyboard.ts b/src/lib/catalog/storyboard.ts
index 3871488e..af9d701a 100644
--- a/src/lib/catalog/storyboard.ts
+++ b/src/lib/catalog/storyboard.ts
@@ -14,6 +14,7 @@
* (`nextScene`); in the cloud fal's hosted Qwen-Image-Edit 2509 with the 2509 LoRA (sent as a URL), as Qwen-Image 2.1 isn't
* hosted. Nano Banana Pro stays a separate choice in the cloud (`partner`), every frame on it as boards ran before.
*/
+import { LAYOUT_PARAM, type LayoutDraft } from "@/lib/layout-prompt";
import { loraEntry, loraRef } from "./loras";
import type { ChainSlot, Engine, GenerationRequest, LoraRef } from "./types";
@@ -183,3 +184,164 @@ export function planStoryboard(input: StoryboardPlanInput): FrameRequest[] {
};
});
}
+
+// ---------------------------------------------------------------------------
+// One sheet (research new-models-7.md §4.10): the whole board as one page on MOSS-Image, one layout box per panel with its
+// shot, then cropped into frames in the browser. Every panel is drawn in one pass, so the cast, wardrobe and light match.
+
+/** The model a one-sheet board is drawn on: MOSS-Image on your GPU, and the same model hosted on fal. */
+export const SHEET_MODELS: Record<Engine, string> = { open: "oss-moss-image", cloud: "moss-image" };
+
+/** Sheet shapes both MOSS-Image halves take (the open graph's and fal's aspect ratios). */
+export const SHEET_ASPECTS = ["1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "21:9", "5:4", "4:5"] as const;
+
+/** The gap between panels and around them, as a share of the sheet's height. */
+export const SHEET_GUTTER = 0.03;
+
+/**
+ * What a render on a GPU showed about one-sheet boards (how many panels still read as consistent frames). Until one is
+ * recorded the option is the owner's alone, said to be untested; once it is, everyone gets it up to that many panels.
+ */
+export interface SheetTest {
+ /** The day it was rendered (YYYY-MM-DD). */
+ date: string;
+ /** The card it ran on ("RTX 4090 24 GB"). */
+ gpu: string;
+ /** The most panels that still came out usable. */
+ maxPanels: number;
+}
+export const ONE_SHEET_GPU_TEST: SheetTest | null = null;
+
+/** How many panels a one-sheet board may have for this viewer: 0 hides the option. */
+export function sheetPanelLimit(owner: boolean, test: SheetTest | null = ONE_SHEET_GPU_TEST): number {
+ if (test) return Math.max(0, Math.min(MAX_FRAMES, test.maxPanels));
+ return owner ? MAX_FRAMES : 0;
+}
+
+/** A box on the sheet: [x0, y0, x1, y1] as 0-1 fractions, from its top-left corner (a layout box). */
+export type SheetBox = [number, number, number, number];
+
+export interface SheetGrid {
+ cols: number;
+ rows: number;
+ /** The sheet's aspect ratio, one of {@link SHEET_ASPECTS}. */
+ aspect: string;
+ /** Each panel's box, in reading order. */
+ boxes: SheetBox[];
+}
+
+const ratio = (a: string): number => {
+ const [w, h] = a.split(":").map(Number);
+ return w > 0 && h > 0 ? w / h : 1;
+};
+const r6 = (v: number) => Math.round(v * 1e6) / 1e6;
+
+/**
+ * The grid of n panels of `panelAspect` on a sheet: the columns, rows and sheet shape that give the panels the most of the
+ * sheet (so each is drawn as large as it can be), then the fewest empty cells. Panels sit in their cells at their own shape,
+ * gutters between them; a short last row is centred.
+ */
+export function sheetGrid(n: number, panelAspect: string, aspects: readonly string[] = SHEET_ASPECTS): SheetGrid {
+ const count = Math.max(1, Math.min(MAX_FRAMES, Math.floor(n)));
+ const a = ratio(panelAspect);
+ const g = SHEET_GUTTER;
+ let best: { cols: number; rows: number; aspect: string; pw: number; ph: number; s: number; score: number; empty: number } | undefined;
+ for (let cols = 1; cols <= count; cols++) {
+ const rows = Math.ceil(count / cols);
+ for (const aspect of aspects) {
+ const s = ratio(aspect);
+ // A sheet s wide and 1 high: each cell after the gutters, the panel at its shape inside it.
+ const cw = (s - g * (cols + 1)) / cols;
+ const ch = (1 - g * (rows + 1)) / rows;
+ if (cw <= 0 || ch <= 0) continue;
+ const pw = Math.min(cw, ch * a);
+ const ph = pw / a;
+ const score = r6((count * pw * ph) / s);
+ const empty = cols * rows - count;
+ if (!best || score > best.score || (score === best.score && empty < best.empty)) best = { cols, rows, aspect, pw, ph, s, score, empty };
+ }
+ }
+ const { cols, rows, aspect, pw, ph, s } = best!;
+ const cw = (s - g * (cols + 1)) / cols;
+ const ch = (1 - g * (rows + 1)) / rows;
+ const boxes: SheetBox[] = [];
+ for (let i = 0; i < count; i++) {
+ const row = Math.floor(i / cols);
+ const inRow = row === rows - 1 ? count - row * cols : cols;
+ const col = i % cols;
+ // A short last row moves right by half the cells it leaves empty.
+ const shift = ((cols - inRow) * (cw + g)) / 2;
+ const x0 = g + col * (cw + g) + (cw - pw) / 2 + shift;
+ const y0 = g + row * (ch + g) + (ch - ph) / 2;
+ boxes.push([r6(x0 / s), r6(y0), r6((x0 + pw) / s), r6(y0 + ph)]);
+ }
+ return { cols, rows, aspect, boxes };
+}
+
+/** A panel's crop of the sheet as it came out: [x, y, w, h] in whole pixels, inside the box (no gutter), on the image. */
+export function sheetCrop(box: SheetBox, width: number, height: number): [number, number, number, number] {
+ const x0 = Math.max(0, Math.ceil(r6(box[0] * width)));
+ const y0 = Math.max(0, Math.ceil(r6(box[1] * height)));
+ const x1 = Math.min(width, Math.floor(r6(box[2] * width)));
+ const y1 = Math.min(height, Math.floor(r6(box[3] * height)));
+ return [x0, y0, Math.max(1, x1 - x0), Math.max(1, y1 - y0)];
+}
+
+/** Every panel's crop of the sheet. */
+export const sheetCrops = (boxes: SheetBox[], width: number, height: number) => boxes.map((b) => sheetCrop(b, width, height));
+
+/**
+ * A panel shown from the sheet without cutting it out (a tile's background): the image scaled so the panel fills the tile,
+ * and moved so the panel is in view, as CSS background-size and background-position percentages.
+ */
+export function sheetPanelStyle(box: SheetBox): { backgroundSize: string; backgroundPosition: string } {
+ const w = box[2] - box[0];
+ const h = box[3] - box[1];
+ const pos = (start: number, span: number) => (span >= 1 ? 0 : r6((start / (1 - span)) * 100));
+ return { backgroundSize: `${r6(100 / w)}% ${r6(100 / h)}%`, backgroundPosition: `${pos(box[0], w)}% ${pos(box[1], h)}%` };
+}
+
+/** What a one-sheet board keeps on its one picture (request.frame.sheet): the panels, their shots and boxes. */
+export interface SheetFrames {
+ cols: number;
+ rows: number;
+ /** The shape of each panel ("16:9"). */
+ aspect: string;
+ panels: { scene: string; box: SheetBox }[];
+}
+
+const SHEET_META = ["storyboard", "film stills", "multi-panel sheet"];
+
+/** The sheet's whole-picture caption: one film, the same cast and light, gutters between panels. */
+export function sheetCaption(n: number, grid: Pick<SheetGrid, "cols" | "rows">, style?: string): string {
+ const look = style?.trim() ? ` Style: ${style.trim().replace(/[.\s]+$/, "")}.` : "";
+ return `A storyboard sheet of ${n} cinematic panels in a ${grid.cols} by ${grid.rows} grid, read left to right and top to bottom: consecutive shots of one film with the same characters, faces, wardrobe, props, location and lighting in every panel. Plain white gutters between the panels, no captions, numbers or borders drawn.${look}`;
+}
+
+/**
+ * A one-sheet board's single request: MOSS-Image with a multi-panel layout (one object box per panel with its shot), the
+ * sheet shaped so the panels are as large as they can be. The layout goes as params.extra.layout, which the plan compiles
+ * at the size the model renders and keeps from being rewritten; the panels go in request.frame.sheet for the crop.
+ */
+export function planOneSheet(input: Omit<StoryboardPlanInput, "partner" | "nextScene" | "look">): FrameRequest {
+ const scenes = input.scenes.map((s) => s.trim()).filter(Boolean).slice(0, MAX_FRAMES);
+ if (!scenes.length) throw new Error("Describe the story or write at least one scene");
+ if (input.references?.length) throw new Error("A one-sheet board is drawn from your words alone: remove the references, or make it frame by frame");
+ const panelAspect = input.aspectRatio && input.aspectRatio !== "auto" ? input.aspectRatio : "16:9";
+ const grid = sheetGrid(scenes.length, panelAspect);
+ const caption = sheetCaption(scenes.length, grid, input.style);
+ const draft: LayoutDraft = {
+ summary: { caption, meta: SHEET_META, canvas: "multi_panel" },
+ items: scenes.map((scene, i) => ({ label: "object", caption: `Panel ${i + 1}, ${scene.replace(/[.\s]+$/, "")}.`, box: grid.boxes[i] })),
+ aspect: grid.aspect,
+ };
+ const sheet: SheetFrames = { cols: grid.cols, rows: grid.rows, aspect: panelAspect, panels: scenes.map((scene, i) => ({ scene, box: grid.boxes[i] })) };
+ return {
+ feature: "storyboard",
+ modelId: SHEET_MODELS[input.engine],
+ prompt: caption,
+ params: { aspectRatio: grid.aspect, ...(input.resolution && { resolution: input.resolution }), numOutputs: 1, extra: { [LAYOUT_PARAM]: draft } },
+ frame: { scene: scenes[0], index: 0, of: 1, sheet },
+ ...(input.batchTitle && { batchTitle: input.batchTitle }),
+ };
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 3f425eff..a1d0a5f8 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1083,7 +1083,15 @@ export interface GenerationRequest {
* A storyboard frame. `look`: the board's Fuobe Soul look, whose grade and overlay every frame gets after it is made
* (as meta, like a Soul picture); `crop`: a look board asked for 21:9 is made at 16:9 and cropped after.
*/
- frame?: { scene: string; index: number; of: number; look?: string; crop?: "21:9" };
+ frame?: {
+ scene: string;
+ index: number;
+ of: number;
+ look?: string;
+ crop?: "21:9";
+ /** A one-sheet board (src/lib/catalog/storyboard.ts planOneSheet): every panel on this one picture, cropped in the browser. */
+ sheet?: { cols: number; rows: number; aspect: string; panels: { scene: string; box: [number, number, number, number] }[] };
+ };
/** Part of a multi-step job (a shot of a multi-shot film, a step of an extend): shown on its tile. */
step?: { label: string; index: number; of: number };
/**
diff --git a/src/server/storyboard.ts b/src/server/storyboard.ts
index eeb72161..580b5607 100644
--- a/src/server/storyboard.ts
+++ b/src/server/storyboard.ts
@@ -5,6 +5,7 @@ import {
heuristicScenes,
MAX_FRAMES,
parseScenes,
+ planOneSheet,
planStoryboard,
SPLIT_SYSTEM,
STORYBOARD_NEXT_SCENE_IDS,
@@ -39,6 +40,8 @@ export const StoryboardBodySchema = z.object({
lookStrength: z.number().min(0).max(1).optional(),
aspectRatio: z.string().max(10).optional(),
resolution: z.string().max(10).optional(),
+ /** One sheet: every panel drawn on one MOSS-Image page (a layout box per panel), cropped into frames in the browser. */
+ sheet: z.boolean().optional(),
});
export interface StoryboardRequest {
@@ -59,6 +62,8 @@ export interface StoryboardRequest {
lookStrength?: number;
aspectRatio?: string;
resolution?: string;
+ /** One sheet: the whole board as one MOSS-Image page, one panel per scene, cropped into frames in the browser. */
+ sheet?: boolean;
}
/** Split a story into scenes with the configured LLM, or a deterministic shot list offline. */
@@ -77,11 +82,23 @@ function boardLook(r: Pick<StoryboardRequest, "look" | "lookStrength">): Storybo
return { id: look.id, words: look.look, ...(r.lookStrength !== undefined && { strength: r.lookStrength }) };
}
+/**
+ * The board's requests: one sheet (one MOSS-Image page with every panel; no look, references or partner model), or a frame
+ * each, every later one made from the one before.
+ */
+function boardFrames(r: StoryboardRequest, scenes: string[], batchTitle?: string) {
+ if (r.sheet) {
+ if (r.look) throw new Error("A one-sheet board has no look: make it frame by frame to use one");
+ return [planOneSheet({ engine: r.engine, scenes, references: r.references, style: r.style, aspectRatio: r.aspectRatio, resolution: r.resolution, batchTitle })];
+ }
+ return planStoryboard({ engine: r.engine, partner: r.partner, nextScene: r.nextScene, scenes, references: r.references, style: r.style, look: boardLook(r), aspectRatio: r.aspectRatio, resolution: r.resolution, batchTitle });
+}
+
/** What a board costs before it runs: each frame's price (frame 1 alone, the rest as chained steps), and whether it would be a demo. */
export function estimateStoryboard(r: StoryboardRequest): { costUsd: number | null; demo: boolean; frames: number; models: string[] } {
const n = Math.max(1, Math.min(MAX_FRAMES, r.scenes?.filter((s) => s.trim()).length || r.frames || 4));
const scenes = Array.from({ length: n }, (_, i) => r.scenes?.[i]?.trim() || `scene ${i + 1}`);
- const frames = planStoryboard({ engine: r.engine, partner: r.partner, nextScene: r.nextScene, scenes, references: r.references, style: r.style, look: boardLook(r), aspectRatio: r.aspectRatio, resolution: r.resolution });
+ const frames = boardFrames(r, scenes);
let cost: number | null = 0;
let demo = false;
const models: string[] = [];
@@ -96,13 +113,12 @@ export function estimateStoryboard(r: StoryboardRequest): { costUsd: number | nu
export async function createStoryboard(r: StoryboardRequest): Promise<{ batchId: string; scenes: string[]; items: Generation[] }> {
const n = Math.max(1, Math.min(MAX_FRAMES, r.scenes?.length || r.frames || 4));
- const look = boardLook(r);
const scenes = r.scenes?.length ? r.scenes.slice(0, MAX_FRAMES).map((s) => s.trim()).filter(Boolean) : await splitStory(r.story ?? "", n);
if (!scenes.length) throw new Error("Describe the story or write at least one scene");
const batchId = nanoid(10);
// The board is named after the user's idea on every device (the Library's stack title too).
const batchTitle = storyboardName(r.scenes?.length ? undefined : r.story, scenes);
- const frames = planStoryboard({ engine: r.engine, partner: r.partner, nextScene: r.nextScene, scenes, references: r.references, style: r.style, look, aspectRatio: r.aspectRatio, resolution: r.resolution, batchTitle });
+ const frames = boardFrames(r, scenes, batchTitle);
const items: Generation[] = [];
let previous: string | undefined;
for (const request of frames) {