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
Image to 3D: five modes (an image, several images, text, pick an object, splat) and Rig & animate
Claudead9d5aae6e64
diff --git a/src/app/(studio)/image-to-3d/page.tsx b/src/app/(studio)/image-to-3d/page.tsxindex 224ce284..b28f6f2c 100644--- a/src/app/(studio)/image-to-3d/page.tsx+++ b/src/app/(studio)/image-to-3d/page.tsx@@ -1,12 +1,60 @@+import fs from "node:fs/promises";+import path from "node:path";import type { Metadata } from "next";-import { Model3dStudio } from "@/components/model3d/model3d-studio";+import { Model3dStudio, type Model3dInfo } from "@/components/model3d/model3d-studio";+import { ALL_MODELS_3D, RIG_MODEL } from "@/lib/av/model3d";import { getModel } from "@/lib/catalog";-import { MODELS_3D } from "@/lib/av/model3d";+import type { Manifest } from "@/lib/comfy";+import { buildLicenceList, FLAG_LABEL } from "@/lib/licences";export const metadata: Metadata = { title: "Image to 3D" };-/** The page passes the 3D models' names, so the client doesn't load the catalog. */-export default function Page() {- const names = Object.fromEntries([...MODELS_3D.cloud, ...MODELS_3D.open].map((m) => [m.id, getModel(m.id)?.name ?? m.id]));- return <Model3dStudio names={names} />;+/** The open text-to-3D route draws its still with this workflow before TRELLIS.2 (src/server/chains.ts). */+const EXTRA_WORKFLOWS: Record<string, string[]> = { "oss-text-trellis2": ["z-image-turbo-t2i"] };++/** The licence the picker shows for each open model: its short name, its catches and the notices it needs. */+async function readLicences(): Promise<Record<string, NonNullable<Model3dInfo["licence"]>>> {+ "use cache";+ let workflows: Manifest["workflows"] = [];+ try {+ workflows = (JSON.parse(await fs.readFile(path.join(process.cwd(), "workflows", "comfyui", "manifest.json"), "utf8")) as Manifest).workflows;+ } catch {+ return {};+ }+ const models = ALL_MODELS_3D.flatMap((c) => {+ const m = getModel(c.id);+ return m?.engine === "open" ? [m] : [];+ });+ const list = buildLicenceList(+ models.map((m) => ({+ id: m.id,+ name: m.name,+ vendor: m.vendor,+ kind: m.kind,+ routes: [...m.routes.map((r) => ({ provider: r.provider, endpoint: r.endpoint })), ...(EXTRA_WORKFLOWS[m.id] ?? []).map((endpoint) => ({ provider: "comfyui" as const, endpoint }))],+ })),+ workflows.map((w) => ({ id: w.id, title: w.title, capability: w.capability, license: w.license })),+ );+ return Object.fromEntries(+ list.rows+ .filter((r) => r.inCatalog)+ .map((r) => [+ r.id,+ {+ // "MIT (TRELLIS.2 weights, …); the …" → "MIT"; a chain's licences joined.+ name: [...new Set(r.licences.map((l) => l.split(/[(;]/)[0].trim()))].join(" + "),+ flags: r.flags.map((f) => (f === "territory" && r.excludes ? `Not in ${r.excludes}` : FLAG_LABEL[f])),+ notices: r.notices,+ },+ ]),+ );+}++/** The page passes the 3D models' names and licences, so the client doesn't load the catalog. */+export default async function Page() {+ const licences = await readLicences();+ const info: Record<string, Model3dInfo> = Object.fromEntries(+ [...ALL_MODELS_3D.map((m) => m.id), RIG_MODEL].map((id) => [id, { name: getModel(id)?.name ?? id, ...(licences[id] && { licence: licences[id] }) }]),+ );+ return <Model3dStudio info={info} />;}diff --git a/src/components/model3d/hooks.ts b/src/components/model3d/hooks.tsnew file mode 100644index 00000000..3ce1fc30--- /dev/null+++ b/src/components/model3d/hooks.ts@@ -0,0 +1,52 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { useEffect, useState } from "react";+import type { GenerationRequest } from "@/lib/catalog/types";++/** What /api/generations?preview=1 says a request would run as (the parts the page shows). */+export interface RunPreview {+ costUsd: number | null;+ demo: boolean;+ providerId: string;+ modelName: string;+ engine: "cloud" | "open";+ notes?: string[];+}++/** The value once it has stopped changing for `ms` (typing doesn't price every key). */+function useSettled<T>(value: T, ms = 300): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++/** The price and route of a request before it runs (null: nothing to price yet). */+export function useRunPreview(req: GenerationRequest | null) {+ const body = useSettled(req ? JSON.stringify(req) : null);+ return useQuery({+ queryKey: ["model3d-preview", body],+ enabled: !!body,+ retry: false,+ staleTime: 30_000,+ queryFn: async () => {+ const res = await fetch("/api/generations?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: body! });+ const j = (await res.json().catch(() => ({}))) as RunPreview & { error?: string };+ if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ return j;+ },+ });+}++/** "≈ $0.38", "Free on your GPU", "Demo — no provider connected" (null: not known yet). */+export function priceLine(p: RunPreview | undefined): string | null {+ if (!p) return null;+ if (p.demo) return "Demo — no provider connected, nothing is charged";+ if (p.engine === "open" || p.costUsd === 0) return "Free — runs on your ComfyUI";+ if (p.costUsd === null) return "Billed by your provider";+ const usd = p.costUsd < 0.01 ? "<$0.01" : `$${p.costUsd < 1 ? p.costUsd.toFixed(3).replace(/0$/, "") : p.costUsd.toFixed(2)}`;+ return `≈ ${usd}, paid to ${p.providerId === "replicate" ? "Replicate" : "fal.ai"}`;+}diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsxnew file mode 100644index 00000000..cb56d350--- /dev/null+++ b/src/components/model3d/model-card.tsx@@ -0,0 +1,236 @@+"use client";++import { Box, Clapperboard, Download, PersonStanding, Sparkles, Video } from "lucide-react";+import Link from "next/link";+import { createElement, useEffect, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { uploadFile, useHydrated } from "@/lib/api";+import { animateSpinHref, animationName, model3dView, type Model3dView } from "@/lib/av/model3d";+import type { Generation } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";+import type { Model3dInfo } from "./model3d-studio";+import { RigDialog } from "./rig-dialog";+import { recordableType, recordTurntable } from "./turntable";++/** Downloads besides the main file, by the name the provider gave them. */+const FORMAT_LABEL: Record<string, string> = { rigged: "Rigged .glb", walking: "Walk .glb", running: "Run .glb", fbx: ".fbx", splat: "Splat" };+const formatLabel = (k: string) => FORMAT_LABEL[k] ?? `.${k}`;++/** What the viewer shows of a rig: the result itself, or one of Meshy's walk and run cycles. */+function rigClips(g: Generation, view: Model3dView): { key: string; label: string; url: string }[] {+ if (!view.rigged || !view.glb) return [];+ const animation = g.request.params?.animation;+ const main = view.animated ? (typeof animation === "number" ? animationName(animation) : "Animation") : "Rigged";+ return [+ { key: "main", label: main, url: view.glb },+ ...(["walking", "running"] as const).filter((k) => view.formats[k]).map((k) => ({ key: k, label: k === "walking" ? "Walk" : "Run", url: view.formats[k] })),+ ];+}++/**+ * A finished 3D model: the GLB in an orbitable viewer (playing its animation when it has one), or a splat as its+ * orbit video or preview with the file to download; the turntable, Animate the spin and Rig & animate.+ */+export function ModelCard({ g, info, cloudAllowed }: { g: Generation; info: Record<string, Model3dInfo>; cloudAllowed: boolean }) {+ const view = model3dView(g);+ const [viewer, setViewer] = useState<HTMLElement | null>(null);+ const [ready, setReady] = useState(false);+ const [failed, setFailed] = useState(false);+ const [recording, setRecording] = useState<number | null>(null);+ const [recorded, setRecorded] = useState<{ url: string; saved?: string } | null>(null);+ const [rigging, setRigging] = useState(false);+ const hydrated = useHydrated();+ const canRecord = hydrated && !!recordableType();+ useEffect(() => {+ if (!view.glb) return;+ let live = true;+ import("@google/model-viewer").then(+ () => live && setReady(true),+ () => live && setFailed(true),+ );+ return () => {+ live = false;+ };+ }, [view.glb]);+ // The recorded clip's blob URL lives until another recording replaces it (saving it doesn't change it).+ const recordedUrl = recorded?.url;+ useEffect(() => () => void (recordedUrl && URL.revokeObjectURL(recordedUrl)), [recordedUrl]);+ // The turntable that came with the model (TRELLIS.2, TripoSplat, demo) or the one recorded here, shown in place of the 3D view.+ const clip = view.turntable ?? recordedUrl;+ // A splat opens on its orbit video when it has one (the page doesn't draw splats).+ const [show, setShow] = useState<"3d" | "video">(view.splat && view.turntable ? "video" : "3d");+ const clips = rigClips(g, view);+ const [clipKey, setClipKey] = useState("main");+ const src = clips.find((c) => c.key === clipKey)?.url ?? view.glb;+ const record = async () => {+ if (!viewer) return;+ setRecording(0);+ try {+ const blob = await recordTurntable(viewer as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });+ const url = URL.createObjectURL(blob);+ setRecorded({ url });+ // Keep it in the Library (Uploads) so it can go on to Edit video.+ const asset = await uploadFile(new File([blob], `${g.modelName ?? "model"} turntable.webm`, { type: "video/webm" }));+ setRecorded({ url, saved: asset.url });+ toast.success("Turntable recorded — saved to your uploads");+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setRecording(null);+ }+ };+ const spin = view.rigged ? null : animateSpinHref(view, recorded?.saved);+ const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");+ const notices = info[g.modelId]?.licence?.notices ?? [];+ // A rigged result rigs its source model again with another animation.+ const rigSource = view.rigged ? (g.request.inputs?.model3d ?? view.glb) : view.glb;+ const splatPicture = view.splat && !(show === "video" && clip);+ return (+ <article className="overflow-hidden rounded-2xl border bg-background shadow-soft">+ <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]">+ {show === "video" && clip ? (+ <video src={clip} controls loop muted playsInline autoPlay preload="metadata" aria-label={`Turntable of the ${g.modelName ?? "3D"} model`} className="size-full bg-media object-contain" />+ ) : splatPicture ? (+ view.poster ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={view.poster} alt="The subject the splat was made from, cut out" className="size-full object-contain p-4" />+ ) : (+ <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">+ <div>+ <Box className="mx-auto mb-2 size-8" aria-hidden />+ Gaussian splat ready — download it below.+ </div>+ </div>+ )+ ) : failed ? (+ <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">Couldn't load the 3D viewer — download the .glb to open it.</div>+ ) : !ready || !src ? (+ <div className="grid size-full place-items-center text-muted-foreground">+ <Box className="size-8 animate-pulse" aria-hidden />+ </div>+ ) : (+ createElement("model-viewer", {+ key: src,+ ref: setViewer,+ src,+ poster: view.poster,+ alt: `3D model made with ${g.modelName ?? "a 3D model"}`,+ "camera-controls": "",+ // A character that moves plays its animation; a still model turns.+ ...(view.rigged ? { autoplay: "" } : { "auto-rotate": "" }),+ "shadow-intensity": "1",+ exposure: "1",+ "touch-action": "pan-y",+ "interaction-prompt": "none",+ style: { width: "100%", height: "100%", background: "transparent" },+ })+ )}+ {recording !== null && (+ <div className="absolute inset-x-3 bottom-3 rounded-full bg-background/90 px-3 py-1.5 text-[12px] font-medium shadow-soft" role="status">+ Recording the turntable… {Math.round(recording * 100)}%+ </div>+ )}+ {g.provider === "mock" && <span className="absolute top-3 left-3 rounded-full bg-highlight/40 px-2 py-0.5 text-[11px] font-medium">Demo</span>}+ {(clip || clips.length > 1) && recording === null && (+ <div role="radiogroup" aria-label="Show" className="absolute top-3 right-3 inline-flex max-w-[calc(100%-1.5rem)] flex-wrap justify-end rounded-full bg-background/85 p-0.5 shadow-soft backdrop-blur">+ {clips.length > 1+ ? clips.map((c) => (+ <button+ key={c.key}+ type="button"+ role="radio"+ aria-checked={show === "3d" && clipKey === c.key}+ onClick={() => {+ setShow("3d");+ setClipKey(c.key);+ }}+ className={cn("h-6 max-w-32 truncate rounded-full px-2.5 text-[11px] font-medium transition", show === "3d" && clipKey === c.key ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}+ >+ {c.label}+ </button>+ ))+ : (["3d", "video"] as const).map((v) => (+ <button+ key={v}+ type="button"+ role="radio"+ aria-checked={show === v}+ onClick={() => setShow(v)}+ className={cn("h-6 rounded-full px-2.5 text-[11px] font-medium transition", show === v ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}+ >+ {v === "3d" ? (view.splat ? "Preview" : "3D") : "Turntable"}+ </button>+ ))}+ </div>+ )}+ </div>+ <div className="space-y-2 p-3">+ <p className="truncate text-[13px] text-muted-foreground">+ {g.modelName}+ {g.prompt && !view.rigged ? ` · ${g.prompt}` : ""}+ </p>+ {view.splat && (+ <p className="text-[12px] text-muted-foreground">+ Fuobe doesn't draw splats yet: {clip ? "the turntable shows it turning" : "the picture is what the model saw"}. Open the .{view.splat.format} in a Gaussian-splat viewer (SuperSplat, for one) to look around it.+ </p>+ )}+ <div className="flex flex-wrap gap-1.5">+ {view.splat ? (+ <Button asChild variant="outline" size="sm" className="rounded-full">+ <a href={view.splat.url} download={`${name}.${view.splat.format}`}>+ <Download className="size-3.5" /> .{view.splat.format}+ </a>+ </Button>+ ) : (+ view.glb && (+ <Button asChild variant="outline" size="sm" className="rounded-full">+ <a href={view.glb} download={`${name}.glb`}>+ <Download className="size-3.5" /> .glb+ </a>+ </Button>+ )+ )}+ {Object.entries(view.formats)+ .filter(([k]) => k !== "glb")+ .slice(0, 4)+ .map(([k, url]) => (+ <Button key={k} asChild variant="ghost" size="sm" className="rounded-full">+ <a href={url} download>+ {formatLabel(k)}+ </a>+ </Button>+ ))}+ {clip ? (+ <Button asChild variant="outline" size="sm" className="rounded-full">+ <a href={clip} download={`${name} turntable.${view.turntable ? "mp4" : "webm"}`} aria-label="Download the turntable video">+ <Video className="size-3.5" /> Turntable+ </a>+ </Button>+ ) : (+ view.glb &&+ !view.rigged && (+ <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!ready || !canRecord || recording !== null}>+ <Clapperboard className="size-3.5" /> Record turntable+ </Button>+ )+ )}+ {rigSource && !view.splat && (+ <Button variant="outline" size="sm" className="rounded-full" onClick={() => setRigging(true)}>+ <PersonStanding className="size-3.5" /> {view.rigged ? "Another animation" : "Rig & animate"}+ </Button>+ )}+ {spin && (+ <Button asChild size="sm" className="rounded-full">+ <Link href={spin} prefetch={false}>+ <Sparkles className="size-3.5" /> Animate the spin+ </Link>+ </Button>+ )}+ </div>+ {notices.length > 0 && <p className="text-[11px] text-muted-foreground">{notices.join(" · ")}</p>}+ </div>+ {rigSource && rigging && <RigDialog glb={rigSource} open={rigging} onOpenChange={setRigging} cloudAllowed={cloudAllowed} />}+ </article>+ );+}diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsxindex f5ef3fbf..60f53b88 100644--- a/src/components/model3d/model3d-studio.tsx+++ b/src/components/model3d/model3d-studio.tsx@@ -1,91 +1,290 @@"use client";-import { Box, Clapperboard, Download, Loader2, Sparkles, Video } from "lucide-react";+import { Box, Loader2 } from "lucide-react";import Link from "next/link";import { useSearchParams } from "next/navigation";-import { createElement, Suspense, useCallback, useEffect, useState } from "react";+import { Suspense, useCallback, useEffect, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Skeleton } from "@/components/ui/skeleton";+import { Textarea } from "@/components/ui/textarea";import { FailedTile, PendingTile } from "@/components/studio/feed";-import type { SlotValue } from "@/components/studio/media-slot";+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { MediaDrop } from "@/components/av/media-drop";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";-import { uploadFile, useCreateGeneration, useEngine, useGenerations, useHydrated } from "@/lib/api";-import { animateSpinHref, model3dRequest, model3dView, MODEL3D_FEATURE, MODELS_3D } from "@/lib/av/model3d";-import type { Generation } from "@/lib/catalog/types";+import { useCreateGeneration, useEngine, useGenerations } from "@/lib/api";+import {+ MAX_3D_PROMPT,+ MODEL3D_FEATURE,+ MODEL3D_MODES,+ MODELS_3D,+ SIDE_LABELS,+ VIEW_SIDES,+ model3dBlocker,+ model3dFor,+ model3dRequest,+ modeOf,+ type Model3dInput,+ type Model3dMode,+ type ViewSide,+} from "@/lib/av/model3d";+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";import { cn } from "@/lib/utils";-import { recordableType, recordTurntable } from "./turntable";+import { priceLine, useRunPreview } from "./hooks";+import { ModelCard } from "./model-card";-/** A link's ?model= (from ⌘K) picks that model and its engine. Under its own Suspense: it reads the URL. */-function UrlModel({ onModel }: { onModel: (engine: "cloud" | "open", id: string) => void }) {- const id = useSearchParams().get("model");+/** A model's name and, for open models, the licence the picker shows (the page reads them from the catalog and the manifest). */+export interface Model3dInfo {+ name: string;+ licence?: { name: string; flags: string[]; notices: string[] };+}++/** What a mode's input looks like before anything is uploaded (the price is asked for with these). */+const PLACEHOLDER = "/api/files/placeholder.png";++const HINTS: Record<Model3dMode, string> = {+ image: "One clear photo → a textured 3D model (.glb) you can spin, download, rig and animate, record as a turntable and turn into a video.",+ multi: "Photos of the same object from 2–4 sides → one 3D model that's right all the way round.",+ text: "Describe one object → a textured 3D model of it.",+ objects: "Name something in a photo → just that object, rebuilt in 3D as it stands.",+ splat: "One photo → a Gaussian splat of the subject: soft, photo-real detail, the background left out.",+};++/** A link's ?model= (from ⌘K) picks that model, its mode and its engine; ?mode= picks a mode. Under its own Suspense: it reads the URL. */+function UrlModel({ onModel, onMode }: { onModel: (mode: Model3dMode, engine: Engine, id: string) => void; onMode: (mode: Model3dMode) => void }) {+ const params = useSearchParams();+ const id = params.get("model");+ const mode = params.get("mode");useEffect(() => {- const engine = (["cloud", "open"] as const).find((e) => MODELS_3D[e].some((m) => m.id === id));- if (id && engine) onModel(engine, id);- }, [id, onModel]);+ const found = id ? modeOf(id) : null;+ if (found && id) onModel(found.mode, found.engine, id);+ else if (MODEL3D_MODES.some((m) => m.id === mode)) onMode(mode as Model3dMode);+ }, [id, mode, onModel, onMode]);return null;}-/** Image to 3D / Product spin: a product photo → a .glb to spin and download, a turntable video, and on to a video. */-export function Model3dStudio({ names }: { names: Record<string, string> }) {- const [engine, setEngine] = useEngine();+/** The five modes as one row of pills (wrapping on a phone); arrow keys move between them. */+function ModePicker({ mode, onChange }: { mode: Model3dMode; onChange: (m: Model3dMode) => void }) {+ const refs = useRef<(HTMLButtonElement | null)[]>([]);+ const move = (from: number, by: number) => {+ const i = (from + by + MODEL3D_MODES.length) % MODEL3D_MODES.length;+ onChange(MODEL3D_MODES[i].id);+ refs.current[i]?.focus();+ };+ return (+ <div role="radiogroup" aria-label="Make a 3D model" className="mx-auto mt-6 flex max-w-full flex-wrap justify-center gap-1.5">+ {MODEL3D_MODES.map((m, i) => (+ <button+ key={m.id}+ ref={(el) => {+ refs.current[i] = el;+ }}+ type="button"+ role="radio"+ aria-checked={mode === m.id}+ tabIndex={mode === m.id ? 0 : -1}+ title={m.hint}+ onClick={() => onChange(m.id)}+ onKeyDown={(e) => {+ if (e.key === "ArrowRight" || e.key === "ArrowDown") {+ e.preventDefault();+ move(i, 1);+ } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {+ e.preventDefault();+ move(i, -1);+ }+ }}+ className={cn(+ "h-8 rounded-full border px-3.5 text-[13px] font-medium transition-colors",+ mode === m.id ? "border-foreground bg-foreground text-background" : "bg-background text-muted-foreground hover:border-border-strong hover:text-foreground",+ )}+ >+ {m.label}+ </button>+ ))}+ </div>+ );+}++/** Image to 3D: a photo, several photos, words, an object in a photo or a splat → a model to spin, download, rig and animate. */+export function Model3dStudio({ info }: { info: Record<string, Model3dInfo> }) {+ const [engine, setEngine, engineMode] = useEngine();const create = useCreateGeneration();const results = useGenerations({ features: [MODEL3D_FEATURE, "app:app-image-to-3d"], limit: 24 });+ const [mode, setMode] = useState<Model3dMode>("image");const [photo, setPhoto] = useState<SlotValue | null>(null);- const [picked, setPicked] = useState<Partial<Record<"cloud" | "open", string>>>({});- const modelId = picked[engine] ?? MODELS_3D[engine][0].id;+ const [views, setViews] = useState<Partial<Record<ViewSide, SlotValue | null>>>({});+ const [text, setText] = useState("");+ const [object, setObject] = useState("");+ const [picked, setPicked] = useState<Record<string, string>>({});const fromUrl = useCallback(- (e: "cloud" | "open", id: string) => {- setPicked((p) => ({ ...p, [e]: id }));+ (m: Model3dMode, e: Engine, id: string) => {+ setMode(m);+ setPicked((p) => ({ ...p, [`${m}:${e}`]: id }));setEngine(e);},[setEngine],);- const blocker = !photo ? "Add a product photo" : photo.uploading ? "Uploading…" : null;+ const choices = MODELS_3D[mode][engine];+ const modelId = model3dFor(mode, engine, picked[`${mode}:${engine}`]);+ const sides = Object.fromEntries(VIEW_SIDES.flatMap((s) => (views[s] ? [[s, views[s]!.ref]] : []))) as Partial<Record<ViewSide, string>>;+ const input: Model3dInput = { engine, mode, modelId: modelId ?? undefined, photo: photo?.ref, views: sides, prompt: mode === "text" ? text : mode === "objects" ? object : undefined };+ const uploading = !!photo?.uploading || VIEW_SIDES.some((s) => views[s]?.uploading);+ const blocker = model3dBlocker(input) ?? (uploading ? "Uploading…" : null);+ // The price before anything is attached: placeholders stand in for the files and the words.+ const priced: GenerationRequest | null = modelId+ ? model3dRequest({ ...input, photo: input.photo ?? PLACEHOLDER, views: { front: PLACEHOLDER, left: PLACEHOLDER, ...sides }, prompt: input.prompt?.trim() || "an object" })+ : null;+ const preview = useRunPreview(priced);+ const price = priceLine(preview.data);+ const cloudAllowed = engineMode !== "open";const go = () => {if (blocker) return void toast(blocker, { id: "3d-blocker" });- create.mutate(model3dRequest({ engine, photo: photo!.ref, modelId }), {- onSuccess: () => toast.success("Building your 3D model"),+ create.mutate(model3dRequest(input), {+ onSuccess: () => toast.success(mode === "splat" ? "Making your splat" : mode === "text" && engine === "open" ? "Drawing the object, then building it in 3D" : "Building your 3D model"),onError: (e) => toast.error((e as Error).message),});};- const items = results.data ?? [];+ const licence = modelId ? info[modelId]?.licence : undefined;+ const items = (results.data ?? []).filter((g) => g.feature !== "image-to-3d-step");+ const setSide = (s: ViewSide) => (v: SlotValue | null) => setViews((cur) => ({ ...cur, [s]: v }));return (<ToolShell title="Image to 3D"><Suspense fallback={null}>- <UrlModel onModel={fromUrl} />+ <UrlModel onModel={fromUrl} onMode={setMode} /></Suspense>- <ToolHero title="Your product, in 3D" subtitle="One clear photo → a textured 3D model (.glb) you can spin, download, record as a turntable and turn into a video." />- <div className="mx-auto mt-8 grid max-w-[880px] gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">- <MediaDrop kind="image" value={photo} onChange={setPhoto} title="Add a product photo" hint="One object, plain background, well lit" compact />- <Panel title="Model">- <div className="flex flex-col gap-1.5">- <Label htmlFor="m3d-model" className="sr-only">- Model+ <ToolHero title="Your product, in 3D" subtitle={HINTS[mode]} />+ <ModePicker mode={mode} onChange={setMode} />+ <div className="mx-auto mt-6 grid max-w-[880px] gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">+ {mode === "multi" ? (+ <Panel title="Photos of each side" aside={<span className="text-[12px] text-muted-foreground">{Object.keys(sides).length} of 4</span>}>+ <div className="grid grid-cols-4 gap-2">+ {VIEW_SIDES.map((s) => (+ <div key={s} className="flex flex-col items-center gap-1">+ <MediaSlot label={SIDE_LABELS[s]} kind="image" value={views[s] ?? null} onChange={setSide(s)} required={s === "front"} size="lg" caption />+ <span className="text-[11px] text-muted-foreground">{s === "front" ? "Needed" : "Optional"}</span>+ </div>+ ))}+ </div>+ <p className="mt-3 text-[12px] text-muted-foreground">+ The front and at least one more side. Same object, same distance and light in each; a plain background helps.+ {engine === "open" && " The open model puts each photo on the side you add it to."}+ </p>+ </Panel>+ ) : mode === "text" ? (+ <Panel title="Describe the object">+ <Label htmlFor="m3d-text" className="sr-only">+ Describe the object</Label>- <Select value={modelId} onValueChange={(v) => setPicked((p) => ({ ...p, [engine]: v }))}>- <SelectTrigger id="m3d-model" className="h-9 w-full rounded-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {MODELS_3D[engine].map((m) => (- <SelectItem key={m.id} value={m.id}>- {names[m.id] ?? m.id}- </SelectItem>- ))}- </SelectContent>- </Select>- <p className="text-[12px] text-muted-foreground">{MODELS_3D[engine].find((m) => m.id === modelId)?.note}</p>+ <Textarea+ id="m3d-text"+ value={text}+ onChange={(e) => setText(e.target.value.slice(0, MAX_3D_PROMPT))}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) go();+ }}+ placeholder="A brass ship's lantern with a glass globe and a carry ring"+ className="min-h-28 rounded-xl"+ />+ <p className="mt-2 text-[12px] text-muted-foreground">+ One object: what it is, its material and colours.{engine === "open" && " Z-Image Turbo draws it on a plain background first; that still is kept with the model."}+ </p>+ </Panel>+ ) : (+ <div className="grid min-w-0 gap-3">+ <MediaDrop+ kind="image"+ value={photo}+ onChange={setPhoto}+ title={mode === "objects" ? "Add a photo" : "Add a photo of the object"}+ hint={mode === "objects" ? "A room, a shelf, a street: anything with the object in it" : "One object, plain background, well lit"}+ compact+ />+ {mode === "objects" && (+ <Panel title="What to take out">+ <Label htmlFor="m3d-object" className="sr-only">+ What to take out+ </Label>+ <Input+ id="m3d-object"+ value={object}+ onChange={(e) => setObject(e.target.value.slice(0, 200))}+ onKeyDown={(e) => e.key === "Enter" && go()}+ placeholder="the green armchair"+ className="h-9 rounded-full"+ />+ <p className="mt-2 text-[12px] text-muted-foreground">Name one thing, or several separated by commas. It's rebuilt where it stands; the rest of the photo is left out.</p>+ </Panel>+ )}</div>- <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>- {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} Make it 3D- </Button>- <p className="mt-2 text-[12px] text-muted-foreground">- {engine === "open" ? "TRELLIS.2 also renders a turntable video on your GPU." : "Cloud models return the .glb; record a turntable right here in your browser."}- </p>+ )}+ <Panel title="Model">+ {!modelId ? (+ <div className="space-y-3 text-[13px]">+ <p className="text-muted-foreground">+ Pick an object runs on SAM 3D Objects, a cloud model; no open model rebuilds one named object yet. On the open engine, crop the photo to the object and use From an image: TRELLIS.2 cuts it out for you.+ </p>+ <div className="flex flex-wrap gap-1.5">+ {cloudAllowed && (+ <Button size="sm" className="rounded-full" onClick={() => setEngine("cloud")}>+ Use the cloud+ </Button>+ )}+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => setMode("image")}>+ From an image+ </Button>+ </div>+ </div>+ ) : (+ <>+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="m3d-model" className="sr-only">+ Model+ </Label>+ <Select value={modelId} onValueChange={(v) => setPicked((p) => ({ ...p, [`${mode}:${engine}`]: v }))}>+ <SelectTrigger id="m3d-model" className="h-9 w-full rounded-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {choices.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {info[m.id]?.name ?? m.id}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-[12px] text-muted-foreground">{choices.find((m) => m.id === modelId)?.note}</p>+ {licence && (+ <p className="text-[12px] text-muted-foreground">+ Licence: {[licence.name, ...licence.flags].join(" · ")}+ {licence.notices.length > 0 && <span className="font-medium text-foreground"> · {licence.notices.join(" · ")}</span>} ·{" "}+ <Link href="/settings/about" className="underline underline-offset-2" prefetch={false}>+ All licences+ </Link>+ </p>+ )}+ </div>+ <Button size="lg" className={cn("mt-4 w-full rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={create.isPending}>+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} {mode === "splat" ? "Make the splat" : "Make it 3D"}+ </Button>+ <p className="mt-2 text-[12px] text-muted-foreground" aria-live="polite">+ {blocker ? `${blocker} · ` : ""}+ {preview.isError ? (preview.error as Error).message : (price ?? "Working out the price…")}+ </p>+ <p className="mt-1 text-[12px] text-muted-foreground">+ {mode === "splat"+ ? engine === "open"+ ? "TripoSplat cuts the subject out and renders an orbit video of the splat on your GPU."+ : "TripoSplat cuts the subject out and returns a .ply splat to download."+ : engine === "open"+ ? "TRELLIS.2 also renders a turntable video on your GPU."+ : "Cloud models return the .glb; record a turntable right here in your browser."}+ </p>+ </>+ )}</Panel></div><section className="mx-auto mt-12 max-w-[880px]" aria-labelledby="models3d">@@ -102,7 +301,7 @@ export function Model3dStudio({ names }: { names: Record<string, string> }) {) : (<div className="grid gap-3 sm:grid-cols-2">{items.map((g) => (- <ResultCard key={g.id} g={g} />+ <ResultCard key={g.id} g={g} info={info} cloudAllowed={cloudAllowed} />))}</div>)}@@ -111,146 +310,18 @@ export function Model3dStudio({ names }: { names: Record<string, string> }) {);}-function ResultCard({ g }: { g: Generation }) {- const create = useCreateGeneration();- if (g.status === "queued" || g.status === "running") return <PendingTile g={g} ratio={4 / 3} />;- if (g.status !== "succeeded") return <FailedTile g={g} ratio={4 / 3} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />;- return <ModelCard g={g} />;+/** Retry runs the same request; a step of the open text-to-3D chain starts the chain again from the words. */+function retryOf(g: Generation): GenerationRequest {+ const r = g.request;+ if (r.chain?.length && r.op === "image-to-3d" && !r.inputs?.images?.length && r.prompt?.trim()) {+ return { feature: r.feature, modelId: "oss-text-trellis2", op: "text-to-3d", prompt: r.prompt, ...(r.params && { params: r.params }) };+ }+ return r;}-function ModelCard({ g }: { g: Generation }) {- const view = model3dView(g);- const [viewer, setViewer] = useState<HTMLElement | null>(null);- const [ready, setReady] = useState(false);- const [failed, setFailed] = useState(false);- const [recording, setRecording] = useState<number | null>(null);- const [recorded, setRecorded] = useState<{ url: string; saved?: string } | null>(null);- const hydrated = useHydrated();- const canRecord = hydrated && !!recordableType();- useEffect(() => {- let live = true;- import("@google/model-viewer").then(- () => live && setReady(true),- () => live && setFailed(true),- );- return () => {- live = false;- };- }, []);- // The recorded clip's blob URL lives until another recording replaces it (saving it doesn't change it).- const recordedUrl = recorded?.url;- useEffect(() => () => void (recordedUrl && URL.revokeObjectURL(recordedUrl)), [recordedUrl]);- // The turntable that came with the model (TRELLIS.2, demo) or the one recorded here, shown in place of the 3D view.- const clip = view.turntable ?? recordedUrl;- const [show, setShow] = useState<"3d" | "video">("3d");- const record = async () => {- if (!viewer) return;- setRecording(0);- try {- const blob = await recordTurntable(viewer as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });- const url = URL.createObjectURL(blob);- setRecorded({ url });- // Keep it in the Library (Uploads) so it can go on to Edit video.- const asset = await uploadFile(new File([blob], `${g.modelName ?? "model"} turntable.webm`, { type: "video/webm" }));- setRecorded({ url, saved: asset.url });- toast.success("Turntable recorded — saved to your uploads");- } catch (e) {- toast.error((e as Error).message);- } finally {- setRecording(null);- }- };- const spin = animateSpinHref(view, recorded?.saved);- const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");- return (- <article className="overflow-hidden rounded-2xl border bg-background shadow-soft">- <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]">- {show === "video" && clip ? (- <video src={clip} controls loop muted playsInline autoPlay preload="metadata" aria-label={`Turntable of the ${g.modelName ?? "3D"} model`} className="size-full bg-media object-contain" />- ) : failed ? (- <div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">Couldn't load the 3D viewer — download the .glb to open it.</div>- ) : !ready || !view.glb ? (- <div className="grid size-full place-items-center text-muted-foreground">- <Box className="size-8 animate-pulse" />- </div>- ) : (- createElement("model-viewer", {- ref: setViewer,- src: view.glb,- poster: view.poster,- alt: `3D model made with ${g.modelName ?? "a 3D model"}`,- "camera-controls": "",- "auto-rotate": "",- "shadow-intensity": "1",- exposure: "1",- "touch-action": "pan-y",- "interaction-prompt": "none",- style: { width: "100%", height: "100%", background: "transparent" },- })- )}- {recording !== null && (- <div className="absolute inset-x-3 bottom-3 rounded-full bg-background/90 px-3 py-1.5 text-[12px] font-medium shadow-soft" role="status">- Recording the turntable… {Math.round(recording * 100)}%- </div>- )}- {g.provider === "mock" && <span className="absolute top-3 left-3 rounded-full bg-highlight/40 px-2 py-0.5 text-[11px] font-medium">Demo</span>}- {clip && recording === null && (- <div role="radiogroup" aria-label="Show" className="absolute top-3 right-3 inline-flex rounded-full bg-background/85 p-0.5 shadow-soft backdrop-blur">- {(["3d", "video"] as const).map((v) => (- <button- key={v}- type="button"- role="radio"- aria-checked={show === v}- onClick={() => setShow(v)}- className={cn("h-6 rounded-full px-2.5 text-[11px] font-medium transition", show === v ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}- >- {v === "3d" ? "3D" : "Turntable"}- </button>- ))}- </div>- )}- </div>- <div className="space-y-2 p-3">- <p className="truncate text-[13px] text-muted-foreground">{g.modelName}</p>- <div className="flex flex-wrap gap-1.5">- {view.glb && (- <Button asChild variant="outline" size="sm" className="rounded-full">- <a href={view.glb} download={`${name}.glb`}>- <Download className="size-3.5" /> .glb- </a>- </Button>- )}- {Object.entries(view.formats)- .filter(([k]) => k !== "glb")- .slice(0, 3)- .map(([k, url]) => (- <Button key={k} asChild variant="ghost" size="sm" className="rounded-full">- <a href={url} download>- .{k}- </a>- </Button>- ))}- {clip ? (- <Button asChild variant="outline" size="sm" className="rounded-full">- <a href={clip} download={`${name} turntable.${view.turntable ? "mp4" : "webm"}`} aria-label="Download the turntable video">- <Video className="size-3.5" /> Turntable- </a>- </Button>- ) : (- <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!ready || !canRecord || recording !== null}>- <Clapperboard className="size-3.5" /> Record turntable- </Button>- )}- {spin && (- <Button asChild size="sm" className="rounded-full">- <Link href={spin} prefetch={false}>- <Sparkles className="size-3.5" /> Animate the spin- </Link>- </Button>- )}- </div>- </div>- </article>- );+function ResultCard({ g, info, cloudAllowed }: { g: Generation; info: Record<string, Model3dInfo>; cloudAllowed: boolean }) {+ const create = useCreateGeneration();+ if (g.status === "queued" || g.status === "running") return <PendingTile g={g} ratio={4 / 3} />;+ if (g.status !== "succeeded") return <FailedTile g={g} ratio={4 / 3} onRetry={() => create.mutate(retryOf(g), { onError: (e) => toast.error((e as Error).message) })} />;+ return <ModelCard g={g} info={info} cloudAllowed={cloudAllowed} />;}diff --git a/src/components/model3d/rig-dialog.tsx b/src/components/model3d/rig-dialog.tsxnew file mode 100644index 00000000..5475502e--- /dev/null+++ b/src/components/model3d/rig-dialog.tsx@@ -0,0 +1,119 @@+"use client";++import { Loader2, PersonStanding } from "lucide-react";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from "@/components/ui/select";+import { useCreateGeneration } from "@/lib/api";+import { ANIMATION_LIBRARY_URL, ANIMATION_MAX, ANIMATION_PRESETS, animationId, rigRequest } from "@/lib/av/model3d";+import { priceLine, useRunPreview } from "./hooks";++const NONE = "none";+const NUMBER = "number";++/**+ * Rig & animate a finished model: Meshy adds a skeleton and walk / run cycles; an animation preset makes the+ * animated GLB the card plays. Cloud only (fal.ai): UniRig, the open rigger, has no verified ComfyUI pack.+ */+export function RigDialog({ glb, open, onOpenChange, cloudAllowed }: { glb: string; open: boolean; onOpenChange: (v: boolean) => void; cloudAllowed: boolean }) {+ const create = useCreateGeneration();+ const [pick, setPick] = useState<string>("30");+ const [typed, setTyped] = useState("");+ const animation = pick === NONE ? null : pick === NUMBER ? animationId(typed) : Number(pick);+ const badNumber = pick === NUMBER && animation === null;+ const req = cloudAllowed && !badNumber ? rigRequest({ glb, animation }) : null;+ const preview = useRunPreview(open ? req : null);+ const price = priceLine(preview.data);+ const go = () => {+ if (!req) return;+ create.mutate(req, {+ onSuccess: () => {+ toast.success(animation === null ? "Rigging your character" : "Rigging and animating your character");+ onOpenChange(false);+ },+ onError: (e) => toast.error((e as Error).message),+ });+ };+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Rig & animate</DialogTitle>+ <DialogDescription>+ For characters standing upright with two arms and two legs. Meshy adds a skeleton and walk and run cycles; pick an animation to make it move.+ </DialogDescription>+ </DialogHeader>+ {!cloudAllowed ? (+ <p className="rounded-xl bg-muted p-3 text-[13px] text-muted-foreground" role="note">+ Rigging runs on Meshy in the cloud, and this install runs open-source models only (Settings → Engine mode). There is no open rigger yet: UniRig's ComfyUI+ pack isn't verified.+ </p>+ ) : (+ <div className="grid gap-3">+ <div className="grid gap-1.5">+ <Label htmlFor="rig-animation">Animation</Label>+ <Select value={pick} onValueChange={setPick}>+ <SelectTrigger id="rig-animation" className="h-9 w-full rounded-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent className="max-h-80">+ <SelectItem value={NONE}>None — just the skeleton, walk and run</SelectItem>+ {ANIMATION_PRESETS.map((g) => (+ <SelectGroup key={g.group}>+ <SelectSeparator />+ <SelectLabel>{g.group}</SelectLabel>+ {g.items.map((p) => (+ <SelectItem key={p.id} value={String(p.id)}>+ {p.name}+ </SelectItem>+ ))}+ </SelectGroup>+ ))}+ <SelectSeparator />+ <SelectItem value={NUMBER}>Another, by its number…</SelectItem>+ </SelectContent>+ </Select>+ </div>+ {pick === NUMBER && (+ <div className="grid gap-1.5">+ <Label htmlFor="rig-number">Preset number (0–{ANIMATION_MAX})</Label>+ <Input+ id="rig-number"+ inputMode="numeric"+ value={typed}+ onChange={(e) => setTyped(e.target.value.replace(/[^\d]/g, "").slice(0, 3))}+ aria-invalid={!!typed && badNumber}+ aria-describedby="rig-number-hint"+ className="h-9 rounded-full"+ placeholder="e.g. 92"+ />+ <p id="rig-number-hint" className="text-[12px] text-muted-foreground">+ Find one in{" "}+ <a href={ANIMATION_LIBRARY_URL} target="_blank" rel="noreferrer" className="underline underline-offset-2">+ Meshy's animation library+ </a>{" "}+ (656 presets).+ </p>+ </div>+ )}+ <p className="text-[12px] text-muted-foreground" aria-live="polite">+ {preview.isError ? (preview.error as Error).message : (price ?? "Working out the price…")} · Runs on Meshy in the cloud, on either engine.+ </p>+ </div>+ )}+ <DialogFooter>+ <Button variant="ghost" className="rounded-full" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button className="rounded-full" onClick={go} disabled={!req || create.isPending}>+ {create.isPending ? <Loader2 className="size-4 animate-spin" /> : <PersonStanding className="size-4" />} {animation === null ? "Rig it" : "Rig and animate"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.tsindex 5104e6cf..64558e32 100644--- a/src/lib/av/model3d.ts+++ b/src/lib/av/model3d.ts@@ -1,42 +1,182 @@import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";/**- * Image to 3D / Product spin: which model, and what a finished job gives the viewer — the .glb, a- * turntable video (TRELLIS.2 renders one; for models that return only a mesh the page records one in- * the browser), a poster, the source photo — and where "Animate the spin" goes next.+ * Image to 3D / Product spin: the modes (from an image, from several images, from text, pick an object, a splat),+ * which model each runs on per engine, and what a finished job gives the viewer — the .glb (or the splat), a+ * turntable video (TRELLIS.2 and TripoSplat render one; for models that return only a mesh the page records one+ * in the browser), a poster, the source photo — and where "Animate the spin" and "Rig & animate" go next.*/export const MODEL3D_FEATURE = "image-to-3d";+/** The helper steps of a chain (the open text-to-3D still): kept out of the page's results and the Library. */+export const MODEL3D_STEP_FEATURE = "image-to-3d-step";-export const MODELS_3D: Record<Engine, { id: string; note: string }[]> = {- cloud: [- { id: "hunyuan-3d-3-1-pro", note: "Textured, game-ready · ≈ $0.38" },- { id: "hunyuan-3d-3-1-rapid", note: "Faster single view · ≈ $0.23" },- { id: "trellis-2", note: "Detailed geometry · ≈ $0.30" },- { id: "tripo-h3-1", note: "Clean topology, PBR · ≈ $0.30" },- { id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },- ],- open: [- { id: "oss-trellis2", note: "Textured GLB + turntable video · 16 GB GPU · MIT" },- { id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },- ],+export type Model3dMode = "image" | "multi" | "text" | "objects" | "splat";++export const MODEL3D_MODES: { id: Model3dMode; label: string; hint: string }[] = [+ { id: "image", label: "From an image", hint: "One clear photo of one object" },+ { id: "multi", label: "From several images", hint: "2–4 photos of the same object from different sides" },+ { id: "text", label: "From text", hint: "Describe one object" },+ { id: "objects", label: "Pick an object", hint: "Name what to take out of a photo" },+ { id: "splat", label: "Splat", hint: "A Gaussian splat of the subject" },+];++export interface Model3dChoice {+ id: string;+ note: string;+}++/** The models each mode offers, the default first. Pick an object has no open model (SAM 3D Objects is cloud only). */+export const MODELS_3D: Record<Model3dMode, Record<Engine, Model3dChoice[]>> = {+ image: {+ cloud: [+ { id: "hunyuan-3d-3-1-pro", note: "Textured, game-ready · ≈ $0.38" },+ { id: "hunyuan-3d-3-1-rapid", note: "Faster single view · ≈ $0.23" },+ { id: "trellis-2", note: "Detailed geometry · ≈ $0.30" },+ { id: "tripo-h3-1", note: "Clean topology, PBR · ≈ $0.30" },+ { id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },+ ],+ open: [+ { id: "oss-trellis2", note: "Textured GLB + turntable video · 16 GB GPU · MIT" },+ { id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },+ ],+ },+ multi: {+ cloud: [{ id: "meshy-7-1-multi", note: "Textured, from 2–4 photos · ≈ $1.20" }],+ open: [{ id: "oss-trellis2-multi", note: "The front plus up to 3 sides · textured GLB + turntable · 16 GB GPU · MIT" }],+ },+ text: {+ cloud: [{ id: "tripo-h3-1-text", note: "A textured model from words · ≈ $0.20" }],+ open: [{ id: "oss-text-trellis2", note: "Draws the object, then builds it · textured GLB + turntable · 16 GB GPU" }],+ },+ objects: {+ cloud: [{ id: "sam-3d-objects", note: "Rebuilds what you name, as it stands in the photo · ≈ $0.02" }],+ open: [],+ },+ splat: {+ cloud: [{ id: "triposplat", note: "The subject as a .ply splat · ≈ $0.05" }],+ open: [{ id: "oss-triposplat", note: "The subject as a .spz splat + an orbit video · 8 GB GPU · MIT" }],+ },};-export function model3dRequest(o: { engine: Engine; photo: string; modelId?: string }): GenerationRequest {- const id = o.modelId && MODELS_3D[o.engine].some((m) => m.id === o.modelId) ? o.modelId : MODELS_3D[o.engine][0].id;- return { feature: MODEL3D_FEATURE, modelId: id, op: "image-to-3d", inputs: { images: [o.photo] } };+/** Every model the page offers (⌘K's ?model= links land on its mode). */+export const ALL_MODELS_3D: Model3dChoice[] = Object.values(MODELS_3D).flatMap((m) => [...m.cloud, ...m.open]);++/** The mode and engine a model belongs to (a ?model= link). */+export function modeOf(id: string): { mode: Model3dMode; engine: Engine } | null {+ for (const mode of Object.keys(MODELS_3D) as Model3dMode[]) {+ for (const engine of ["cloud", "open"] as const) if (MODELS_3D[mode][engine].some((m) => m.id === id)) return { mode, engine };+ }+ return null;+}++/** The sides of an object, in the order the open multi-view graph takes them; the front is needed. */+export const VIEW_SIDES = ["front", "left", "back", "right"] as const;+export type ViewSide = (typeof VIEW_SIDES)[number];+export const SIDE_LABELS: Record<ViewSide, string> = { front: "Front", left: "Left side", back: "Back", right: "Right side" };++/** What the user filled in: the photo (or photos by side), the words. */+export interface Model3dInput {+ engine: Engine;+ mode?: Model3dMode;+ modelId?: string;+ /** From an image, Pick an object, Splat. */+ photo?: string;+ /** From several images: the photos by side. */+ views?: Partial<Record<ViewSide, string>>;+ /** From text: the object; Pick an object: what to take out. */+ prompt?: string;+}++/** The model for a mode and engine: the one picked when the mode offers it, else its default (null: none on that engine). */+export function model3dFor(mode: Model3dMode, engine: Engine, modelId?: string): string | null {+ const list = MODELS_3D[mode][engine];+ return (modelId && list.find((m) => m.id === modelId)?.id) || list[0]?.id || null;+}++export const MAX_3D_PROMPT = 600;+const NO_OPEN_OBJECTS = "Pick an object runs on SAM 3D Objects, a cloud model";++/** Why the request can't go yet, in the words the button shows (null: ready). */+export function model3dBlocker(i: Model3dInput): string | null {+ const mode = i.mode ?? "image";+ if (!model3dFor(mode, i.engine, i.modelId)) return NO_OPEN_OBJECTS;+ if (mode === "multi") {+ if (!i.views?.front) return "Add a photo of the front";+ return VIEW_SIDES.filter((s) => i.views?.[s]).length < 2 ? "Add at least one more side" : null;+ }+ if (mode === "text") return i.prompt?.trim() ? null : "Describe the object";+ if (!i.photo) return "Add a photo";+ if (mode === "objects" && !i.prompt?.trim()) return "Name the object to take out";+ return null;+}++/**+ * The generation request for a mode. Several images go in side order (front, left, back, right); the open+ * graph also gets their sides by name (params.extra.views), since a side may be missing. SAM 3D Objects+ * always gets the words (its API reads "car" when there are none).+ */+export function model3dRequest(i: Model3dInput): GenerationRequest {+ const mode = i.mode ?? "image";+ const modelId = model3dFor(mode, i.engine, i.modelId);+ if (!modelId) throw new Error(NO_OPEN_OBJECTS);+ const prompt = i.prompt?.trim().slice(0, MAX_3D_PROMPT) ?? "";+ const base = { feature: MODEL3D_FEATURE, modelId };+ const images = i.photo ? [i.photo] : [];+ switch (mode) {+ case "multi": {+ const sides = VIEW_SIDES.filter((s) => i.views?.[s]);+ return {+ ...base,+ op: "image-to-3d",+ inputs: { images: sides.map((s) => i.views![s]!) },+ ...(i.engine === "open" && { params: { extra: { views: [...sides] } } }),+ };+ }+ case "text":+ return { ...base, op: "text-to-3d", prompt };+ case "objects":+ return { ...base, op: "image-to-3d", prompt, inputs: { images } };+ case "splat":+ return { ...base, op: "splat", inputs: { images } };+ default:+ return { ...base, op: "image-to-3d", inputs: { images } };+ }+}++/** The mode a job was made in (its card goes by it). */+export function modeOfRequest(r: Pick<GenerationRequest, "op" | "modelId" | "inputs">): Model3dMode {+ if (r.op === "splat") return "splat";+ if (r.op === "text-to-3d") return "text";+ return modeOf(r.modelId)?.mode ?? ((r.inputs?.images?.length ?? 0) > 1 ? "multi" : "image");+}++/**+ * The open text-to-3D still: one object, whole, centred on a plain background in soft light, which is+ * what TRELLIS.2's cut-out and reconstruction want.+ */+export function stillPromptFor3d(prompt: string): string {+ const words = prompt.trim().replace(/[.\s]+$/, "");+ return `${words}. A single object, whole and centred, seen from the front at eye level, on a plain light grey background, soft even studio light, no other objects, no text`;}export interface Model3dView {glb?: string;- /** A rendered turntable that came with the model (TRELLIS.2 open, demo). */+ /** A Gaussian splat (.ply / .spz / .ksplat), which the page doesn't draw: downloaded, with its turntable or preview shown. */+ splat?: { url: string; format: string };+ /** A rendered turntable that came with the model (TRELLIS.2, TripoSplat on the open engine, demo). */turntable?: string;poster?: string;/** The product photo it was made from. */photo?: string;- /** Other formats the provider returned (OBJ, FBX, USDZ…), by extension. */+ /** Other files the provider returned (OBJ, FBX, USDZ, the splat, the walk and run clips…), by name. */formats: Record<string, string>;+ /** A rigged character; `animated` when it plays an animation preset. */+ rigged?: boolean;+ animated?: boolean;}+const SPLAT_FORMATS = new Set(["ply", "spz", "ksplat", "splat"]);+export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3dView {const mesh = g.outputs.find((o) => o.kind === "model3d");const meta = (mesh?.meta ?? {}) as Record<string, unknown>;@@ -46,12 +186,19 @@ export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3dconst formats: Record<string, string> = {};const listed = meta.formats;if (listed && typeof listed === "object") for (const [k, v] of Object.entries(listed as Record<string, unknown>)) if (typeof v === "string") formats[k.toLowerCase()] = v;+ // A splat says so (meta.format), or its file's extension does. The demo's "splat" is a GLB the viewer shows.+ const ext = mesh?.url.split("?")[0].split(".").pop()?.toLowerCase();+ const format = str(meta.format)?.toLowerCase() ?? (ext && SPLAT_FORMATS.has(ext) ? ext : undefined);+ const splat = mesh && format && SPLAT_FORMATS.has(format) ? { url: mesh.url, format } : undefined;return {- glb: mesh?.url,+ glb: splat ? undefined : mesh?.url,+ splat,turntable: str(meta.turntable) ?? str(meta.video) ?? video?.url,poster: str(meta.preview) ?? str(meta.poster) ?? g.outputs.find((o) => o.kind === "image")?.url,photo: g.request.inputs?.images?.[0],formats,+ rigged: meta.rigged === true || undefined,+ animated: meta.animated === true || undefined,};}@@ -64,3 +211,98 @@ export function animateSpinHref(v: Model3dView, turntable?: string): string | nuif (v.photo) return `/video?${new URLSearchParams({ image: v.photo, prompt: SPIN_PROMPT })}`;return null;}++// ---------------------------------------------------------------------------+// Rig & animate (Meshy rigging on fal; cloud only — UniRig's ComfyUI pack isn't verified)++export const RIG_MODEL = "meshy-rigging";++/**+ * Animation presets from Meshy's library (https://docs.meshy.ai/en/api/animation-library: 656 presets numbered+ * 0–696, read 2026-10-25): a short list by kind; any other goes by its number.+ */+export const ANIMATION_PRESETS: { group: string; items: { id: number; name: string }[] }[] = [+ {+ group: "Everyday",+ items: [+ { id: 0, name: "Idle" },+ { id: 28, name: "Wave hello" },+ { id: 41, name: "Bow" },+ { id: 25, name: "Nod yes" },+ { id: 50, name: "Phone call" },+ { id: 56, name: "Stand and chat" },+ { id: 32, name: "Sit on a chair" },+ ],+ },+ {+ group: "Walk and run",+ items: [+ { id: 30, name: "Casual walk" },+ { id: 106, name: "Confident walk" },+ { id: 117, name: "Red carpet walk" },+ { id: 118, name: "Skip" },+ { id: 14, name: "Run" },+ { id: 16, name: "Sprint" },+ { id: 112, name: "Monster walk" },+ ],+ },+ {+ group: "Dance",+ items: [+ { id: 22, name: "Funny dance" },+ { id: 74, name: "Gangnam groove" },+ { id: 82, name: "Shake it off" },+ { id: 64, name: "All-night dance" },+ ],+ },+ {+ group: "Jump and cheer",+ items: [+ { id: 466, name: "Jump" },+ { id: 44, name: "Happy jump" },+ { id: 452, name: "Backflip" },+ { id: 59, name: "Victory cheer" },+ { id: 303, name: "Cheer with both hands" },+ ],+ },+ {+ group: "Fight",+ items: [+ { id: 89, name: "Combat stance" },+ { id: 87, name: "Boxing" },+ { id: 96, name: "Kung fu punch" },+ { id: 207, name: "Roundhouse kick" },+ { id: 198, name: "Punch combo" },+ ],+ },+ {+ group: "Workout",+ items: [+ { id: 329, name: "Push-ups" },+ { id: 319, name: "Squats" },+ ],+ },+];++export const ANIMATION_MAX = 696;+export const ANIMATION_LIBRARY_URL = "https://docs.meshy.ai/en/api/animation-library";++export function animationName(id: number): string {+ for (const g of ANIMATION_PRESETS) for (const p of g.items) if (p.id === id) return p.name;+ return `Preset ${id}`;+}++/** A preset number Meshy takes (a whole number 0–696), else null. */+export function animationId(v: unknown): number | null {+ const n = typeof v === "number" ? v : typeof v === "string" && v.trim() ? Number(v) : NaN;+ return Number.isInteger(n) && n >= 0 && n <= ANIMATION_MAX ? n : null;+}++/**+ * Rig a finished model (a humanoid GLB): the skeleton plus Meshy's walk and run cycles, and with a preset the+ * animated GLB the viewer plays.+ */+export function rigRequest(o: { glb: string; animation?: number | null }): GenerationRequest {+ const animation = o.animation === undefined || o.animation === null ? null : animationId(o.animation);+ return { feature: MODEL3D_FEATURE, modelId: RIG_MODEL, op: "rig-3d", inputs: { model3d: o.glb }, ...(animation !== null && { params: { animation } }) };+}diff --git a/src/lib/palette-index.ts b/src/lib/palette-index.tsindex 305640fc..e05e383c 100644--- a/src/lib/palette-index.ts+++ b/src/lib/palette-index.ts@@ -2,7 +2,7 @@* The slim catalog behind the ⌘K palette (GET /api/search-index): names, categories and where each item* opens. Built on the server from the catalog, so the palette never ships prompt templates or routes.*/-import { MODELS_3D } from "@/lib/av/model3d";+import { ALL_MODELS_3D, RIG_MODEL } from "@/lib/av/model3d";import { APPS, EFFECTS, MODELS, MOTIONS } from "@/lib/catalog";import { OPERATION_LABELS, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";import type { PaletteIndex, PaletteModel, PalettePreset } from "@/lib/command-search";@@ -61,8 +61,8 @@ const MODEL_STUDIOS: [string, StudioConfig][] = [["/video-tools/colors", VIDEO_COLOR_MATCH_STUDIO],];-/** Image to 3D picks its model from ?model= too. */-const IN_3D = new Set([...MODELS_3D.cloud, ...MODELS_3D.open].map((m) => m.id));+/** Image to 3D picks its model from ?model= too (and rigs its results). */+const IN_3D = new Set([...ALL_MODELS_3D.map((m) => m.id), RIG_MODEL]);/** The Layers editor's tools (cut-out, layers, text detection…): its project list is where they start. */const IN_LAYERS = new Set(Object.values(TOOL_MODELS).flatMap((t) => [...t.cloud, ...t.open]));/** Tools with their own flow (and their own model choice), by operation. */diff --git a/tests/av-tools.test.ts b/tests/av-tools.test.tsindex ff188ca2..ada1fa8b 100644--- a/tests/av-tools.test.ts+++ b/tests/av-tools.test.ts@@ -109,7 +109,7 @@ describe("3D viewer data flow", () => {expect(model3dRequest({ engine: "cloud", photo: "p.png" })).toEqual({ feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d", inputs: { images: ["p.png"] } });expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-trellis2");expect(model3dRequest({ engine: "cloud", photo: "p.png", modelId: "tripo-h3-1" }).modelId).toBe("tripo-h3-1");- for (const m of [...MODELS_3D.cloud, ...MODELS_3D.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);+ for (const m of [...MODELS_3D.image.cloud, ...MODELS_3D.image.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);});it("a cloud GLB with formats and a preview → viewer, downloads, and Animate the spin from the photo", () => {diff --git a/tests/model3d.test.ts b/tests/model3d.test.tsnew file mode 100644index 00000000..78273ecb--- /dev/null+++ b/tests/model3d.test.ts@@ -0,0 +1,291 @@+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 { Model3dChoice, Model3dMode } from "@/lib/av/model3d";++/**+ * Image to 3D's modes (r4/3d-plus): the plan per mode and engine, the cloud payloads (SAM 3D's prompt is+ * always sent), the outputs the cards read, the open multi-view and splat bindings, the open text-to-3D chain+ * and Rig & animate.+ */++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-model3d-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const { collectOutputs, getWorkflow, prepareWorkflow, viewSlots } = await import("@/server/providers/comfyui");+const { getModel, getPreset } = await import("@/lib/catalog");+const { estimateCost, planGeneration } = await import("@/lib/catalog/plan");+const { buildPayload, extractOutputs } = await import("@/lib/catalog/payload");+const { dropBranch } = await import("@/lib/comfy");+const m3d = await import("@/lib/av/model3d");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const plan = (req: Parameters<typeof planGeneration>[0]) => planGeneration(req, getModel, getPreset);+const photo = "/api/files/uploads/p.png";+const views = { front: "/api/files/f.png", left: "/api/files/l.png", back: "/api/files/b.png" };++describe("modes: which model and operation each runs, per engine", () => {+ const cases: [Model3dMode, "cloud" | "open", string, string][] = [+ ["image", "cloud", "hunyuan-3d-3-1-pro", "image-to-3d"],+ ["image", "open", "oss-trellis2", "image-to-3d"],+ ["multi", "cloud", "meshy-7-1-multi", "image-to-3d"],+ ["multi", "open", "oss-trellis2-multi", "image-to-3d"],+ ["text", "cloud", "tripo-h3-1-text", "text-to-3d"],+ ["text", "open", "oss-text-trellis2", "text-to-3d"],+ ["objects", "cloud", "sam-3d-objects", "image-to-3d"],+ ["splat", "cloud", "triposplat", "splat"],+ ["splat", "open", "oss-triposplat", "splat"],+ ];+ it.each(cases)("%s on %s → %s (%s)", (mode, engine, modelId, op) => {+ const input = { engine, mode, photo, views, prompt: "a red leather armchair" };+ expect(m3d.model3dBlocker(input)).toBeNull();+ const req = m3d.model3dRequest(input);+ expect(req).toMatchObject({ feature: "image-to-3d", modelId, op });+ const p = plan(req);+ expect([p.model.id, p.op, p.model.engine]).toEqual([modelId, op, engine]);+ expect(p.jobs).toBe(1);+ expect(m3d.modeOfRequest(req)).toBe(mode);+ expect(m3d.modeOf(modelId)).toEqual({ mode, engine });+ });++ it("every model the page offers is in the catalog with its mode's operation", () => {+ const ops: Record<Model3dMode, string> = { image: "image-to-3d", multi: "image-to-3d", text: "text-to-3d", objects: "image-to-3d", splat: "splat" };+ for (const [mode, byEngine] of Object.entries(m3d.MODELS_3D) as [Model3dMode, Record<string, Model3dChoice[]>][]) {+ for (const [engine, list] of Object.entries(byEngine)) {+ for (const c of list) {+ const m = getModel(c.id);+ expect(m?.engine, c.id).toBe(engine);+ expect(m?.routes.some((r) => r.op === ops[mode]), c.id).toBe(true);+ }+ }+ }+ expect(getModel(m3d.RIG_MODEL)?.routes[0]).toMatchObject({ op: "rig-3d", provider: "fal", endpoint: "fal-ai/meshy/rigging" });+ });++ it("says what is missing, and that Pick an object is cloud only", () => {+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "image" })).toBe("Add a photo");+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "multi", views: { left: "l.png", back: "b.png" } })).toBe("Add a photo of the front");+ expect(m3d.model3dBlocker({ engine: "open", mode: "multi", views: { front: "f.png" } })).toBe("Add at least one more side");+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "text", prompt: " " })).toBe("Describe the object");+ expect(m3d.model3dBlocker({ engine: "cloud", mode: "objects", photo })).toBe("Name the object to take out");+ expect(m3d.model3dBlocker({ engine: "open", mode: "objects", photo, prompt: "lamp" })).toMatch(/cloud model/);+ expect(() => m3d.model3dRequest({ engine: "open", mode: "objects", photo, prompt: "lamp" })).toThrow(/cloud model/);+ // An unknown pick falls back to the mode's default.+ expect(m3d.model3dRequest({ engine: "open", mode: "splat", photo, modelId: "triposplat" }).modelId).toBe("oss-triposplat");+ });++ it("sends several photos in side order; the open graph also gets their sides by name", () => {+ const sides = { front: "f.png", back: "b.png", right: "r.png" };+ expect(m3d.model3dRequest({ engine: "cloud", mode: "multi", views: sides })).toEqual({ feature: "image-to-3d", modelId: "meshy-7-1-multi", op: "image-to-3d", inputs: { images: ["f.png", "b.png", "r.png"] } });+ expect(m3d.model3dRequest({ engine: "open", mode: "multi", views: sides }).params).toEqual({ extra: { views: ["front", "back", "right"] } });+ // Meshy multi-view and the open graph need two photos.+ expect(() => plan({ feature: "x", modelId: "meshy-7-1-multi", op: "image-to-3d", inputs: { images: ["f.png"] } })).toThrow();+ expect(() => plan({ feature: "x", modelId: "oss-trellis2-multi", op: "image-to-3d", inputs: { images: ["f.png"] } })).toThrow();+ });++ it("refuses SAM 3D Objects without words and a text model without a description", () => {+ expect(() => plan({ feature: "x", modelId: "sam-3d-objects", op: "image-to-3d", prompt: "", inputs: { images: [photo] } })).toThrow(/Name the objects/);+ expect(() => plan({ feature: "x", modelId: "tripo-h3-1-text", op: "text-to-3d", prompt: "" })).toThrow();+ });+});++describe("cloud payloads", () => {+ const route = (id: string) => getModel(id)!.routes[0];++ it("SAM 3D Objects: the words always go (the API reads “car” without them), with a textured GLB", () => {+ const req = m3d.model3dRequest({ engine: "cloud", mode: "objects", photo, prompt: " the green lamp " });+ expect(req.prompt).toBe("the green lamp");+ const p = plan(req);+ const body = buildPayload(route("sam-3d-objects").map!, { prompt: p.prompt, images: ["https://fal.test/p.png"], seed: 4 });+ expect(body).toEqual({ prompt: "the green lamp", image_url: "https://fal.test/p.png", seed: 4, export_textured_glb: true });+ });++ it("Meshy multi-view: the photos as image_urls; Tripo text: the words as the prompt", () => {+ expect(buildPayload(route("meshy-7-1-multi").map!, { prompt: "", images: ["a.png", "b.png"] })).toMatchObject({ image_urls: ["a.png", "b.png"] });+ expect(buildPayload(route("tripo-h3-1-text").map!, { prompt: "a brass lantern", seed: 9 })).toMatchObject({ prompt: "a brass lantern", model_seed: 9 });+ });++ it("TripoSplat: a .ply splat of the photo, with the number of Gaussians picked", () => {+ const body = buildPayload(route("triposplat").map!, { prompt: "", images: ["https://fal.test/p.png"], extra: { num_gaussians: 131072 } });+ expect(body).toEqual({ image_url: "https://fal.test/p.png", output_format: "ply", num_gaussians: 131072 });+ });++ it("Meshy rigging: the model's URL, and a preset turns animation on; it costs $0.12 more", () => {+ const rig = getModel(m3d.RIG_MODEL)!;+ const animated = m3d.rigRequest({ glb: "/api/files/m.glb", animation: 30 });+ expect(animated).toEqual({ feature: "image-to-3d", modelId: "meshy-rigging", op: "rig-3d", inputs: { model3d: "/api/files/m.glb" }, params: { animation: 30 } });+ expect(plan(animated).op).toBe("rig-3d");+ expect(buildPayload(rig.routes[0].map!, { prompt: "", model3d: "https://fal.test/m.glb", animation: 30 })).toEqual({ model_url: "https://fal.test/m.glb", animation_action_id: 30, enable_animation: true });+ expect(buildPayload(rig.routes[0].map!, { prompt: "", model3d: "https://fal.test/m.glb" })).toEqual({ model_url: "https://fal.test/m.glb" });+ expect(estimateCost(rig, {}, 1, "rig-3d")).toBe(0.2);+ expect(estimateCost(rig, { animation: 30 }, 1, "rig-3d")).toBe(0.32);+ // Only Meshy's preset numbers go.+ expect(m3d.rigRequest({ glb: "m.glb", animation: 697 }).params).toBeUndefined();+ expect(m3d.animationId("92")).toBe(92);+ expect(m3d.animationId("9.5")).toBeNull();+ expect(m3d.animationName(30)).toBe("Casual walk");+ expect(m3d.animationName(92)).toBe("Preset 92");+ expect(() => plan({ feature: "x", modelId: "meshy-rigging", op: "rig-3d" })).toThrow(/3D model to rig/);+ });+});++describe("what the cards show", () => {+ const view = (outputs: ReturnType<typeof extractOutputs>, request = m3d.model3dRequest({ engine: "cloud", mode: "splat", photo })) =>+ m3d.model3dView({ outputs: outputs.map((o) => ({ ...o, meta: o.meta ?? {} })) as never, request });++ it("a cloud splat is a download with the cut-out as its poster, not a GLB for the viewer", () => {+ const outs = extractOutputs({ model_mesh: { url: "https://fal.test/x/splat.ply" }, preprocessed_image: { url: "https://fal.test/x/seen.png" } }, "splat");+ expect(view(outs)).toMatchObject({ glb: undefined, splat: { url: "https://fal.test/x/splat.ply", format: "ply" }, poster: "https://fal.test/x/seen.png" });+ });++ it("an open splat (.spz) brings its orbit video", () => {+ const v = m3d.model3dView({+ outputs: [+ { url: "/api/files/g/s.spz", kind: "model3d", meta: { role: "splat", format: "spz" } },+ { url: "/api/files/g/orbit.mp4", kind: "video", meta: { role: "turntable" } },+ ] as never,+ request: m3d.model3dRequest({ engine: "open", mode: "splat", photo }),+ });+ expect(v).toMatchObject({ splat: { url: "/api/files/g/s.spz", format: "spz" }, turntable: "/api/files/g/orbit.mp4", glb: undefined });+ // The demo's splat is a GLB the viewer shows.+ expect(m3d.model3dView({ outputs: [{ url: "sample:demo-model.glb", kind: "model3d", meta: { splat: true, format: "glb" } }] as never, request: { feature: "x", modelId: "y", op: "splat" } as never })).toMatchObject({ glb: "sample:demo-model.glb", splat: undefined });+ });++ it("SAM 3D Objects: the GLB in the viewer, its splat as a download", () => {+ const outs = extractOutputs({ model_glb: { url: "https://fal.test/o.glb" }, gaussian_splat: { url: "https://fal.test/o.ply" } }, "image-to-3d");+ expect(view(outs, m3d.model3dRequest({ engine: "cloud", mode: "objects", photo, prompt: "lamp" }))).toMatchObject({ glb: "https://fal.test/o.glb", formats: { splat: "https://fal.test/o.ply" } });+ });++ it("a rig plays the animated GLB, with the rigged one and the walk and run cycles to download", () => {+ const outs = extractOutputs(+ {+ rigged_character_glb: { url: "https://fal.test/rig.glb" },+ animation_glb: { url: "https://fal.test/anim.glb" },+ animation_fbx: { url: "https://fal.test/anim.fbx" },+ basic_animations: { walking_glb: { url: "https://fal.test/walk.glb" }, running_glb: { url: "https://fal.test/run.glb" } },+ },+ "rig-3d",+ );+ expect(view(outs, m3d.rigRequest({ glb: "/api/files/m.glb", animation: 22 }))).toMatchObject({+ glb: "https://fal.test/anim.glb",+ rigged: true,+ animated: true,+ formats: { fbx: "https://fal.test/anim.fbx", rigged: "https://fal.test/rig.glb", walking: "https://fal.test/walk.glb", running: "https://fal.test/run.glb" },+ });+ });+});++describe("open engine: multi-view TRELLIS.2 (image-to-3d-trellis2-multiview)", () => {+ const manifest = getWorkflow("image-to-3d-trellis2-multiview").manifest;+ const prep = (images: string[], extra?: Record<string, unknown>) =>+ prepareWorkflow("image-to-3d-trellis2-multiview", { prompt: "", images, extra }, { generationId: "gen-mv", op: "image-to-3d", upload: async (_d, _t, n) => `up_${n}` });++ it("is a validated workflow with a licence that asks for the DINOv3 notice", () => {+ expect(manifest).toMatchObject({ capability: "image-to-3d", validated: true });+ expect(manifest.license).toMatch(/Built with DINOv3/);+ expect(manifest.outputs).toEqual([{ node: "372", kind: "model3d" }, { node: "702", kind: "video", role: "turntable" }]);+ });++ it("puts each photo on its side and leaves the missing side out of the graph", async () => {+ const { workflow } = await prep(["f.png", "b.png"], { views: ["front", "back"] });+ expect(workflow["360"].inputs.image).toBe("f.png");+ expect(workflow["362"].inputs.image).toBe("b.png");+ // Left and right: their loaders, cut-outs and crops are gone, and the rig doesn't read them.+ for (const id of ["361", "363", "348", "349", "352", "353"]) expect(workflow[id], id).toBeUndefined();+ expect(Object.keys(workflow["324"].inputs).sort()).toEqual(["back", "clip_vision_model", "fov", "front"]);+ expect(workflow["324"].inputs.front).toEqual(["312", 0]);+ // The shared cut-out model and the outputs stay.+ expect(workflow["193"]).toBeDefined();+ expect(workflow["372"].inputs.filename_prefix).toBe("fuobe/gen-mv");+ expect(workflow["702"].inputs.filename_prefix).toBe("fuobe/gen-mv");+ });++ it("takes the photos in side order when they aren't named, and all four sides", async () => {+ const { workflow } = await prep(["f.png", "l.png", "b.png", "r.png"]);+ expect(["360", "361", "362", "363"].map((id) => workflow[id].inputs.image)).toEqual(["f.png", "l.png", "b.png", "r.png"]);+ expect(Object.keys(workflow["324"].inputs).sort()).toEqual(["back", "clip_vision_model", "fov", "front", "left", "right"]);+ });++ it("needs the front, and one photo per named side", async () => {+ await expect(prep(["l.png", "b.png"], { views: ["left", "back"] })).rejects.toThrow("Add a photo of the front");+ await expect(prep(["f.png", "b.png"], { views: ["front"] })).rejects.toThrow(/2 photos but 1 side/);+ await expect(prep(["f.png", "x.png"], { views: ["front", "top"] })).rejects.toThrow(/front, left, back, right/);+ await expect(prep(["f.png", "x.png"], { views: ["front", "front"] })).rejects.toThrow(/Two photos of the front/);+ expect(viewSlots({ sides: ["front", "left"], into: "X" }, ["a", "b"], undefined)).toEqual({ image: "a", image2: "b" });+ });++ it("dropBranch refuses a branch that doesn't end in the named node", () => {+ const wf = { "1": { class_type: "LoadImage", inputs: { image: "a.png" } }, "2": { class_type: "SaveImage", inputs: { images: ["1", 0] } } };+ expect(dropBranch(wf, "1", "Pixal3DMultiViewConditioning")).toBeNull();+ expect(dropBranch(wf, "9", "Pixal3DMultiViewConditioning")).toBeNull();+ });+});++describe("open engine: TripoSplat (image-to-splat-triposplat)", () => {+ it("binds the photo, the Gaussians picked and the defaults (cut-out on, .spz)", async () => {+ const m = getModel("oss-triposplat")!;+ expect(m.routes).toEqual([expect.objectContaining({ op: "splat", provider: "comfyui", endpoint: "image-to-splat-triposplat" })]);+ const { workflow } = await prepareWorkflow("image-to-splat-triposplat", { prompt: "", images: ["p.png"], extra: { numGaussians: 131072 } }, { generationId: "gen-sp", op: "splat", upload: async () => "x" });+ expect(workflow["99"].inputs.image).toBe("p.png");+ expect(workflow["88:55"].inputs.num_gaussians).toBe(131072);+ expect(workflow["88:35"].inputs.switch).toBe(true);+ expect(workflow["92"].inputs.format).toBe("spz");+ });++ it("names the splat's format and type, and keeps the orbit video as the turntable", () => {+ const file = (filename: string) => ({ filename, subfolder: "fuobe", type: "output" });+ const outs = collectOutputs(+ { status: { status_str: "success", completed: true }, outputs: { "51": { "3d": [file("gen-sp_00001_.spz")] }, "42": { images: [file("gen-sp_00001_.mp4")], animated: [true] } } },+ getWorkflow("image-to-splat-triposplat").manifest,+ );+ expect(outs.map((o) => [o.kind, o.contentType, o.meta])).toEqual([+ ["model3d", "model/x-spz", { role: "splat", format: "spz" }],+ ["video", undefined, { role: "turntable" }],+ ]);+ });+});++describe("open engine: text to 3D as a Z-Image Turbo still, then TRELLIS.2", () => {+ async function settle(id: string, ms = 40_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));+ }+ }++ it("is free and runs as two steps: the still (a helper step) and the model made from it", async () => {+ const req = m3d.model3dRequest({ engine: "open", mode: "text", prompt: "A brass lantern." });+ expect(gens.previewGeneration(req)).toMatchObject({ op: "text-to-3d", costUsd: 0 });+ const [built, still] = gens.createGenerations(req);+ expect(still).toMatchObject({ feature: "image-to-3d-step", modelId: "oss-z-image-turbo", op: "t2i" });+ expect(still.prompt).toMatch(/^A brass lantern\. A single object, whole and centred/);+ expect(built).toMatchObject({ feature: "image-to-3d", modelId: "oss-trellis2", op: "image-to-3d", status: "queued" });+ expect(built.batchId).toBe(still.batchId);+ const dep = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(built.id) as { depends_on: string }).depends_on;+ expect(dep).toBe(still.id);+ const done = await settle(built.id);+ expect(done.status).toBe("succeeded");+ expect(done.outputs.some((o) => o.kind === "model3d")).toBe(true);+ expect(done.request.inputs?.images?.length).toBe(1);+ }, 60_000);++ it("needs the words", () => {+ expect(() => gens.createGenerations({ feature: "image-to-3d", modelId: "oss-text-trellis2", op: "text-to-3d", prompt: " " })).toThrow();+ });++ it("writes the still prompt for a clean cut-out", () => {+ expect(m3d.stillPromptFor3d(" a ceramic teapot... ")).toBe(+ "a ceramic teapot. A single object, whole and centred, seen from the front at eye level, on a plain light grey background, soft even studio light, no other objects, no text",+ );+ });+});