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.

Image to 3D: the full-screen splat viewer lets the arrow keys browse results, and closed viewers give their WebGL context back

Claude54249e70ffaa
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 2e0e4bd7..7597a458 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -145,7 +145,7 @@ Every adapter implements `isConfigured`, `prepareFile`, `submit` and `poll`, and
- **Round 5 part 2: soundtrack splits and asked sizes.** On `separate-soundtrack-dbs`, `prepareWorkflow()` binds `separationModel` to the model asked for, else the host's pick (`dbsModelFor` in `src/lib/av/split.ts`: DBS-TIGER on a CUDA device, DBS-BSRNN on a CPU, the other one when the pick isn't on disk). The device comes from `/system_stats` (`comfyDevice`, kept a minute) and the models on disk from `GET /models/dbs`, which ComfyUI-DBS registers (`comfyDbsModels`, read fresh at submit; callers that arrive while either request is on its way share it); a model that isn't there is refused in words, never sent. `channels` is mono or each channel (`dbsChannelsFor`), and a source with more than 2 channels (the header's count, else `params.extra.sourceChannels`) is split in mono with a mono Music & effects (`dbsSurroundBed`), because ComfyUI saves at most 2 channels. A canvas the request names (`params.extra.width` / `height`: a layout's, Soul's exact sizes) is fitted to the graph's grid and maximum side with its shape kept (`fitCanvas` in `src/lib/comfy.ts`), as the cloud's `sizeValue` fits it, so both engines render one size. Upload headers carry the channel count (`MediaInfo.channels`: WAV, FLAC, MP3 and an MP4 / MOV's first sound track in `src/lib/media-probe.ts`; WebM / Matroska in `src/server/webm-probe.ts`). The manifest's outputs gain the stems `music` and `effects` and the role `report` (a node's own account of the run).
- **llm** — text steps in this process (below).
- **local** — results made in the browser (Color grading's PNG / WebM, Ads Studio composites; `/api/generations/local` records them).
-- **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup. Round-4 operations answer too: a scene-3d job gets the GLB plus a grey depth PNG on the open engine and a Spectral-coloured depth PNG on the cloud, and an EXR job a sample clip with a zip that holds only a README. An extract-frames job returns as many frames as `max_frames` asks (4 without a count), so a per-frame Mixed Media demo fans out like the real one. Splat and rig jobs get the demo GLB too (`meta.format` `glb`), so a demo run never shows the splat card. Since round 4 part 5 a `video-swap` on Character Swap Studio's segment graph also returns a `master`, so a demo continuation runs like a real one. Since round 5 part 1 a `face-mosaic` job returns a demo picture with no masks. Since round 5 part 2 a `separate-audio` job on `separate-soundtrack-dbs` returns four stems (voice, music, effects and background, voice first). A request with `demo: true` (a skill's free dry run) goes to this provider whatever Settings → Demo mode says (see Pipelines).
+- **mock** — demo outputs for every operation (SVG art, bundled sample clips, a tone, layers with meta, cue lists, two stems, a GLB with a turntable from `scripts/gen-demo-3d.mjs`), so the product works with zero setup. Round-4 operations answer too: a scene-3d job gets the GLB plus a grey depth PNG on the open engine and a Spectral-coloured depth PNG on the cloud, and an EXR job a sample clip with a zip that holds only a README. An extract-frames job returns as many frames as `max_frames` asks (4 without a count), so a per-frame Mixed Media demo fans out like the real one. A splat job gets a real splat from `scripts/gen-demo-splat.mjs`, so the splat viewer opens in demo mode: an `.spz` with `demo-turntable.mp4` on the open engine (`meta.openSplat`: op `splat` on `comfyui`) and a `.ply` on the cloud. Rig jobs get the demo GLB (`meta.format` `glb`). Since round 4 part 5 a `video-swap` on Character Swap Studio's segment graph also returns a `master`, so a demo continuation runs like a real one. Since round 5 part 1 a `face-mosaic` job returns a demo picture with no masks. Since round 5 part 2 a `separate-audio` job on `separate-soundtrack-dbs` returns four stems (voice, music, effects and background, voice first). A request with `demo: true` (a skill's free dry run) goes to this provider whatever Settings → Demo mode says (see Pipelines).
## Structured outputs
diff --git a/src/components/model3d/splat-engine.ts b/src/components/model3d/splat-engine.ts
index c17c4a33..76132377 100644
--- a/src/components/model3d/splat-engine.ts
+++ b/src/components/model3d/splat-engine.ts
@@ -34,7 +34,17 @@ export class SplatEngine {
/** The last frame's CPU time in milliseconds (renderer.render), for the numbers in docs/research/idol-9.md. */
lastFrameMs = 0;
- constructor(private canvas: HTMLCanvasElement) {
+ private onLost = (e: Event) => {
+ e.preventDefault();
+ if (!this.disposed) this.onContextLost?.();
+ };
+
+ /** onContextLost: the browser took the WebGL context away (too many open, a GPU reset) while this was showing. */
+ constructor(
+ private canvas: HTMLCanvasElement,
+ private onContextLost?: () => void,
+ ) {
+ canvas.addEventListener("webglcontextlost", this.onLost);
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: "high-performance" });
this.spark = new SparkRenderer({ renderer: this.renderer, onDirty: () => this.requestRender() });
this.scene.add(this.spark);
@@ -178,6 +188,10 @@ export class SplatEngine {
this.mesh?.dispose();
this.spark.dispose();
this.renderer.dispose();
+ // Give the context back now rather than at garbage collection: browsers keep only about 16 live, and a feed
+ // of cards that open and close the viewer would otherwise push out the one that is showing.
+ this.renderer.forceContextLoss();
+ this.canvas.removeEventListener("webglcontextlost", this.onLost);
}
}
diff --git a/src/components/model3d/splat-viewer.tsx b/src/components/model3d/splat-viewer.tsx
index 42c3f293..85f4764c 100644
--- a/src/components/model3d/splat-viewer.tsx
+++ b/src/components/model3d/splat-viewer.tsx
@@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Slider } from "@/components/ui/slider";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { uploadFile, useIsGuest } from "@/lib/api";
+import { uploadFile, useViewer } from "@/lib/api";
import { backgroundColor, FALLBACK_TEXT, HAZE_MAX, HAZE_STEP, SPLAT_BACKGROUNDS, SPLAT_MAX_BYTES, stillFileName, type SplatBackground } from "@/lib/av/splat-view";
import { toastError } from "@/lib/refusals";
import { cn } from "@/lib/utils";
@@ -87,7 +87,9 @@ export function SplatViewer({
const { resolvedTheme } = useTheme();
const [background, setBackground] = useState<SplatBackground>(() => (tone === "panel" ? "dark" : resolvedTheme === "dark" ? "dark" : "light"));
const [saving, setSaving] = useState(false);
- const guest = useIsGuest();
+ // "Save a still" waits until who is viewing is known: a guest can't save (the upload would be refused).
+ const viewer = useViewer().data;
+ const canSave = !!viewer && !(viewer.publicSignup && !viewer.signedIn);
const helpId = useId();
const onUnavailableRef = useRef(onUnavailable);
useEffect(() => void (onUnavailableRef.current = onUnavailable));
@@ -103,7 +105,12 @@ export function SplatViewer({
import("./splat-engine")
.then(async ({ SplatEngine, SplatTooBigError }) => {
if (ctl.signal.aborted) return;
- eng = new SplatEngine(canvas);
+ eng = new SplatEngine(canvas, () => {
+ // The browser took the WebGL context back (too many open, or the GPU reset): show the fallback.
+ if (ctl.signal.aborted) return;
+ setStatus("error");
+ onUnavailableRef.current?.("The 3D view stopped here. Open it again, or download the file to look around it in a splat viewer.");
+ });
engineRef.current = eng;
const el = stageRef.current;
if (el) eng.resize(el.clientWidth, el.clientHeight, Math.min(window.devicePixelRatio || 1, coarse ? 1.5 : 2));
@@ -149,8 +156,25 @@ export function SplatViewer({
backgroundRef.current = background;
engineRef.current?.setBackground(backgroundColor(background));
}, [background]);
+ // The stage takes ArrowLeft / ArrowRight only once the user has reached for it (tabbed to it, pressed on it, used
+ // one of its keys, or chose to open it). A dialog that focuses it by itself on opening leaves those two keys to
+ // the page, so the full-screen viewer keeps browsing the results.
+ const engaged = useRef(false);
+ const tabbed = useRef(false);
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => void (tabbed.current = e.key === "Tab");
+ const onPointer = () => void (tabbed.current = false);
+ window.addEventListener("keydown", onKeyDown, true);
+ window.addEventListener("pointerdown", onPointer, true);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown, true);
+ window.removeEventListener("pointerdown", onPointer, true);
+ };
+ }, []);
useEffect(() => {
- if (autoFocus && status === "ready") stageRef.current?.focus({ preventScroll: true });
+ if (!autoFocus || status !== "ready") return;
+ engaged.current = true;
+ stageRef.current?.focus({ preventScroll: true });
}, [autoFocus, status]);
const ready = status === "ready";
@@ -171,6 +195,8 @@ export function SplatViewer({
};
const fn = act[e.key];
if (!fn) return;
+ if (!engaged.current && (e.key === "ArrowLeft" || e.key === "ArrowRight")) return;
+ engaged.current = true;
e.preventDefault();
fn();
};
@@ -223,6 +249,9 @@ export function SplatViewer({
aria-describedby={helpId}
aria-busy={!ready}
onKeyDown={onKey}
+ onFocus={() => void (engaged.current ||= tabbed.current)}
+ onBlur={() => void (engaged.current = false)}
+ onPointerDown={() => void (engaged.current = true)}
className="absolute inset-0 touch-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
>
<canvas ref={setCanvas} className={cn("size-full transition-opacity", ready ? "opacity-100" : "opacity-0")} />
@@ -293,7 +322,7 @@ export function SplatViewer({
</PopoverContent>
</Popover>
)}
- {!guest && (
+ {canSave && (
<IconButton text={saving ? "Saving the still…" : "Save a still"} panel={panel} onClick={() => void saveStill()} disabled={saving}>
{saving ? <Loader2 className="size-3.5 animate-spin" /> : <Camera className="size-3.5" />}
</IconButton>
diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsx
index a01ef47b..247ebcf8 100644
--- a/src/components/studio/result-media.tsx
+++ b/src/components/studio/result-media.tsx
@@ -249,7 +249,8 @@ export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }
/**
* A splat in the full-screen viewer (the Library's 3D tab and "View in 3D" open it): the splat viewer, with the file
* to download. The orbit video (or the picture) stays instead where the browser has no WebGL2 or the file is too big
- * for the device, and when the user prefers reduced motion until they choose "Look around in 3D".
+ * for the device, and when the user prefers reduced motion until they choose "Look around in 3D". The viewer takes
+ * focus only when they chose it: otherwise the arrow keys keep browsing the results (the Viewer's own keys).
*/
function SplatPanel({ output, format, poster, video, g }: { output: OutputFile; format: string; poster?: string; video?: string; g: Generation }) {
const hydrated = useHydrated();
@@ -267,7 +268,7 @@ function SplatPanel({ output, format, poster, video, g }: { output: OutputFile;
return (
<div className="flex size-full flex-col">
<div className="relative min-h-0 flex-1 overflow-hidden md:rounded-lg">
- <SplatViewer url={output.url} format={format} poster={poster} name={name} defaultCutoff={hazeCutoffFor(g.modelId)} tone="panel" label={g.request.prompt || "the splat"} autoFocus onUnavailable={setNote} />
+ <SplatViewer url={output.url} format={format} poster={poster} name={name} defaultCutoff={hazeCutoffFor(g.modelId)} tone="panel" label={g.request.prompt || "the splat"} autoFocus={asked} onUnavailable={setNote} />
</div>
<div className="flex shrink-0 justify-center pt-2">{download}</div>
</div>
diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.ts
index 6b26793e..cef52976 100644
--- a/src/lib/av/model3d.ts
+++ b/src/lib/av/model3d.ts
@@ -254,7 +254,7 @@ export interface Model3dView {
glb?: string;
/** The GLB to show in a viewer: the web GLB when there is one, else `glb`. */
web?: string;
- /** A Gaussian splat (.ply / .spz / .ksplat), which the page doesn't draw: downloaded, with its turntable or preview shown. */
+ /** A Gaussian splat (.ply / .spz / .ksplat): the splat viewer draws it (src/components/model3d/splat-viewer.tsx), with its turntable or preview as the poster and fallback, and it downloads. */
splat?: { url: string; format: string };
/** A rendered turntable that came with the model (the server's render for open 3D models, TripoSplat's orbit on the open engine, demo). */
turntable?: string;
@@ -276,7 +276,8 @@ const SPLAT_FORMATS = new Set(["ply", "spz", "ksplat", "splat"]);
/**
* A Gaussian splat's format (ply, spz, ksplat), which no glTF viewer loads, else undefined. A splat says so
- * (meta.format), or its file's extension does; the demo's "splat" is a GLB the viewer shows.
+ * (meta.format), or its file's extension does. A GLB marked as a splat (older demo results) stays a GLB; today's demo
+ * splat is a real .spz or .ply (scripts/gen-demo-splat.mjs).
*/
export function splatFormatOf(o: Pick<OutputFile, "url" | "meta"> | undefined): string | undefined {
if (!o) return undefined;
diff --git a/tests/demo-ops.test.ts b/tests/demo-ops.test.ts
index 10d3c6fa..a1d31e07 100644
--- a/tests/demo-ops.test.ts
+++ b/tests/demo-ops.test.ts
@@ -226,4 +226,21 @@ describe("demo outputs for the round-4 operations", () => {
expect(frames.map((f) => [f.kind, f.meta?.index])).toEqual([0, 1, 2, 3].map((i) => ["image", i]));
expect(done.overlay.outputs).toEqual([expect.objectContaining({ kind: "image", contentType: "image/svg+xml" })]);
});
+
+ it("gives an open-engine splat an .spz with its orbit video, as the TripoSplat and Idol 3D graphs write", async () => {
+ const image = saveFile({ data: png, contentType: "image/png", source: "upload" }).url;
+ for (const modelId of ["oss-triposplat", "oss-idol"]) {
+ const [g] = gens.createGenerations({ feature: "image-to-3d", modelId, op: "splat", inputs: { images: [image] } });
+ expect(g.kind, modelId).toBe("model3d");
+ const done = await settle(g.id);
+ expect(done.status, `${modelId}: ${done.error}`).toBe("succeeded");
+ const splat = done.outputs.find((o) => o.kind === "model3d");
+ expect(splat, modelId).toMatchObject({ contentType: "model/x-spz", meta: expect.objectContaining({ format: "spz", role: "splat" }) });
+ expect(splat!.url, modelId).toMatch(/\.spz$/);
+ expect(done.outputs.find((o) => o.kind === "video"), modelId).toMatchObject({ contentType: "video/mp4", meta: expect.objectContaining({ turntable: true }) });
+ // Niantic's .spz is gzip.
+ const spz = Buffer.from(await (await serve(splat!.url)).arrayBuffer());
+ expect([spz[0], spz[1]], modelId).toEqual([0x1f, 0x8b]);
+ }
+ });
});
diff --git a/tests/e2e/splat-viewer.mjs b/tests/e2e/splat-viewer.mjs
index f791fb85..cf453b11 100644
--- a/tests/e2e/splat-viewer.mjs
+++ b/tests/e2e/splat-viewer.mjs
@@ -211,6 +211,21 @@ for (const phone of [false, true]) {
await noSideScroll(page, `${tag} library viewer`);
await sleep(1000);
await shoot(page, `${name}-panel`);
+ // Opening the panel doesn't take the arrow keys: ArrowRight keeps browsing the results.
+ const shown = async () => (await dialog.getByRole("link", { name: /^\.(spz|ply)$/ }).first().getAttribute("href", { timeout: 2000 }).catch(() => null)) ?? "";
+ const before = await shown();
+ await page.keyboard.press("ArrowRight");
+ await until(async () => (await shown()) !== before, `${tag}: ArrowRight moved to the next result`, 15_000);
+ // Once the user presses on the splat, the arrow keys turn it instead.
+ const stagePanel = dialog.getByRole("application");
+ if ((await stagePanel.count()) === 1) {
+ await stagePanel.waitFor();
+ await stagePanel.click();
+ const here = await shown();
+ await page.keyboard.press("ArrowRight");
+ await sleep(1500);
+ assert.equal(await shown(), here, `${tag}: ArrowRight turns the splat the user pressed on`);
+ }
} catch (e) {
failures.push(`${tag}: ${e.message}`);
await shoot(page, `${name}-failure`);
@@ -257,6 +272,8 @@ for (const phone of [false, true]) {
const dialog = page.getByRole("dialog");
await dialog.getByRole("button", { name: "Look around in 3D" }).click({ timeout: 30_000 });
await dialog.getByRole("toolbar", { name: "3D view" }).waitFor({ timeout: 60_000 });
+ // Chosen: the viewer takes the focus, so the keys turn the splat.
+ await until(() => dialog.getByRole("application").evaluate((el) => document.activeElement === el), "reduced motion: the chosen viewer has the focus", 30_000);
await shoot(page, "reduced-motion-panel");
} catch (e) {
failures.push(`reduced motion: ${e.message}`);
diff --git a/tests/splat-view.test.ts b/tests/splat-view.test.ts
index 9ed13b49..73e4f36d 100644
--- a/tests/splat-view.test.ts
+++ b/tests/splat-view.test.ts
@@ -127,3 +127,23 @@ describe("Spark loads only with the splat viewer", () => {
expect(engineUsers.map((f) => path.relative(process.cwd(), f))).toEqual(["src/components/model3d/splat-viewer.tsx"]);
});
});
+
+describe("the viewer leaves the page as it found it", () => {
+ const read = (f: string) => fs.readFileSync(path.join(process.cwd(), f), "utf8");
+
+ it("gives its WebGL context back when it closes, and falls back when the browser takes it", () => {
+ const engine = read("src/components/model3d/splat-engine.ts");
+ const dispose = engine.slice(engine.indexOf(" dispose() {"));
+ expect(dispose.slice(0, dispose.indexOf("\n }\n"))).toMatch(/this\.renderer\.forceContextLoss\(\)/);
+ expect(engine).toMatch(/addEventListener\("webglcontextlost"/);
+ });
+
+ it("the full-screen panel takes focus only when the user chose 'Look around in 3D', so the arrow keys keep browsing", () => {
+ const panel = read("src/components/studio/result-media.tsx");
+ const tag = panel.match(/<SplatViewer[^>]*\/>/)![0];
+ expect(tag).toMatch(/autoFocus=\{asked\}/);
+ // A dialog that focuses the stage on opening doesn't hand it ArrowLeft / ArrowRight (tests/e2e/splat-viewer.mjs checks it in a browser).
+ const viewer = read("src/components/model3d/splat-viewer.tsx");
+ expect(viewer).toMatch(/if \(!engaged\.current && \(e\.key === "ArrowLeft" \|\| e\.key === "ArrowRight"\)\) return;/);
+ });
+});