Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Cinema 3D scene: read Marigold's colour-mapped depth maps

Claudee3968570905e
diff --git a/src/lib/scene3d.ts b/src/lib/scene3d.ts
index 147980f7..ba1f98a6 100644
--- a/src/lib/scene3d.ts
+++ b/src/lib/scene3d.ts
@@ -239,7 +239,7 @@ export interface PointCloudOptions {
hFov: number;
/** At most this many points (the sampling stride follows). */
maxPoints?: number;
- /** Depth maps differ: bright = near (disparity) or dark = near (depth). Undefined = read it from the map. */
+ /** Grey depth maps differ: bright = near (disparity) or dark = near (depth). Undefined = read it from the map. */
nearIsBright?: boolean;
/** Distance of the nearest and the farthest points (scene units ≈ metres). */
near?: number;
@@ -259,24 +259,136 @@ export interface PointCloud {
stride: number;
/** Median distance (the orbit pivot). */
depth: number;
+ /** How the depth map was painted. */
+ encoding: "grey" | "spectral";
}
-/** Bilinear grey value (0–1, the red channel) of a depth map at normalised (u, v). */
-function greyAt(px: Pixels, u: number, v: number): number {
- const x = clamp(u * px.width - 0.5, 0, px.width - 1);
- const y = clamp(v * px.height - 0.5, 0, px.height - 1);
+/**
+ * Matplotlib's "Spectral" colour map, ColorBrewer's 11 stops evenly spaced from 0 to 1. Marigold paints its depth
+ * maps with it (fal-ai/marigold-v2 returns this "colorized depth map", not grey): dark red is near, then orange,
+ * yellow, green and blue, to violet far away.
+ */
+export const SPECTRAL: readonly (readonly [number, number, number])[] = [
+ [158, 1, 66],
+ [213, 62, 79],
+ [244, 109, 67],
+ [253, 174, 97],
+ [254, 224, 139],
+ [255, 255, 191],
+ [230, 245, 152],
+ [171, 221, 164],
+ [102, 194, 165],
+ [50, 136, 189],
+ [94, 79, 162],
+];
+
+/** The Spectral colour at t (0–1), as 0–255 RGB. */
+export function spectralColor(t: number): [number, number, number] {
+ const x = clamp(t, 0, 1) * (SPECTRAL.length - 1);
+ const i = Math.min(SPECTRAL.length - 2, Math.floor(x));
+ const f = x - i;
+ const [a, b] = [SPECTRAL[i], SPECTRAL[i + 1]];
+ return [0, 1, 2].map((k) => Math.round(a[k] + (b[k] - a[k]) * f)) as [number, number, number];
+}
+
+/** Where a colour sits along the Spectral map: t (0–1) of the nearest point on it, and how far off it is (0–255 units). */
+export function spectralValue(r: number, g: number, b: number): { t: number; off: number } {
+ let best = Infinity;
+ let t = 0;
+ for (let i = 0; i < SPECTRAL.length - 1; i++) {
+ const a = SPECTRAL[i];
+ const d = [SPECTRAL[i + 1][0] - a[0], SPECTRAL[i + 1][1] - a[1], SPECTRAL[i + 1][2] - a[2]];
+ const q = [r - a[0], g - a[1], b - a[2]];
+ const u = clamp((q[0] * d[0] + q[1] * d[1] + q[2] * d[2]) / (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]), 0, 1);
+ const e = (q[0] - u * d[0]) ** 2 + (q[1] - u * d[1]) ** 2 + (q[2] - u * d[2]) ** 2;
+ if (e < best) {
+ best = e;
+ t = (i + u) / (SPECTRAL.length - 1);
+ }
+ }
+ return { t, off: Math.sqrt(best) };
+}
+
+/** A grey value 0–1 (luma, so a grey map reads the same on every channel). */
+const lumaAt = (data: ArrayLike<number>, o: number) => (0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2]) / 255;
+
+/**
+ * How a depth map is painted: "grey" (one value per pixel, either way round), or "spectral" (Marigold's colour map).
+ * A map whose pixels carry colour and sit on the Spectral curve is Spectral; any other colour falls back to its grey.
+ */
+export function depthEncoding(depth: Pixels): "grey" | "spectral" {
+ const n = depth.width * depth.height;
+ const step = Math.max(1, Math.floor(n / 4096));
+ let spread = 0;
+ let off = 0;
+ let seen = 0;
+ for (let i = 0; i < n; i += step) {
+ const o = i * 4;
+ const [r, g, b] = [depth.data[o], depth.data[o + 1], depth.data[o + 2]];
+ spread += Math.max(r, g, b) - Math.min(r, g, b);
+ off += spectralValue(r, g, b).off;
+ seen++;
+ }
+ return seen && spread / seen > 16 && off / seen < 12 ? "spectral" : "grey";
+}
+
+/** A depth map read into nearness: 0 (far) … 1 (near) per pixel. */
+export interface DepthField {
+ width: number;
+ height: number;
+ nearness: Float32Array;
+ /** Bright-near grey maps are disparity (1/z, as Depth Anything's); dark-near grey and Marigold's maps are depth (z). */
+ disparity: boolean;
+ encoding: "grey" | "spectral";
+}
+
+/**
+ * Decode a depth map. Spectral maps (Marigold) are inverted along the colour map: red is near, so no guess is
+ * needed. Grey maps run the way `nearIsBright` says, or the way the map itself shows (see nearIsBright).
+ */
+export function readDepth(depth: Pixels, brightNear?: boolean): DepthField {
+ const { width, height, data } = depth;
+ const nearness = new Float32Array(width * height);
+ const encoding = depthEncoding(depth);
+ if (encoding === "spectral") {
+ // Each colour is looked up once: a depth map has far fewer colours than pixels.
+ const seen = new Map<number, number>();
+ for (let i = 0; i < nearness.length; i++) {
+ const o = i * 4;
+ const key = (data[o] << 16) | (data[o + 1] << 8) | data[o + 2];
+ let v = seen.get(key);
+ if (v === undefined) {
+ v = 1 - spectralValue(data[o], data[o + 1], data[o + 2]).t;
+ seen.set(key, v);
+ }
+ nearness[i] = v;
+ }
+ return { width, height, nearness, disparity: false, encoding };
+ }
+ const bright = brightNear ?? nearIsBright(depth);
+ for (let i = 0; i < nearness.length; i++) {
+ const g = lumaAt(data, i * 4);
+ nearness[i] = bright ? g : 1 - g;
+ }
+ return { width, height, nearness, disparity: bright, encoding };
+}
+
+/** Bilinear nearness of a decoded depth map at normalised (u, v). */
+function nearnessAt(f: DepthField, u: number, v: number): number {
+ const x = clamp(u * f.width - 0.5, 0, f.width - 1);
+ const y = clamp(v * f.height - 0.5, 0, f.height - 1);
const x0 = Math.floor(x);
const y0 = Math.floor(y);
- const x1 = Math.min(px.width - 1, x0 + 1);
- const y1 = Math.min(px.height - 1, y0 + 1);
- const g = (xx: number, yy: number) => px.data[(yy * px.width + xx) * 4];
+ const x1 = Math.min(f.width - 1, x0 + 1);
+ const y1 = Math.min(f.height - 1, y0 + 1);
+ const g = (xx: number, yy: number) => f.nearness[yy * f.width + xx];
const fx = x - x0;
const fy = y - y0;
- return ((g(x0, y0) * (1 - fx) + g(x1, y0) * fx) * (1 - fy) + (g(x0, y1) * (1 - fx) + g(x1, y1) * fx) * fy) / 255;
+ return (g(x0, y0) * (1 - fx) + g(x1, y0) * fx) * (1 - fy) + (g(x0, y1) * (1 - fx) + g(x1, y1) * fx) * fy;
}
/**
- * Which way a depth map runs: in a photo the bottom of the frame (the floor, the street) is nearly always nearer
+ * Which way a grey depth map runs: in a photo the bottom of the frame (the floor, the street) is nearly always nearer
* than the top, so the map is "bright = near" when its bottom quarter is brighter than its top quarter.
*/
export function nearIsBright(depth: Pixels): boolean {
@@ -286,7 +398,7 @@ export function nearIsBright(depth: Pixels): boolean {
let n = 0;
for (let y = y0; y < y0 + band; y++)
for (let x = 0; x < depth.width; x += Math.max(1, Math.floor(depth.width / 64))) {
- s += depth.data[(y * depth.width + x) * 4];
+ s += lumaAt(depth.data, (y * depth.width + x) * 4);
n++;
}
return s / Math.max(1, n);
@@ -296,15 +408,15 @@ export function nearIsBright(depth: Pixels): boolean {
/**
* The photo as points: every `stride`-th pixel, pushed back to its distance along its own ray from the origin.
- * Bright-near maps are read as disparity (1/z), dark-near maps as depth (z), each spread between the map's 1st and
- * 99th percentile so every map fills the near–far range.
+ * Bright-near grey maps are read as disparity (1/z); dark-near grey maps and Marigold's Spectral maps as depth (z).
+ * Each is spread between the map's 1st and 99th percentile so every map fills the near–far range.
*/
export function buildPointCloud(photo: Pixels, depthMap: Pixels, opts: PointCloudOptions): PointCloud {
const W = photo.width;
const H = photo.height;
const near = opts.near ?? 1;
const far = Math.max(near * 1.05, opts.far ?? 6);
- const bright = opts.nearIsBright ?? nearIsBright(depthMap);
+ const field = readDepth(depthMap, opts.nearIsBright);
const stride = Math.max(1, Math.ceil(Math.sqrt((W * H) / Math.max(1, opts.maxPoints ?? 300_000))));
const cols = Math.ceil(W / stride);
const rows = Math.ceil(H / stride);
@@ -313,8 +425,7 @@ export function buildPointCloud(photo: Pixels, depthMap: Pixels, opts: PointClou
const nearness = new Float32Array(cols * rows);
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) {
- const g = greyAt(depthMap, (Math.min(W - 1, c * stride) + 0.5) / W, (Math.min(H - 1, r * stride) + 0.5) / H);
- nearness[r * cols + c] = bright ? g : 1 - g;
+ nearness[r * cols + c] = nearnessAt(field, (Math.min(W - 1, c * stride) + 0.5) / W, (Math.min(H - 1, r * stride) + 0.5) / H);
}
const sorted = Float32Array.from(nearness).sort();
const lo = sorted[Math.floor(sorted.length * 0.01)];
@@ -323,7 +434,7 @@ export function buildPointCloud(photo: Pixels, depthMap: Pixels, opts: PointClou
const z = new Float32Array(cols * rows);
for (let i = 0; i < z.length; i++) {
const s = clamp((nearness[i] - lo) / span, 0, 1);
- z[i] = bright ? 1 / (1 / far + s * (1 / near - 1 / far)) : far - s * (far - near);
+ z[i] = field.disparity ? 1 / (1 / far + s * (1 / near - 1 / far)) : far - s * (far - near);
}
const fx = W / 2 / Math.tan(clamp(opts.hFov, 1, 179) * DEG * 0.5);
@@ -374,7 +485,7 @@ export function buildPointCloud(photo: Pixels, depthMap: Pixels, opts: PointClou
colors[i * 3 + 2] = photo.data[o + 2] / 255;
sizes[i] = ((stride * d) / fx) * 1.5;
}
- return { positions, colors, sizes, count, stride, depth: medianDepth(positions) };
+ return { positions, colors, sizes, count, stride, depth: medianDepth(positions), encoding: field.encoding };
}
/** Whether sample i is the nearest or the farthest of itself and its four neighbours (a side of an edge). */
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 8d169340..a2c4d6c1 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -2,6 +2,7 @@ import "server-only";
import { nanoid } from "nanoid";
import { cueText, parseCues, type Cue } from "@/lib/cues";
import { OPERATION_OUTPUT, type MediaKind, type Operation } from "@/lib/catalog/types";
+import { spectralColor } from "@/lib/scene3d";
import type { ProviderAdapter, RemoteOutput } from "./types";
import { textOutput } from "./llm";
import { encodePng } from "../png";
@@ -232,10 +233,11 @@ function demoOcr(brief: string): DemoOutput {
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Number.isFinite(n) ? n : lo));
/**
- * A depth map like a depth model's PNG (bright = near), 512 px wide in the request's shape: a back wall, a
- * floor that comes closer toward the bottom of the frame and three rounded subjects standing on it.
+ * A depth map like a depth model's PNG, 512 px wide in the request's shape: a back wall, a floor that comes closer
+ * toward the bottom of the frame and three rounded subjects standing on it. Grey (bright = near) like MoGe's on the
+ * open engine; painted with the Spectral colour map (red = near) like Marigold's on the cloud.
*/
-function demoDepth(prompt: string, aspectRatio: string): DemoOutput {
+function demoDepth(prompt: string, aspectRatio: string, spectral: boolean): DemoOutput {
const { w: cw, h: ch } = canvas(aspectRatio);
const w = 512;
const h = Math.max(16, Math.round((w * ch) / cw));
@@ -251,8 +253,9 @@ function demoDepth(prompt: string, aspectRatio: string): DemoOutput {
const d = ((u - b.x) / b.rx) ** 2 + ((v - b.y) / b.ry) ** 2;
if (d < 1) near = Math.max(near, b.near + 0.08 * Math.sqrt(1 - d));
}
- const g = Math.round(clamp(near, 0, 1) * 255);
- data.set([g, g, g, 255], (y * w + x) * 4);
+ const n = clamp(near, 0, 1);
+ const g = Math.round(n * 255);
+ data.set(spectral ? [...spectralColor(1 - n), 255] : [g, g, g, 255], (y * w + x) * 4);
}
return { url: toDataUri(encodePng({ width: w, height: h, data }), "image/png"), kind: "image", contentType: "image/png", meta: { role: "depth", demo: true } };
}
@@ -294,7 +297,7 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
// Round 4. A splat and a rig come back as the demo mesh (a real splat is a .ply or .spz). A scene is the
// mesh and its depth map on the open engine (MoGe), the depth map alone on the cloud (Marigold).
case "scene-3d": {
- const depth = demoDepth(brief, ar);
+ const depth = demoDepth(brief, ar, kind === "image");
if (kind === "image") return [depth];
return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", scene: true, role: "scene" } }, depth];
}
diff --git a/tests/scene3d-provider.test.ts b/tests/scene3d-provider.test.ts
index 80b44901..9917d155 100644
--- a/tests/scene3d-provider.test.ts
+++ b/tests/scene3d-provider.test.ts
@@ -17,6 +17,7 @@ const { buildPayload, extractOutputs } = await import("@/lib/catalog/payload");
const { outputKind } = await import("@/server/generations");
const { mockProvider } = await import("@/server/providers/mock");
const { decodePng } = await import("@/server/png");
+const { buildPointCloud, depthEncoding } = await import("@/lib/scene3d");
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -156,22 +157,33 @@ describe("demo mode", () => {
return res.outputs;
}
- it("makes a 16:9 depth map (bright = near, the floor closest at the bottom) for the cloud", async () => {
+ const png = (o: { url: string }) => decodePng(Buffer.from(o.url.split(",")[1], "base64"));
+
+ it("makes a 16:9 depth map painted like Marigold's (Spectral, red = near) that the point cloud reads the right way round", async () => {
const outs = await demo(getModel("marigold-depth")!);
expect(outs).toHaveLength(1);
expect(outs[0]).toMatchObject({ kind: "image", contentType: "image/png", meta: { role: "depth", demo: true } });
- const png = decodePng(Buffer.from(outs[0].url.split(",")[1], "base64"));
- expect(png.width).toBe(512);
- expect(png.height).toBe(288);
- const grey = (x: number, y: number) => png.data[(y * png.width + x) * 4];
- expect(grey(4, png.height - 1)).toBeGreaterThan(grey(4, 0) + 100);
+ const map = png(outs[0]);
+ expect(map.width).toBe(512);
+ expect(map.height).toBe(288);
+ expect(depthEncoding(map)).toBe("spectral");
+ // The floor nearest at the bottom, the wall far at the top.
+ const photo = { width: 64, height: 36, data: new Uint8ClampedArray(64 * 36 * 4).fill(128) };
+ const cloud = buildPointCloud(photo, map, { hFov: 74, near: 1, far: 6 });
+ const z = (x: number, y: number) => -cloud.positions[(y * 64 + x) * 3 + 2];
+ expect(z(4, 35)).toBeLessThan(1.5);
+ expect(z(4, 0)).toBeGreaterThan(5);
});
- it("makes the demo mesh and its depth map for the open engine", async () => {
+ it("makes the demo mesh and its grey depth map (bright = near) for the open engine", async () => {
const outs = await demo(getModel("oss-scene-moge")!);
expect(outs.map((o) => [o.kind, o.meta?.role])).toEqual([
["model3d", "scene"],
["image", "depth"],
]);
+ const map = png(outs[1]);
+ expect(depthEncoding(map)).toBe("grey");
+ const grey = (x: number, y: number) => map.data[(y * map.width + x) * 4];
+ expect(grey(4, map.height - 1)).toBeGreaterThan(grey(4, 0) + 100);
});
});
diff --git a/tests/scene3d.test.ts b/tests/scene3d.test.ts
index d163825b..d3acffd3 100644
--- a/tests/scene3d.test.ts
+++ b/tests/scene3d.test.ts
@@ -16,13 +16,17 @@ import {
lensFov,
lookStep,
medianDepth,
+ depthEncoding,
nearIsBright,
objectStart,
poseWords,
ratioOf,
+ readDepth,
recomposePrompt,
sceneFov,
scenePose,
+ spectralColor,
+ spectralValue,
strafe,
twoFinger,
type FlyPose,
@@ -196,6 +200,64 @@ describe("point cloud from a photo and a depth map", () => {
});
});
+describe("Marigold's colour-mapped depth (Spectral: red near, violet far)", () => {
+ it("inverts the colour map", () => {
+ expect(spectralColor(0)).toEqual([158, 1, 66]);
+ expect(spectralColor(0.5)).toEqual([255, 255, 191]);
+ expect(spectralColor(1)).toEqual([94, 79, 162]);
+ for (const t of [0, 0.03, 0.25, 0.5, 0.61, 0.9, 1]) {
+ const v = spectralValue(...spectralColor(t));
+ expect(v.t).toBeCloseTo(t, 2);
+ expect(v.off).toBeLessThan(1);
+ }
+ // Colours read off fal's example output (a dog on a bench): the dog, the bench, the grass, the sky.
+ expect(spectralValue(168, 11, 69).t).toBeLessThan(0.05);
+ expect(spectralValue(247, 139, 81).t).toBeCloseTo(0.25, 1);
+ expect(spectralValue(231, 244, 152).t).toBeCloseTo(0.6, 1);
+ expect(spectralValue(44, 139, 183).t).toBeGreaterThan(0.85);
+ });
+
+ // Near at the bottom (red), far at the top (violet), as Marigold paints a photo with a floor.
+ const spectralMap = pixels(20, 10, (_x, y) => spectralColor(1 - y / 9));
+
+ it("tells a Spectral map from a grey one", () => {
+ expect(depthEncoding(spectralMap)).toBe("spectral");
+ expect(depthEncoding(pixels(20, 10, (_x, y) => [y * 20, y * 20, y * 20]))).toBe("grey");
+ // Colour that isn't on the Spectral curve is read by its grey.
+ expect(depthEncoding(pixels(20, 10, (x) => (x % 2 ? [255, 0, 0] : [0, 0, 255])))).toBe("grey");
+ });
+
+ it("reads red as near, as depth (not disparity), whatever the grey guess would say", () => {
+ const field = readDepth(spectralMap);
+ expect(field).toMatchObject({ encoding: "spectral", disparity: false });
+ expect(field.nearness[9 * 20]).toBeCloseTo(1, 2);
+ expect(field.nearness[0]).toBeCloseTo(0, 2);
+ // The red channel alone rises and falls along the map: read as grey, the bottom and the middle would clash.
+ expect(spectralColor(0)[0]).toBeLessThan(spectralColor(0.4)[0]);
+ expect(spectralColor(0.4)[0]).toBeGreaterThan(spectralColor(1)[0]);
+ const photo = pixels(40, 20, () => [128, 128, 128]);
+ const cloud = buildPointCloud(photo, spectralMap, { hFov: 60, near: 1, far: 5, edge: 0 });
+ expect(cloud.encoding).toBe("spectral");
+ const z = (x: number, y: number) => -cloud.positions[(y * 40 + x) * 3 + 2];
+ expect(z(5, 19)).toBeCloseTo(1, 1);
+ expect(z(5, 0)).toBeCloseTo(5, 1);
+ // Linear in depth: halfway down the map is halfway between near and far.
+ const mid = buildPointCloud(photo, pixels(20, 3, (_x, y) => spectralColor([1, 0.5, 0][y])), { hFov: 60, near: 1, far: 5, edge: 0 });
+ expect(-mid.positions[(10 * 40 + 5) * 3 + 2]).toBeCloseTo(3, 0);
+ });
+
+ it("keeps reading grey maps either way round", () => {
+ const grey = pixels(20, 10, (_x, y) => {
+ const g = Math.round((y / 9) * 255);
+ return [g, g, g];
+ });
+ expect(readDepth(grey)).toMatchObject({ encoding: "grey", disparity: true });
+ expect(readDepth(grey, false)).toMatchObject({ encoding: "grey", disparity: false });
+ expect(readDepth(grey).nearness[9 * 20]).toBeCloseTo(1, 5);
+ expect(readDepth(grey, false).nearness[9 * 20]).toBeCloseTo(0, 5);
+ });
+});
+
describe("depth of field and focus", () => {
it("blurs like a thin lens: more with a longer lens, a wider aperture and a closer focus", () => {
const a = blurScale(50, 1.4, 2, 3 / 2);