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.

Cinema Studio: plan "Create 3D scene" and recompositions on both engines

Claude1e59901c458e
diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.ts
index d22a4c9f..7216bfc5 100644
--- a/src/lib/catalog/cinema.ts
+++ b/src/lib/catalog/cinema.ts
@@ -1,3 +1,4 @@
+import { APERTURE, LENS, anglesNote, poseWords, recomposePrompt, type ScenePose } from "@/lib/scene3d";
import { getModel, getPreset } from "./index";
import { composeShots, estimateCost, planGeneration, routesFor } from "./plan";
import type { Engine, GenerationRequest, GenParams, LoraRef, ModelDef, Operation } from "./types";
@@ -147,6 +148,8 @@ export interface CinemaTakeInfo {
prompt: string;
moves?: string[];
grid?: { size: GridSize; type: GridType };
+ /** A recomposition: the camera of the captured view. */
+ camera?: { lens: number; aperture: number; pose: ScenePose };
}
/** A generation's membership in a project (and its folder = scene). */
@@ -181,7 +184,7 @@ export interface DirectorMessage {
}
export type CinemaMode = "video" | "image";
-export type CinemaAction = "generate" | "extend-forward" | "extend-backward" | "edit" | "grid" | "cast" | "location" | "location-view";
+export type CinemaAction = "generate" | "extend-forward" | "extend-backward" | "edit" | "grid" | "cast" | "location" | "location-view" | "scene" | "recompose";
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>;
@@ -213,6 +216,17 @@ export interface CinemaGenerateInput {
cast?: CastValues;
/** Soul Location: which extra view to render. */
view?: string;
+ /** "recompose": the view captured in the 3D scene (an uploaded PNG) and the camera it was taken with. */
+ capture?: SceneCapture;
+}
+
+export interface SceneCapture {
+ url: string;
+ /** mm on a full-frame body. */
+ lens: number;
+ /** f-number. */
+ aperture: number;
+ pose: ScenePose;
}
export interface CinemaContext {
@@ -1129,8 +1143,15 @@ function finish(model: ModelDef, steps: CinemaStep[], notes: string[], blocker?:
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";
+const FEATURES: Partial<Record<CinemaAction, string>> = {
+ grid: "cinema-grid",
+ cast: "cinema-cast",
+ location: "cinema-location",
+ "location-view": "cinema-location",
+ scene: "cinema-scene",
+ recompose: "cinema-recompose",
+};
+const feature = (action: CinemaAction, mode: CinemaMode) => FEATURES[action] ?? (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 {
@@ -1438,6 +1459,73 @@ function planEdit(input: CinemaGenerateInput, ctx: CinemaContext): CinemaPlan {
);
}
+// ---------------------------------------------------------------------------
+// 3D scene and recomposition (higgsfield-delta-4.md §4.4; paid-model-apis-4.md §8; comfyui-oss-4.md §i)
+
+/** What builds a still's 3D scene: MoGe 2's textured mesh on the open engine, a Marigold depth map on the cloud. */
+export const SCENE_MODELS: Record<Engine, string> = { cloud: "marigold-depth", open: "oss-scene-moge" };
+/** What re-renders a captured view. The first is the default. */
+export const RECOMPOSE_MODELS: Record<Engine, string[]> = { cloud: ["nano-banana-pro", "qwen-multiple-angles"], open: ["oss-qwen-edit"] };
+/** The open scene mesh skips every other pixel: about a quarter of the triangles, light enough for a phone. */
+export const SCENE_DECIMATION = 2;
+
+function planScene(input: CinemaGenerateInput): CinemaPlan {
+ const open = input.engine === "open";
+ const model = getModel(SCENE_MODELS[input.engine])!;
+ const src = input.source?.kind === "image" ? input.source.url : undefined;
+ const notes = [
+ open
+ ? "MoGe 2 turns the whole frame into a textured 3D mesh on your ComfyUI (about 40 s on a CPU)"
+ : "Marigold makes a depth map of the frame, and your browser turns it and the still into a 3D point cloud",
+ ];
+ const params: GenParams = { numOutputs: 1, ...(input.aspectRatio ? { aspectRatio: input.aspectRatio } : {}), ...(open ? { extra: { decimation: SCENE_DECIMATION } } : {}) };
+ return finish(
+ model,
+ [{ key: "main", request: { feature: "cinema-scene", modelId: model.id, op: "scene-3d", prompt: "", inputs: src ? { images: [src] } : undefined, params } }],
+ notes,
+ src ? undefined : "Pick a still to build the scene from",
+ );
+}
+
+/**
+ * Re-render a captured view. Nano Banana Pro (cloud) and Qwen-Image-Edit 2511 with the Multiple-Angles LoRA
+ * (open; its camera words lead the prompt) get the capture as image 1 and the still as image 2. Qwen Multiple
+ * Angles on the cloud re-shoots the still itself from the flown camera's angles instead.
+ */
+function planRecompose(input: CinemaGenerateInput): CinemaPlan {
+ const notes: string[] = [];
+ const open = input.engine === "open";
+ const list = RECOMPOSE_MODELS[input.engine];
+ const model = getModel(input.modelId && list.includes(input.modelId) ? input.modelId : list[0])!;
+ const src = input.source?.kind === "image" ? input.source.url : undefined;
+ const cap = input.capture;
+ const lens = cap?.lens ?? LENS.default;
+ const aperture = cap?.aperture ?? APERTURE.default;
+ const pose = cap?.pose ?? { horizontal: 0, vertical: 0, zoom: 5 };
+ const params = fitParams(model, { ...input, batch: 1, resolution: input.resolution ?? "1K" }, notes, "image");
+ let request: GenerationRequest;
+ if (model.id === "qwen-multiple-angles") {
+ params.extra = { horizontal_angle: pose.horizontal, vertical_angle: pose.vertical, zoom: pose.zoom };
+ request = { feature: "cinema-recompose", modelId: model.id, op: "edit", prompt: anglesNote(lens, aperture, input.prompt), inputs: src ? { images: [src] } : undefined, params };
+ notes.push(`${model.name} re-shoots the still from the angles you flew to (${Math.round(pose.horizontal)}° round, ${Math.round(pose.vertical)}° up, zoom ${pose.zoom}) — the capture itself isn't sent`);
+ } else {
+ const loras = open ? getPreset("app-angles")?.open?.loras : undefined;
+ const words = recomposePrompt(lens, aperture, input.prompt);
+ request = {
+ feature: "cinema-recompose",
+ modelId: model.id,
+ op: "edit",
+ prompt: open ? `<sks> ${poseWords(pose)}. ${words}` : words,
+ inputs: src && cap ? { images: [cap.url, src] } : undefined,
+ params,
+ ...(loras?.length ? { loras } : {}),
+ };
+ notes.push(`${model.name}${loras?.length ? " with the Multiple-Angles LoRA" : ""} re-renders your capture, with the still as the reference for every detail`);
+ }
+ const blocker = !src ? "Pick the scene's still" : !cap ? "Capture a view first" : undefined;
+ return finish(model, [{ key: "main", request }], 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 ?? "" };
@@ -1454,6 +1542,10 @@ export function planCinema(input: CinemaGenerateInput, ctx: CinemaContext): Cine
return planExtend(i, ctx);
case "edit":
return planEdit(i, ctx);
+ case "scene":
+ return planScene(i);
+ case "recompose":
+ return planRecompose(i);
default:
return i.mode === "image" ? planStill(i, ctx) : planVideo(i, ctx);
}
diff --git a/src/server/cinema-generate.ts b/src/server/cinema-generate.ts
index 6e5620cc..986b1644 100644
--- a/src/server/cinema-generate.ts
+++ b/src/server/cinema-generate.ts
@@ -136,6 +136,7 @@ export function generateInProject(projectId: string, input: CinemaRequest, folde
prompt: input.prompt.slice(0, 4000),
...(input.moves?.length ? { moves: input.moves } : {}),
...(input.action === "grid" && input.grid ? { grid: input.grid } : {}),
+ ...(input.action === "recompose" && input.capture ? { camera: { lens: input.capture.lens, aperture: input.capture.aperture, pose: input.capture.pose } } : {}),
};
const batchId = nanoid(10);
const made: Record<string, Generation[]> = {};
diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.ts
index dc916f92..5861fbae 100644
--- a/src/server/cinema-schemas.ts
+++ b/src/server/cinema-schemas.ts
@@ -1,5 +1,6 @@
import "server-only";
import { z } from "zod";
+import { APERTURE, LENS } from "@/lib/scene3d";
import { CinemaError } from "./cinema";
/** Request bodies of /api/cinema/** (zod drops unknown keys). */
@@ -78,7 +79,7 @@ export const GenerateBody = z.object({
input: z.object({
engine: z.enum(["cloud", "open"]),
mode: z.enum(["video", "image"]),
- action: z.enum(["generate", "extend-forward", "extend-backward", "edit", "grid", "cast", "location", "location-view"]).default("generate"),
+ action: z.enum(["generate", "extend-forward", "extend-backward", "edit", "grid", "cast", "location", "location-view", "scene", "recompose"]).default("generate"),
modelId: z.string().max(80).optional(),
prompt: z.string().max(60_000).default(""),
moves: z.array(z.string().max(40)).max(12).optional(),
@@ -96,6 +97,14 @@ export const GenerateBody = z.object({
grid: z.object({ size: z.enum(["2x2", "3x3", "4x4"]), type: z.enum(["freeform", "zooms", "shots", "next_shots", "prev_shots"]) }).optional(),
cast: z.record(z.string().max(40), z.union([z.string().max(300), z.number(), z.array(z.string().max(60)).max(10)])).optional(),
view: z.string().max(20).optional(),
+ capture: z
+ .object({
+ url: FileRef,
+ lens: z.number().min(LENS.min).max(LENS.max),
+ aperture: z.number().min(APERTURE.min).max(APERTURE.max),
+ pose: z.object({ horizontal: z.number().min(0).max(360), vertical: z.number().min(-30).max(90), zoom: z.number().min(0).max(10) }),
+ })
+ .optional(),
}),
});
diff --git a/tests/cinema-scene.test.ts b/tests/cinema-scene.test.ts
new file mode 100644
index 00000000..ecf11b19
--- /dev/null
+++ b/tests/cinema-scene.test.ts
@@ -0,0 +1,175 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type { CinemaGenerateInput } from "@/lib/catalog/cinema";
+
+/** Cinema Studio's 3D scene: "Create 3D scene" on a still, then Capture → recomposition, on both engines. */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-scene-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const cinema = await import("@/server/cinema");
+const { generateInProject } = await import("@/server/cinema-generate");
+const generateRoute = await import("@/app/api/cinema/projects/[id]/generate/route");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const { planCinema, RECOMPOSE_MODELS, SCENE_DECIMATION } = await import("@/lib/catalog/cinema");
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const STILL = "/api/files/uploads/still.png";
+const CAPTURE = "/api/files/uploads/capture.png";
+const ctx = { higgsfield: false, cloudAllowed: true };
+const base = { mode: "image" as const, prompt: "", settings: {}, aspectRatio: "16:9" };
+const scene = (engine: "cloud" | "open"): CinemaGenerateInput => ({ ...base, engine, action: "scene", source: { url: STILL, kind: "image" } });
+const capture = { url: CAPTURE, lens: 85, aperture: 1.4, pose: { horizontal: 45, vertical: 30, zoom: 7 } };
+const recompose = (engine: "cloud" | "open", over: Partial<CinemaGenerateInput> = {}): CinemaGenerateInput => ({
+ ...base,
+ engine,
+ action: "recompose",
+ source: { url: STILL, kind: "image" },
+ capture,
+ ...over,
+});
+
+describe("planning a 3D scene", () => {
+ it("cloud: one Marigold depth map of the still, priced before it runs", () => {
+ const plan = planCinema(scene("cloud"), ctx);
+ expect(plan.blocker).toBeUndefined();
+ expect(plan.model.id).toBe("marigold-depth");
+ expect(plan.steps).toHaveLength(1);
+ expect(plan.steps[0].request).toMatchObject({ feature: "cinema-scene", op: "scene-3d", inputs: { images: [STILL] }, params: { aspectRatio: "16:9", numOutputs: 1 } });
+ expect(plan.costUsd).toBe(0.03);
+ expect(plan.notes[0]).toMatch(/your browser turns it and the still into a 3D point cloud/);
+ });
+
+ it("open: one MoGe 2 mesh, thinned for phones, and free", () => {
+ const plan = planCinema(scene("open"), ctx);
+ expect(plan.model.id).toBe("oss-scene-moge");
+ expect(plan.steps[0].request.params?.extra).toEqual({ decimation: SCENE_DECIMATION });
+ expect(plan.costUsd).toBe(0);
+ expect(plan.outputs).toBe(1);
+ });
+
+ it("needs a still", () => {
+ expect(planCinema({ ...scene("cloud"), source: undefined }, ctx).blocker).toBe("Pick a still to build the scene from");
+ expect(planCinema({ ...scene("open"), source: { url: "/api/files/x.mp4", kind: "video" } }, ctx).blocker).toBe("Pick a still to build the scene from");
+ });
+});
+
+describe("planning a recomposition", () => {
+ it("cloud default: Nano Banana Pro gets the capture first and the still second, with the re-render prompt", () => {
+ const plan = planCinema(recompose("cloud", { prompt: "make it dusk" }), ctx);
+ expect(RECOMPOSE_MODELS.cloud[0]).toBe("nano-banana-pro");
+ expect(plan.model.id).toBe("nano-banana-pro");
+ const req = plan.steps[0].request;
+ expect(req).toMatchObject({ feature: "cinema-recompose", op: "edit", inputs: { images: [CAPTURE, STILL] }, params: { aspectRatio: "16:9", resolution: "1K", numOutputs: 1 } });
+ expect(req.prompt).toMatch(/^Re-render this exact camera view of the scene photorealistically\./);
+ expect(req.prompt).toContain("85 mm portrait telephoto lens at f/1.4");
+ expect(req.prompt).toMatch(/make it dusk\.$/);
+ expect(req.loras).toBeUndefined();
+ expect(plan.costUsd).toBe(0.15);
+ });
+
+ it("cloud Qwen Multiple Angles: the still and the flown angles, said in a note", () => {
+ const plan = planCinema(recompose("cloud", { modelId: "qwen-multiple-angles" }), ctx);
+ const req = plan.steps[0].request;
+ expect(req.inputs?.images).toEqual([STILL]);
+ expect(req.params?.extra).toEqual({ horizontal_angle: 45, vertical_angle: 30, zoom: 7 });
+ expect(req.prompt).toMatch(/^Keep the same subjects/);
+ expect(plan.notes.join(" ")).toMatch(/\(45° round, 30° up, zoom 7\) — the capture itself isn't sent/);
+ expect(plan.costUsd).toBe(0.035);
+ });
+
+ it("open: Qwen-Image-Edit 2511 with the Multiple-Angles LoRA and its camera words first, free", () => {
+ const plan = planCinema(recompose("open", { modelId: "nano-banana-pro" }), ctx);
+ expect(plan.model.id).toBe("oss-qwen-edit");
+ const req = plan.steps[0].request;
+ expect(req.inputs?.images).toEqual([CAPTURE, STILL]);
+ expect(req.loras?.[0].file).toBe("qwen-image-edit-2511-multiple-angles-lora.safetensors");
+ expect(req.prompt).toMatch(/^<sks> front-right quarter view elevated shot medium shot\. Re-render this exact camera view/);
+ expect(plan.costUsd).toBe(0);
+ });
+
+ it("waits for a capture", () => {
+ expect(planCinema(recompose("cloud", { capture: undefined }), ctx).blocker).toBe("Capture a view first");
+ expect(planCinema(recompose("open", { source: undefined }), ctx).blocker).toBe("Pick the scene's still");
+ });
+});
+
+const json = (body: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+const params = (id: string) => ({ params: Promise.resolve({ id }) });
+
+async function settle(id: string, ms = 30_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+/** A small grey PNG saved as an upload (the still, or a capture). */
+const upload = (name: string) => saveFile({ data: encodePng({ width: 32, height: 18, data: Buffer.alloc(32 * 18 * 4, 128) }), contentType: "image/png", name, source: "upload" }).url;
+
+describe("Cinema API: scene and recomposition in demo mode", () => {
+ it("builds a cloud scene as a depth map and an open one as a mesh, filed where asked", async () => {
+ const still = upload("still.png");
+ const scene = (engine: "cloud" | "open"): CinemaGenerateInput => ({ ...base, engine, action: "scene", source: { url: still, kind: "image" } });
+ const p = cinema.createProject({ name: "Scenes" });
+ const folder = cinema.createFolder(p.id, { name: "Rooftop" });
+ const res = await generateRoute.POST(json({ input: scene("cloud"), folderId: folder.id }), params(p.id));
+ expect(res.status).toBe(201);
+ const { items, plan } = await res.json();
+ expect(plan.modelId).toBe("marigold-depth");
+ const depth = await settle(items[0].id);
+ expect(depth.error).toBeNull();
+ expect(depth).toMatchObject({ status: "succeeded", kind: "image", feature: "cinema-scene", op: "scene-3d" });
+ expect(depth.outputs[0].meta?.role).toBe("depth");
+ const listed = cinema.listItems(p.id, { folderId: folder.id });
+ expect(listed.map((g) => g.id)).toEqual([depth.id]);
+ expect(listed[0].take).toMatchObject({ mode: "image", action: "scene" });
+
+ const open = generateInProject(p.id, scene("open"), folder.id);
+ const mesh = await settle(open.items[0].id);
+ expect(mesh.kind).toBe("model3d");
+ expect(mesh.outputs.map((o) => [o.kind, o.meta?.role])).toEqual([
+ ["model3d", "scene"],
+ ["image", "depth"],
+ ]);
+ }, 60_000);
+
+ it("re-renders a capture into a new take that remembers the camera", async () => {
+ const p = cinema.createProject({ name: "Recompose" });
+ const still = upload("still.png");
+ const shot = { ...capture, url: upload("capture.png") };
+ const res = await generateRoute.POST(json({ input: recompose("cloud", { prompt: "golden hour", source: { url: still, kind: "image" }, capture: shot }), folderId: null }), params(p.id));
+ expect(res.status).toBe(201);
+ const { items } = await res.json();
+ expect(items[0].request.inputs.images).toEqual([shot.url, still]);
+ const take = cinema.listItems(p.id).find((g) => g.id === items[0].id)!.take!;
+ expect(take).toMatchObject({ action: "recompose", prompt: "golden hour", camera: { lens: 85, aperture: 1.4, pose: capture.pose } });
+ expect((await settle(items[0].id)).status).toBe("succeeded");
+ }, 40_000);
+
+ it("refuses a capture outside the lens and aperture ranges, or not uploaded here", async () => {
+ const p = cinema.createProject({ name: "Bad capture" });
+ for (const bad of [{ ...capture, lens: 10 }, { ...capture, aperture: 22 }, { ...capture, url: "https://elsewhere.test/c.png" }, { ...capture, pose: { horizontal: 400, vertical: 0, zoom: 5 } }]) {
+ const res = await generateRoute.POST(json({ input: recompose("cloud", { capture: bad }) }), params(p.id));
+ expect(res.status).toBe(400);
+ }
+ const none = await generateRoute.POST(json({ input: recompose("cloud", { capture: undefined }) }), params(p.id));
+ expect(none.status).toBe(422);
+ expect((await none.json()).error).toBe("Capture a view first");
+ });
+});