Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add per-run render options and solid-background keying to image-to-3D (#4657)

[._.]/ Adam Eivy2086e550e9ff
diff --git a/client/src/components/media/ImageTo3dRenderOptions.jsx b/client/src/components/media/ImageTo3dRenderOptions.jsx
new file mode 100644
index 0000000000..d529ee5e07
--- /dev/null
+++ b/client/src/components/media/ImageTo3dRenderOptions.jsx
@@ -0,0 +1,83 @@
+import FormField from '../ui/FormField';
+import { SEED_MAX, STEPS_PRESETS } from '../../lib/imageTo3dRenderOptions';
+
+// Per-run sampler knobs for image-to-3D generation, shared by the /3d
+// workspace and the /3d/:id detail page. Controlled, with per-field props
+// (the documented convention for knob grids — see ImageGenControls.jsx).
+// Image-to-3D-specific by design: the presets bake in TRELLIS.2's 12-step
+// default and the keying toggle has no analogue in image/video gen.
+//
+// Value conventions (see lib/imageTo3dRenderOptions.js for the body mapping):
+// - steps: '' = pipeline default, else a preset number string.
+// - seed: '' = a fresh random seed every render; a value pins this run.
+// - keyBackground: key a solid-color backdrop to transparency before render.
+
+const FIELD_LABEL_CLASS = 'mb-1 block text-xs text-gray-400';
+const FIELD_INPUT_CLASS = 'w-full rounded-md border border-port-border bg-port-bg px-2 py-1.5 text-xs text-gray-200 disabled:opacity-40';
+
+export default function ImageTo3dRenderOptions({
+ steps,
+ onStepsChange,
+ seed,
+ onSeedChange,
+ keyBackground,
+ onKeyBackgroundChange,
+ disabled = false,
+}) {
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="grid gap-3 sm:grid-cols-3">
+ <FormField label="Quality" labelClassName={FIELD_LABEL_CLASS}>
+ <select
+ value={steps}
+ onChange={(e) => onStepsChange(e.target.value)}
+ disabled={disabled}
+ className={FIELD_INPUT_CLASS}
+ >
+ {STEPS_PRESETS.map((preset) => (
+ <option key={preset.value || 'default'} value={preset.value}>{preset.label}</option>
+ ))}
+ {/* A run can carry a non-preset steps value (set via the API) — surface it
+ rather than silently snapping the select to the default. */}
+ {steps !== '' && !STEPS_PRESETS.some((preset) => preset.value === steps) && (
+ <option value={steps}>{`Custom (${steps} steps)`}</option>
+ )}
+ </select>
+ </FormField>
+ <FormField label="Seed" labelClassName={FIELD_LABEL_CLASS}>
+ <input
+ type="number"
+ inputMode="numeric"
+ min={0}
+ max={SEED_MAX}
+ step={1}
+ value={seed}
+ onChange={(e) => onSeedChange(e.target.value)}
+ placeholder="Random each render"
+ disabled={disabled}
+ className={`${FIELD_INPUT_CLASS} placeholder:text-gray-600`}
+ />
+ </FormField>
+ <div className="flex items-end pb-1.5">
+ <label className="inline-flex cursor-pointer items-center gap-2 text-xs text-gray-300">
+ <input
+ type="checkbox"
+ checked={keyBackground}
+ onChange={(e) => onKeyBackgroundChange(e.target.checked)}
+ disabled={disabled}
+ className="h-3.5 w-3.5 rounded border-port-border bg-port-bg accent-port-accent disabled:opacity-40"
+ />
+ Key out solid background
+ </label>
+ </div>
+ </div>
+ <p className="text-xs leading-relaxed text-gray-500">
+ <span className="font-medium text-gray-400">Best source images:</span> one subject,
+ front or ¾ view, filling the frame, with no parts hidden behind others (tails, wings,
+ props) — the model has to guess anything it can’t see. A transparent PNG is used as-is;
+ a solid-color backdrop is keyed out automatically when enabled here; busy backgrounds
+ fall back to automatic matting, which can leave soft edges.
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 7621c29d05..93a57d4165 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -65,6 +65,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. |
| `imageGenResolutions.js` | Shared resolution presets for image generation. |
| `imageTo3dReasons.js` | Client mirror of the image-to-3D unavailable-reason labels in `server/services/imageTo3d/targets.js`: `UNAVAILABLE_REASONS` (reason code → user-facing label), `UNAVAILABLE_REASON_FALLBACK`, and `unavailableReasonLabel(code, fallback?)`. Use this anywhere a target's `unavailableReason` is rendered — never re-declare the codes. Parity + code coverage enforced by `server/services/imageTo3d/unavailableReasons.parity.test.js`. |
+| `imageTo3dRenderOptions.js` | Pure helpers for the image-to-3D per-run render options: `SEED_MAX` (client mirror of the server's `RENDER_SEED_MAX`, parity-pinned by `server/services/imageTo3d/renderOptions.parity.test.js`), `STEPS_PRESETS`, `renderOptionsBody(fields)` (field state → request body, unset keys omitted), and `fieldsFromRun(run)` (latest run → field state; seed stays blank so re-renders keep rolling fresh seeds). |
| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. |
| `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. |
| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |
diff --git a/client/src/lib/imageTo3dRenderOptions.js b/client/src/lib/imageTo3dRenderOptions.js
new file mode 100644
index 0000000000..c3b4016d03
--- /dev/null
+++ b/client/src/lib/imageTo3dRenderOptions.js
@@ -0,0 +1,54 @@
+/**
+ * Pure helpers for the image-to-3D per-run render options (steps / seed /
+ * background keying) — the client mirror of the server's accepted bounds.
+ *
+ * `SEED_MAX` is a hand-maintained mirror of the server's `RENDER_SEED_MAX`
+ * (`server/services/imageTo3d/renderOptions.js`) pinned by
+ * `server/services/imageTo3d/renderOptions.parity.test.js` — same mechanism as
+ * `imageTo3dReasons.js`. It is deliberately narrower than the image/video-gen
+ * `MAX_SEED` in `genUtils.js`: TRELLIS.2 hands seeds to torch generators, which
+ * reject values above int32.
+ *
+ * Kept free of React so the server-side parity suite (node runner, no JSX) can
+ * import it directly.
+ */
+
+export const SEED_MAX = 2147483647;
+
+/** The steps presets: the pipeline's own default, and two slower/higher-detail
+ * tiers. Values stay strings because they live in <select> state. */
+export const STEPS_PRESETS = [
+ { value: '', label: 'Standard (12 steps)' },
+ { value: '24', label: 'High (24 steps — ~2× slower)' },
+ { value: '48', label: 'Max (48 steps — ~4× slower)' },
+];
+
+/**
+ * Convert the option fields' string state into the API's per-run body. Unset
+ * fields are OMITTED (not null): absent steps → the pipeline default, absent
+ * seed → the server rolls a fresh random one for that run. Range/int validation
+ * is the server's job — the route 400s with a readable message.
+ */
+export function renderOptionsBody({ steps, seed, keyBackground }) {
+ return {
+ ...(steps !== '' && { steps: Number(steps) }),
+ ...(seed !== '' && { seed: Number(seed) }),
+ keyBackground,
+ };
+}
+
+/**
+ * Derive the option fields' initial state from a record's latest run entry.
+ * `steps` and `keyBackground` carry over (they're safe to inherit); `seed` is
+ * ALWAYS blank — seeding the field from the run's concrete (randomly rolled)
+ * seed would silently pin it, reintroducing the deterministic-re-render trap
+ * this feature exists to fix. A user pins a seed by typing one deliberately
+ * (the run's seed is displayed in the meta line to copy from).
+ */
+export function fieldsFromRun(run) {
+ return {
+ steps: Number.isInteger(run?.steps) ? String(run.steps) : '',
+ seed: '',
+ keyBackground: typeof run?.keyBackground === 'boolean' ? run.keyBackground : true,
+ };
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 3ef1ffdfde..e72a125691 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -35,6 +35,7 @@ export * as imageGenModes from './imageGenModes.js';
export * from './imageGenDefaults.js';
export * from './imageGenResolutions.js';
export * from './imageTo3dReasons.js';
+export * from './imageTo3dRenderOptions.js';
export * from './importerDeepLink.js';
export * from './letteringDensity.js';
export * from './issueLength.js';
diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsx
index 99d8aab043..720605eee3 100644
--- a/client/src/pages/Media3D.jsx
+++ b/client/src/pages/Media3D.jsx
@@ -13,6 +13,8 @@ import { useHfTokenStatus } from '../hooks/useHfTokenStatus';
import useUrlParams from '../hooks/useUrlParams';
import MediaImage from '../components/MediaImage';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
+import ImageTo3dRenderOptions from '../components/media/ImageTo3dRenderOptions';
+import { renderOptionsBody } from '../lib/imageTo3dRenderOptions';
import { unavailableReasonLabel } from '../lib/imageTo3dReasons';
// Poll cadence while a render is in flight (a real TRELLIS.2 render is multi-minute).
@@ -192,6 +194,10 @@ export default function Media3D() {
const [genError, setGenError] = useState(null);
const [genPercent, setGenPercent] = useState(null);
const [modelId, setModelId] = useState(null);
+ // Per-run sampler knobs (see ImageTo3dRenderOptions for the value conventions).
+ const [steps, setSteps] = useState('');
+ const [seed, setSeed] = useState('');
+ const [keyBackground, setKeyBackground] = useState(true);
// Existing image-to-3D records (newest-first) so the page doubles as a library:
// each links to its `/3d/:id` detail view.
const [records, setRecords] = useState([]);
@@ -284,14 +290,19 @@ export default function Media3D() {
setGenError(null); setGenPercent(0); setModelId(null);
updateParams({ glb: '' }); // clear any previously-previewed mesh
const created = await createImageTo3dModel(
- { name: nameFromImageFilename(selectedImage.filename), filename: selectedImage.filename, target: selectedTarget.id },
+ {
+ name: nameFromImageFilename(selectedImage.filename),
+ filename: selectedImage.filename,
+ target: selectedTarget.id,
+ ...renderOptionsBody({ steps, seed, keyBackground }),
+ },
{ silent: true },
).catch((err) => {
if (mountedRef.current) setGenError(err?.message || 'Could not start the render.');
return null;
});
if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); patchRecord(created); }
- }, [selectedImage, selectedTarget, updateParams, mountedRef, patchRecord]);
+ }, [selectedImage, selectedTarget, steps, seed, keyBackground, updateParams, mountedRef, patchRecord]);
// Why the Generate action is blocked, or null when it's ready to run. The runner
// (POST create → on-device render → landed .glb) is wired, so the terminal state
@@ -383,6 +394,16 @@ export default function Media3D() {
/>
)}
+ <ImageTo3dRenderOptions
+ steps={steps}
+ onStepsChange={setSteps}
+ seed={seed}
+ onSeedChange={setSeed}
+ keyBackground={keyBackground}
+ onKeyBackgroundChange={setKeyBackground}
+ disabled={generating}
+ />
+
<div className="mt-auto flex flex-col items-start gap-2">
<button
type="button"
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index 7b78afa227..c6f91876ae 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { ArrowLeft, Boxes, AlertTriangle, Loader2, RefreshCw, Trash2 } from 'lucide-react';
import { getImageTo3dModel, generateImageTo3dModel, deleteImageTo3dModel, imageTo3dAssetUrl } from '../services/api';
@@ -8,6 +8,8 @@ import { timeAgo } from '../utils/formatters';
import GlbViewer from '../components/media/GlbViewer';
import MediaImage from '../components/MediaImage';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import ImageTo3dRenderOptions from '../components/media/ImageTo3dRenderOptions';
+import { fieldsFromRun, renderOptionsBody } from '../lib/imageTo3dRenderOptions';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
import toast from '../components/ui/Toast';
@@ -27,6 +29,13 @@ export default function Media3DDetail() {
const [notFound, setNotFound] = useState(false);
const [busy, setBusy] = useState(false);
const [confirmingDelete, setConfirmingDelete] = useState(false);
+ // Per-run knobs, seeded from the latest run once per id (NOT on every poll
+ // tick — that would clobber in-progress edits). Seed stays blank by design:
+ // see fieldsFromRun.
+ const [steps, setSteps] = useState('');
+ const [seed, setSeed] = useState('');
+ const [keyBackground, setKeyBackground] = useState(true);
+ const optionsSeededFor = useRef(null);
const load = useCallback(async ({ initial = false } = {}) => {
const next = await getImageTo3dModel(id, { silent: true }).catch((err) => {
@@ -57,16 +66,30 @@ export default function Media3DDetail() {
enabled: !notFound && record?.status === 'generating',
});
+ // Seed the option fields from the latest run once per id.
+ useEffect(() => {
+ if (!record || optionsSeededFor.current === record.id) return;
+ optionsSeededFor.current = record.id;
+ const fields = fieldsFromRun(record.runs?.at?.(-1));
+ setSteps(fields.steps);
+ setSeed(fields.seed);
+ setKeyBackground(fields.keyBackground);
+ }, [record]);
+
const handleRegenerate = useCallback(async () => {
if (busy || record?.status === 'generating') return;
setBusy(true);
- const next = await generateImageTo3dModel(id, { silent: true }).catch((err) => {
+ const next = await generateImageTo3dModel(
+ id,
+ renderOptionsBody({ steps, seed, keyBackground }),
+ { silent: true },
+ ).catch((err) => {
toast.error(err?.message || 'Could not start the render.');
return null;
});
if (mountedRef.current) setBusy(false);
if (next && mountedRef.current) setRecord(next);
- }, [busy, record?.status, id, mountedRef]);
+ }, [busy, record?.status, id, steps, seed, keyBackground, mountedRef]);
const handleDelete = useCallback(async () => {
const ok = await deleteImageTo3dModel(id, { silent: true }).then(() => true).catch((err) => {
@@ -136,10 +159,26 @@ export default function Media3DDetail() {
</div>
<p className="mt-1 text-xs text-gray-500">
{imageTo3dStatusMeta(record.status).label}
- {isGenerating && percent !== null ? ` · ${percent}%` : ''} · updated {timeAgo(record.updatedAt)}
+ {isGenerating && percent !== null ? ` · ${percent}%` : ''}
+ {Number.isInteger(latestRun?.seed) ? ` · seed ${latestRun.seed}` : ''}
+ {Number.isInteger(latestRun?.steps) ? ` · ${latestRun.steps} steps` : ''}
+ {latestRun?.sourceKeyed ? ' · background keyed' : ''}
+ {' '}· updated {timeAgo(record.updatedAt)}
</p>
</header>
+ <div className="mb-4 rounded-lg border border-port-border bg-port-card p-3">
+ <ImageTo3dRenderOptions
+ steps={steps}
+ onStepsChange={setSteps}
+ seed={seed}
+ onSeedChange={setSeed}
+ keyBackground={keyBackground}
+ onKeyBackgroundChange={setKeyBackground}
+ disabled={busy || isGenerating}
+ />
+ </div>
+
{confirmingDelete && (
<InlineConfirmRow
className="mb-4"
diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
index 39212ada3c..37ce9b26fa 100644
--- a/client/src/pages/Media3DDetail.test.jsx
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -83,4 +83,55 @@ describe('Media3DDetail', () => {
await waitFor(() => expect(deleteImageTo3dModel).toHaveBeenCalledWith('image3d-1', { silent: true }));
expect(await screen.findByText('3D index')).toBeInTheDocument();
});
+
+ it('re-render sends the chosen per-run options (blank seed omitted → server rolls fresh)', async () => {
+ getImageTo3dModel.mockResolvedValue(record());
+ generateImageTo3dModel.mockResolvedValue(record({ status: 'generating' }));
+ renderAt();
+ await screen.findByText('Example Beacon');
+
+ fireEvent.change(screen.getByLabelText(/quality/i), { target: { value: '24' } });
+ fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
+
+ await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
+ 'image3d-1',
+ { steps: 24, keyBackground: true },
+ { silent: true },
+ ));
+ });
+
+ it('seeds steps/keying from the latest run but leaves the seed blank (stays random)', async () => {
+ getImageTo3dModel.mockResolvedValue(record({
+ runs: [{ operationId: 'op-1', status: 'completed', percent: 100, steps: 48, seed: 1234, keyBackground: false }],
+ }));
+ generateImageTo3dModel.mockResolvedValue(record({ status: 'generating' }));
+ renderAt();
+ await screen.findByText('Example Beacon');
+
+ // The seeding effect commits one render after the record lands — wait for it.
+ await waitFor(() => expect(screen.getByLabelText(/quality/i)).toHaveValue('48'));
+ // Blank by design — echoing the run's concrete seed back would silently pin
+ // it, reintroducing the deterministic-re-render trap.
+ expect(screen.getByLabelText(/seed/i)).toHaveValue(null);
+ expect(screen.getByLabelText(/key out solid background/i)).not.toBeChecked();
+
+ fireEvent.click(screen.getByRole('button', { name: /re-render/i }));
+ await waitFor(() => expect(generateImageTo3dModel).toHaveBeenCalledWith(
+ 'image3d-1',
+ { steps: 48, keyBackground: false },
+ { silent: true },
+ ));
+ });
+
+ it('shows the latest run’s seed, steps, and keyed-background badge in the meta line', async () => {
+ getImageTo3dModel.mockResolvedValue(record({
+ runs: [{ operationId: 'op-1', status: 'completed', percent: 100, seed: 777, steps: 24, sourceKeyed: true }],
+ }));
+ renderAt();
+ await screen.findByText('Example Beacon');
+ // Scope to the meta paragraph — the quality <select> also mentions "24 steps".
+ const meta = screen.getByText(/seed 777/);
+ expect(meta.textContent).toContain('24 steps');
+ expect(meta.textContent).toContain('background keyed');
+ });
});
diff --git a/client/src/services/apiImageTo3d.js b/client/src/services/apiImageTo3d.js
index 9307ae4fed..80dade006c 100644
--- a/client/src/services/apiImageTo3d.js
+++ b/client/src/services/apiImageTo3d.js
@@ -21,9 +21,13 @@ export const createImageTo3dModel = (input, options) =>
});
// Re-run the render for an existing record (status → generating again).
-export const generateImageTo3dModel = (id, options) =>
+// `input` carries the optional per-run knobs ({ steps, seed, keyBackground }) —
+// they apply to this run only: absent steps → the pipeline default, absent
+// seed → the server rolls a fresh random one, absent keyBackground → enabled.
+export const generateImageTo3dModel = (id, input = {}, options) =>
request(`/image-to-3d/models/${encodeURIComponent(id)}/generate`, {
method: 'POST',
+ body: JSON.stringify(input),
...options,
});
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index c99fe493af..513cd7e5f4 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -20,6 +20,9 @@ import {
deleteModel,
getModelAsset,
} from '../services/imageTo3d/models.js';
+import {
+ RENDER_STEPS_MIN, RENDER_STEPS_MAX, RENDER_SEED_MAX,
+} from '../services/imageTo3d/renderOptions.js';
import { createInstallLogger } from '../lib/installLogger.js';
import { openSseStream } from '../lib/sseDownload.js';
@@ -28,11 +31,20 @@ const router = Router();
const galleryFilenameSchema = z.string().trim().min(1).max(256)
.regex(/^[^/\\]+\.(png|jpe?g|webp)$/i, 'filename must be a gallery image basename');
+// PER-RUN sampler knobs, shared by create and re-generate. Nothing persists
+// between runs: absent steps → the pipeline default, absent seed → a fresh
+// random roll for that run, absent keyBackground → keying enabled.
+const renderOptionsSchema = z.object({
+ steps: z.number().int().min(RENDER_STEPS_MIN).max(RENDER_STEPS_MAX).optional(),
+ seed: z.number().int().min(0).max(RENDER_SEED_MAX).optional(),
+ keyBackground: z.boolean().optional(),
+});
+
const createModelSchema = z.object({
name: z.string().trim().min(1).max(120),
filename: galleryFilenameSchema,
target: z.enum([...IMAGE_TO_3D_TARGET_IDS]).optional(),
-});
+}).extend(renderOptionsSchema.shape);
// Target ids with an install currently running — a rapid double-click would
// otherwise race two clone/setup processes against the same install dir.
@@ -279,7 +291,10 @@ router.get('/models/:id', asyncHandler(async (req, res) => {
}));
router.post('/models/:id/generate', asyncHandler(async (req, res) => {
- const model = await startGeneration(req.params.id);
+ // Re-render accepts the same per-run knobs as create; they apply to this run
+ // only and are recorded on its run entry.
+ const options = validateRequest(renderOptionsSchema, req.body ?? {});
+ const model = await startGeneration(req.params.id, { options });
res.status(202).json(model);
}));
diff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.js
index 7e8ab1ddfd..b41f21d7a4 100644
--- a/server/routes/imageTo3d.test.js
+++ b/server/routes/imageTo3d.test.js
@@ -371,7 +371,25 @@ describe('image-to-3d model records', () => {
models.startGeneration.mockResolvedValue({ id: 'image3d-1', status: 'generating' });
const res = await request(makeApp()).post('/api/image-to-3d/models/image3d-1/generate');
expect(res.status).toBe(202);
- expect(models.startGeneration).toHaveBeenCalledWith('image3d-1');
+ // A bodiless re-render forwards empty options — stored renderOptions apply.
+ expect(models.startGeneration).toHaveBeenCalledWith('image3d-1', { options: {} });
+ });
+
+ it('POST /models/:id/generate forwards per-run options and rejects invalid ones', async () => {
+ models.startGeneration.mockResolvedValue({ id: 'image3d-1', status: 'generating' });
+ const res = await request(makeApp())
+ .post('/api/image-to-3d/models/image3d-1/generate')
+ .send({ steps: 24, seed: 7, keyBackground: false });
+ expect(res.status).toBe(202);
+ expect(models.startGeneration).toHaveBeenCalledWith(
+ 'image3d-1',
+ { options: { steps: 24, seed: 7, keyBackground: false } },
+ );
+
+ const bad = await request(makeApp())
+ .post('/api/image-to-3d/models/image3d-1/generate')
+ .send({ steps: 999 });
+ expect(bad.status).toBe(400);
});
it('DELETE /models/:id soft-deletes', async () => {
diff --git a/server/services/imageTo3d/adapters.js b/server/services/imageTo3d/adapters.js
index ca6fdd4292..99716b96b2 100644
--- a/server/services/imageTo3d/adapters.js
+++ b/server/services/imageTo3d/adapters.js
@@ -24,8 +24,11 @@
* - `install({ onEvent, env })` — installs (or repairs, when the caller decides
* an already-installed target should re-run setup — see the route). Returns
* `{ promise, kill }`. Omit for a target with no install step.
- * - `run({ imagePath, outputPath, onProgress, env })` — renders; returns
- * `{ promise, kill }`, `promise` resolving `{ assetPath }`.
+ * - `run({ imagePath, outputPath, onProgress, env, caps, steps, seed })` —
+ * renders; returns `{ promise, kill }`, `promise` resolving `{ assetPath }`.
+ * `caps` is the host-capability snapshot resolved at the request boundary;
+ * `steps`/`seed` are the per-run sampler knobs (null = target default). A
+ * target may ignore any option key it doesn't understand.
* - `describeInstallState?()` — optional extra per-target diagnostics: async,
* returns `{ warnings?: string[], fields?: object }`. `warnings` are generic
* user-facing strings the route can surface (e.g. on an "already installed"
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 601ce8e95b..365029e3fc 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -25,6 +25,8 @@ import { prepareLocalMemory } from '../../lib/localMemory.js';
import { slugifyForFilename } from '../../lib/civitai.js';
import { detectHostCapabilities, resolveTarget, DEFAULT_IMAGE_TO_3D_TARGET } from './targets.js';
import { getTargetAdapter } from './adapters.js';
+import { normalizeRenderOptions, randomRenderSeed } from './renderOptions.js';
+import { prepareSourceImage } from './sourceKeying.js';
import * as store from './db.js';
const MAX_RUNS = 30;
@@ -39,8 +41,12 @@ const cleanError = (error) => String(error?.message || error || 'Render failed')
/** The served URL for a record's exported GLB (static-mounted under /data). */
const assetUrl = (id) => `/data/image-to-3d/${id}/model.glb`;
+/** A record's render directory on disk. */
+const recordDir = (id) => join(PATHS.imageTo3d, id);
/** The on-disk destination the runner writes the GLB to. */
-const assetDiskPath = (id) => join(PATHS.imageTo3d, id, 'model.glb');
+const assetDiskPath = (id) => join(recordDir(id), 'model.glb');
+/** Where a background-keyed copy of the source lands (never the gallery file). */
+const keyedSourcePath = (id) => join(recordDir(id), 'source-keyed.png');
/**
* Remove a record's render directory (the exported GLB + its folder). Used to
@@ -49,10 +55,22 @@ const assetDiskPath = (id) => join(PATHS.imageTo3d, id, 'model.glb');
* not the render got far enough to emit a file.
*/
async function cleanupRenderDir(id) {
- await rm(join(PATHS.imageTo3d, id), { recursive: true, force: true })
+ await rm(recordDir(id), { recursive: true, force: true })
.catch((err) => console.error(`❌ Image-to-3D cleanup failed for ${id}: ${err.message}`));
}
+/**
+ * Best-effort patch of one run entry (progress-class writes). Guarded on the
+ * operation still owning the record, fire-and-forget — a lost frame must never
+ * fail or stall a render.
+ */
+function patchRun(id, operationId, patch) {
+ void store.mutateModel(id, (current) => {
+ if (current.generationOperationId !== operationId) return null;
+ return { ...current, runs: updateRun(current.runs, operationId, patch) };
+ }).catch(() => {});
+}
+
/**
* Verify a target can actually run on this host right now — unknown target →
* 400, hardware-unsupported → 409 (reason surfaced), not-installed → 409 so the
@@ -112,12 +130,32 @@ async function failGeneration(id, operationId, error) {
});
}
-async function executeRender({ id, operationId, adapter, sourcePath, caps }) {
+async function executeRender({ id, operationId, adapter, sourcePath, caps, options }) {
const outputPath = assetDiskPath(id);
+ // keyBackground is consumed here; the sampler knobs ride through to the
+ // adapter as-is, so a future knob added to the options shape flows without
+ // touching this call chain.
+ const { keyBackground, ...samplerOptions } = options;
let lastPersistedPercent = -1;
let heavyClaim = null;
try {
- await ensureDir(join(PATHS.imageTo3d, id));
+ await ensureDir(recordDir(id));
+ // Key a solid background out of the source (into THIS record's render dir —
+ // the shared gallery file is never touched) so the pipeline consumes a real
+ // alpha channel instead of matting a green screen. Runs BEFORE the heavy-job
+ // claim: it is CPU-only preprocessing, so other heavy jobs shouldn't queue
+ // behind it and resident models shouldn't be evicted for it. Best-effort: a
+ // keying failure must never fail a render the model could still attempt raw.
+ const keyedPath = keyBackground
+ ? await prepareSourceImage({ sourcePath, targetPath: keyedSourcePath(id) })
+ .catch((err) => {
+ console.error(`❌ Image-to-3D background keying failed for ${id}: ${err.message}`);
+ return null;
+ })
+ : null;
+ if (keyedPath) console.log(`🎨 Image-to-3D keyed a solid background for ${id}`);
+ // Record what the render actually consumed (best-effort, like percent below).
+ patchRun(id, operationId, { sourceKeyed: Boolean(keyedPath) });
heavyClaim = await claimHeavyLocalJob({ kind: 'image-to-3D generation', id: operationId });
if (!heavyClaim.ok) {
throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });
@@ -133,9 +171,13 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps }) {
// the kill handle so deleteModel can SIGTERM this render if the record is deleted
// mid-flight.
const { promise, kill } = adapter.run({
- imagePath: sourcePath,
+ imagePath: keyedPath ?? sourcePath,
outputPath,
env,
+ // The per-run sampler knobs resolved in beginRender: `seed` is always a
+ // concrete integer (pinned or freshly rolled), `steps: null` means the
+ // pipeline default.
+ ...samplerOptions,
// The host capabilities resolved at the request boundary, passed down rather
// than re-probed: a target whose output budget scales with the hardware (the
// CUDA lane's atlas size, keyed on VRAM) reads the same values the readiness
@@ -148,10 +190,7 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps }) {
const percent = Number.isFinite(frame?.percent) ? Math.round(frame.percent) : null;
if (percent === null || percent <= lastPersistedPercent) return;
lastPersistedPercent = percent;
- void store.mutateModel(id, (current) => {
- if (current.generationOperationId !== operationId) return null;
- return { ...current, runs: updateRun(current.runs, operationId, { percent }) };
- }).catch(() => {}); // progress is best-effort; a lost frame is not fatal
+ patchRun(id, operationId, { percent });
},
});
activeRenders.set(operationId, kill);
@@ -243,11 +282,12 @@ export async function createModel(input, { caps } = {}) {
// Thread the already-validated adapter + resolved source straight into the
// render — createModel and startGeneration share `beginRender`, so the create
// path does NOT re-resolve the gallery image, re-assert readiness, or re-fetch
- // the row it just wrote.
- return beginRender(created, adapter, sourcePath, hostCaps);
+ // the row it just wrote. `input` carries the optional per-run knobs
+ // (steps/seed/keyBackground); beginRender normalizes them.
+ return beginRender(created, adapter, sourcePath, hostCaps, input);
}
-export async function startGeneration(id, { caps } = {}) {
+export async function startGeneration(id, { caps, options } = {}) {
const current = await store.getModel(id);
if (!current) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });
if (current.status === 'generating'
@@ -261,7 +301,7 @@ export async function startGeneration(id, { caps } = {}) {
if (!sourcePath) {
throw new ServerError('The source gallery image is no longer available', { status: 409, code: 'GALLERY_IMAGE_NOT_FOUND' });
}
- return beginRender(current, adapter, sourcePath, hostCaps);
+ return beginRender(current, adapter, sourcePath, hostCaps, options);
}
/**
@@ -270,11 +310,18 @@ export async function startGeneration(id, { caps } = {}) {
* validation (target readiness, gallery-image resolution) and pass the resolved
* adapter + source through. The transactional `status==='generating'` guard here
* is the authoritative race check (the callers' pre-check is just a fast 409).
+ *
+ * Render options are PER-RUN parameters: normalized from this request alone
+ * (nothing persists between runs), with an unpinned seed rolled fresh so
+ * re-render actually samples a new model. The run entry records the concrete
+ * values the subprocess receives — the truthful, reproducible record.
*/
-async function beginRender(record, adapter, sourcePath, caps) {
+async function beginRender(record, adapter, sourcePath, caps, requestOptions) {
const { id } = record;
const operationId = randomUUID();
const startedAt = new Date().toISOString();
+ const normalized = normalizeRenderOptions(requestOptions);
+ const options = { ...normalized, seed: normalized.seed ?? randomRenderSeed() };
const next = await store.mutateModel(id, (fresh) => {
if (fresh.status === 'generating') {
throw new ServerError('This model is already generating', { status: 409, code: 'MODEL_BUSY' });
@@ -291,6 +338,9 @@ async function beginRender(record, adapter, sourcePath, caps) {
status: 'running',
target: fresh.target,
percent: 0,
+ steps: options.steps,
+ seed: options.seed,
+ keyBackground: options.keyBackground,
startedAt,
completedAt: null,
error: null,
@@ -301,7 +351,7 @@ async function beginRender(record, adapter, sourcePath, caps) {
activeOperations.add(operationId);
setImmediate(() => {
- void executeRender({ id, operationId, adapter, sourcePath, caps });
+ void executeRender({ id, operationId, adapter, sourcePath, caps, options });
});
return next;
}
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index 3f12771d04..f93213fb27 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -40,6 +40,12 @@ vi.mock('../../lib/hfToken.js', () => ({
hfChildEnv: vi.fn(async () => ({ HF_TOKEN: 'hf_from_store', HUGGINGFACE_HUB_TOKEN: 'hf_from_store' })),
}));
+// Background keying reads the source with sharp — mock it so the suite never
+// touches real files. Default: null = pass-through (no solid background).
+vi.mock('./sourceKeying.js', () => ({
+ prepareSourceImage: vi.fn(async () => null),
+}));
+
const { claimRelease } = vi.hoisted(() => ({ claimRelease: vi.fn(async () => {}) }));
vi.mock('../../lib/heavyJobClaim.js', () => ({
claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: {}, release: claimRelease })),
@@ -62,6 +68,7 @@ import { ensureDir } from '../../lib/fileUtils.js';
import { resolveTarget } from './targets.js';
import { isTrellis2Installed, runTrellis2Generate } from './trellis2.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
+import { prepareSourceImage } from './sourceKeying.js';
import * as store from './db.js';
import {
createModel, startGeneration, getModelAsset, recoverInterruptedModels, deleteModel,
@@ -285,3 +292,106 @@ describe('image-to-3D model orchestration', () => {
expect(asset.filename).toBe('my-beacon.glb');
});
});
+
+describe('render options and source keying', () => {
+ // The standard live-record store harness: mutations apply to `current`.
+ let current;
+ const wireStore = (record) => {
+ current = record;
+ store.createModel.mockImplementation(async () => current);
+ store.getModel.mockImplementation(async () => current);
+ store.mutateModel.mockImplementation(async (_id, mutate) => {
+ const next = mutate(current);
+ if (next) current = next;
+ return current;
+ });
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: {}, release: claimRelease });
+ isTrellis2Installed.mockReturnValue(true);
+ resolveTarget.mockImplementation(() => (
+ { targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: true, reason: null }
+ ));
+ runTrellis2Generate.mockReturnValue({
+ promise: Promise.resolve({ assetPath: '/mock/data/image-to-3d/x/model.glb' }),
+ kill: vi.fn(),
+ });
+ prepareSourceImage.mockResolvedValue(null);
+ wireStore(draftRecord());
+ });
+
+ it('rolls a fresh random seed per unpinned run and records it on the run entry', async () => {
+ await createModel({ name: 'Beacon', filename: 'example.png' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(generateArgs.steps).toBeNull();
+ expect(Number.isInteger(generateArgs.seed)).toBe(true);
+ expect(generateArgs.seed).toBeGreaterThanOrEqual(0);
+ expect(generateArgs.seed).toBeLessThanOrEqual(2147483647);
+ // The run entry records the concrete values the subprocess received.
+ expect(current.runs.at(-1)).toMatchObject({
+ seed: generateArgs.seed, steps: null, keyBackground: true,
+ });
+ });
+
+ it('per-run options reach the runner and the run entry, and do not persist on the record', async () => {
+ await createModel({ name: 'Beacon', filename: 'example.png', steps: 24, seed: 7 });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(generateArgs).toMatchObject({ steps: 24, seed: 7 });
+ expect(current.runs.at(-1)).toMatchObject({ steps: 24, seed: 7 });
+ // Options are per-run parameters, not a stored record preference.
+ expect(current.renderOptions).toBeUndefined();
+ });
+
+ it('a re-generate without options gets defaults, not the previous run’s values', async () => {
+ wireStore({
+ ...draftRecord(),
+ runs: [{ operationId: 'op-old', status: 'completed', steps: 24, seed: 7 }],
+ });
+
+ await startGeneration('image3d-example', { options: {} });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(generateArgs.steps).toBeNull();
+ expect(Number.isInteger(generateArgs.seed)).toBe(true);
+ });
+
+ it('a keyed source image is what the render consumes', async () => {
+ prepareSourceImage.mockImplementation(async ({ targetPath }) => targetPath);
+
+ await createModel({ name: 'Beacon', filename: 'example.png' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(posixPath(generateArgs.imagePath))
+ .toBe('/mock/data/image-to-3d/image3d-example/source-keyed.png');
+ expect(current.runs.at(-1).sourceKeyed).toBe(true);
+ });
+
+ it('keyBackground:false skips keying entirely', async () => {
+ await createModel({ name: 'Beacon', filename: 'example.png', keyBackground: false });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ expect(prepareSourceImage).not.toHaveBeenCalled();
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(posixPath(generateArgs.imagePath)).toBe('/mock/data/images/example.png');
+ expect(current.runs.at(-1).keyBackground).toBe(false);
+ });
+
+ it('a keying failure falls back to the raw source instead of failing the render', async () => {
+ prepareSourceImage.mockRejectedValue(new Error('unreadable image'));
+
+ await createModel({ name: 'Beacon', filename: 'example.png' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+
+ const [generateArgs] = runTrellis2Generate.mock.calls[0];
+ expect(posixPath(generateArgs.imagePath)).toBe('/mock/data/images/example.png');
+ expect(current.runs.at(-1).sourceKeyed).toBe(false);
+ });
+});
diff --git a/server/services/imageTo3d/renderOptions.js b/server/services/imageTo3d/renderOptions.js
new file mode 100644
index 0000000000..f35407df4f
--- /dev/null
+++ b/server/services/imageTo3d/renderOptions.js
@@ -0,0 +1,82 @@
+/**
+ * Lane-agnostic PER-RUN render options for image-to-3D generation (sampler
+ * steps / seed / background keying). Shared by the route schema, the record
+ * layer, and both TRELLIS.2 lanes so the accepted ranges and CLI flags can't
+ * drift between them.
+ *
+ * These are deliberately per-run parameters, NOT a stored record preference:
+ * each generate request says what it wants, the run entry records the concrete
+ * values the subprocess received (the truthful, reproducible record), and
+ * nothing merges or persists between runs.
+ *
+ * - `steps: null` → the pipeline's own default (12 per flow phase).
+ * - `seed: null` → roll a fresh random seed for this run, so "Re-render"
+ * actually samples a new model instead of deterministically reproducing the
+ * last one (the upstream CLI default is a fixed 42).
+ */
+
+import { randomInt } from 'node:crypto';
+
+/** Sampler steps per flow phase. The pipeline default is 12; runtime scales
+ * roughly linearly with steps across all three phases, so the cap keeps a
+ * mistyped value from queueing an hours-long render. */
+export const RENDER_STEPS_MIN = 1;
+export const RENDER_STEPS_MAX = 64;
+
+/** Seeds stay in int32 range — both lanes hand them to torch generators.
+ * (Deliberately narrower than the 32-bit unsigned `MAX_SEED` the image/video
+ * gen lanes use in `client/src/lib/genUtils.js` — torch rejects > int32.) */
+export const RENDER_SEED_MAX = 2147483647;
+
+/** A fresh random seed for an unpinned run. */
+export function randomRenderSeed() {
+ return randomInt(0, RENDER_SEED_MAX + 1);
+}
+
+const intInRange = (value, min, max) => (
+ Number.isInteger(value) && value >= min && value <= max
+);
+
+/** Whether a value is a valid steps count (null/undefined are "unset"). */
+export const isValidRenderSteps = (value) => intInRange(value, RENDER_STEPS_MIN, RENDER_STEPS_MAX);
+
+/** Whether a value is a valid seed (null/undefined are "unset"). */
+export const isValidRenderSeed = (value) => intInRange(value, 0, RENDER_SEED_MAX);
+
+/**
+ * Normalize a request's options into the per-run shape. Invalid/absent values
+ * collapse to the unset sentinel (`null`) rather than throwing — the route
+ * schema is the loud gate; this is the internal-caller normalizer.
+ * @param {{steps?: number|null, seed?: number|null, keyBackground?: boolean}} [input]
+ * @returns {{steps: number|null, seed: number|null, keyBackground: boolean}}
+ */
+export function normalizeRenderOptions(input = {}) {
+ return {
+ steps: isValidRenderSteps(input.steps) ? input.steps : null,
+ seed: isValidRenderSeed(input.seed) ? input.seed : null,
+ keyBackground: input.keyBackground !== false,
+ };
+}
+
+/**
+ * Validate steps/seed and emit their CLI flags — the single owner of both the
+ * bounds check and the flag names, shared by the MPS and CUDA arg builders so
+ * neither the ranges nor the CLI contract can drift between lanes. `null`
+ * omits a flag (the subprocess default applies). Throws with the caller's
+ * label so the error reads like the builder that rejected it.
+ * @param {string} label
+ * @param {{steps?: number|null, seed?: number|null}} [opts]
+ * @returns {string[]}
+ */
+export function renderOptionArgs(label, { steps = null, seed = null } = {}) {
+ if (steps !== null && !isValidRenderSteps(steps)) {
+ throw new Error(`${label}: steps must be an integer in [${RENDER_STEPS_MIN}, ${RENDER_STEPS_MAX}]`);
+ }
+ if (seed !== null && !isValidRenderSeed(seed)) {
+ throw new Error(`${label}: seed must be an integer in [0, ${RENDER_SEED_MAX}]`);
+ }
+ return [
+ ...(seed !== null ? ['--seed', String(seed)] : []),
+ ...(steps !== null ? ['--steps', String(steps)] : []),
+ ];
+}
diff --git a/server/services/imageTo3d/renderOptions.parity.test.js b/server/services/imageTo3d/renderOptions.parity.test.js
new file mode 100644
index 0000000000..eba82ec9e2
--- /dev/null
+++ b/server/services/imageTo3d/renderOptions.parity.test.js
@@ -0,0 +1,36 @@
+/**
+ * Cross-package parity for the image-to-3D render-option bounds.
+ *
+ * `renderOptions.js` owns the server-side bounds; `client/src/lib/
+ * imageTo3dRenderOptions.js` is the hand-maintained client mirror (the input's
+ * `max` attribute and the steps presets). This suite imports BOTH and asserts
+ * they stay compatible — the same mechanism as
+ * `unavailableReasons.parity.test.js` next door. It lives server-side because
+ * the client mirror is a pure module that loads fine under the node runner.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ RENDER_SEED_MAX,
+ isValidRenderSteps,
+} from './renderOptions.js';
+import {
+ SEED_MAX as CLIENT_SEED_MAX,
+ STEPS_PRESETS as CLIENT_STEPS_PRESETS,
+} from '../../../client/src/lib/imageTo3dRenderOptions.js';
+
+describe('image-to-3D render-option parity (server bounds ↔ client mirror)', () => {
+ it('the client seed ceiling equals the server bound', () => {
+ expect(CLIENT_SEED_MAX).toBe(RENDER_SEED_MAX);
+ });
+
+ it('every non-default client steps preset is a value the server accepts', () => {
+ const numeric = CLIENT_STEPS_PRESETS
+ .map((preset) => preset.value)
+ .filter((value) => value !== '');
+ expect(numeric.length).toBeGreaterThan(0);
+ for (const value of numeric) {
+ expect(isValidRenderSteps(Number(value)), `preset ${value}`).toBe(true);
+ }
+ });
+});
diff --git a/server/services/imageTo3d/renderOptions.test.js b/server/services/imageTo3d/renderOptions.test.js
new file mode 100644
index 0000000000..e8634dd432
--- /dev/null
+++ b/server/services/imageTo3d/renderOptions.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import {
+ RENDER_SEED_MAX,
+ RENDER_STEPS_MAX,
+ RENDER_STEPS_MIN,
+ isValidRenderSeed,
+ isValidRenderSteps,
+ normalizeRenderOptions,
+ randomRenderSeed,
+ renderOptionArgs,
+} from './renderOptions.js';
+
+describe('normalizeRenderOptions', () => {
+ it('defaults to unset steps/seed with keying enabled', () => {
+ expect(normalizeRenderOptions()).toEqual({ steps: null, seed: null, keyBackground: true });
+ expect(normalizeRenderOptions({})).toEqual({ steps: null, seed: null, keyBackground: true });
+ });
+
+ it('keeps valid values and collapses invalid ones to the unset sentinel', () => {
+ expect(normalizeRenderOptions({ steps: 24, seed: 0, keyBackground: false }))
+ .toEqual({ steps: 24, seed: 0, keyBackground: false });
+ expect(normalizeRenderOptions({ steps: RENDER_STEPS_MAX + 1, seed: RENDER_SEED_MAX + 1 }))
+ .toEqual({ steps: null, seed: null, keyBackground: true });
+ expect(normalizeRenderOptions({ steps: 12.5, seed: '42' }))
+ .toEqual({ steps: null, seed: null, keyBackground: true });
+ });
+});
+
+describe('renderOptionArgs', () => {
+ it('emits --seed/--steps for provided values and nothing for unset ones', () => {
+ expect(renderOptionArgs('x', { steps: 24, seed: 1234 }))
+ .toEqual(['--seed', '1234', '--steps', '24']);
+ expect(renderOptionArgs('x', { seed: 0 })).toEqual(['--seed', '0']);
+ expect(renderOptionArgs('x', {})).toEqual([]);
+ expect(renderOptionArgs('x')).toEqual([]);
+ });
+
+ it('throws with the caller label on out-of-range values', () => {
+ expect(() => renderOptionArgs('buildGenerateArgs', { steps: 0 }))
+ .toThrow(/buildGenerateArgs: steps must be an integer/);
+ expect(() => renderOptionArgs('buildCudaGenerateArgs', { seed: -1 }))
+ .toThrow(/buildCudaGenerateArgs: seed must be an integer/);
+ expect(() => renderOptionArgs('x', { steps: RENDER_STEPS_MAX + 1 }))
+ .toThrow(/steps must be an integer/);
+ expect(() => renderOptionArgs('x', { seed: RENDER_SEED_MAX + 1 }))
+ .toThrow(/seed must be an integer/);
+ });
+});
+
+describe('randomRenderSeed', () => {
+ it('stays in the valid int32 seed range', () => {
+ for (let i = 0; i < 50; i += 1) {
+ expect(isValidRenderSeed(randomRenderSeed())).toBe(true);
+ }
+ });
+});
+
+describe('validators', () => {
+ it('accept the bounds and reject just outside them', () => {
+ expect(isValidRenderSteps(RENDER_STEPS_MIN)).toBe(true);
+ expect(isValidRenderSteps(RENDER_STEPS_MAX)).toBe(true);
+ expect(isValidRenderSteps(RENDER_STEPS_MIN - 1)).toBe(false);
+ expect(isValidRenderSteps(RENDER_STEPS_MAX + 1)).toBe(false);
+ expect(isValidRenderSeed(0)).toBe(true);
+ expect(isValidRenderSeed(RENDER_SEED_MAX)).toBe(true);
+ expect(isValidRenderSeed(-1)).toBe(false);
+ expect(isValidRenderSeed(RENDER_SEED_MAX + 1)).toBe(false);
+ });
+});
diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.js
new file mode 100644
index 0000000000..46eb432978
--- /dev/null
+++ b/server/services/imageTo3d/sourceKeying.js
@@ -0,0 +1,203 @@
+/**
+ * Solid-background keying for image-to-3D source images.
+ *
+ * TRELLIS.2's own preprocessing uses a real alpha channel directly when one is
+ * present and only falls back to RMBG-2.0 matting when there isn't — and matting a
+ * flat green/blue screen is exactly where it produces soft, uncertain mattes (color
+ * spill, fuzzy fur edges) that turn into hallucinated geometry. When the user's
+ * source has NO alpha but sits on a detectably solid background, PortOS can key it
+ * deterministically before the render and hand the pipeline a real alpha channel.
+ *
+ * The pixel work is pure (raw RGBA buffers in/out) so it's unit-testable on tiny
+ * synthetic images; `prepareSourceImage` is the one sharp/file boundary. The keyed
+ * copy is written into the RECORD's render directory — the shared gallery file is
+ * never mutated (other features reference it).
+ *
+ * A deliberately simpler edge model than the sprites lane's chroma unmix
+ * (`services/sprites/chromaKey.js`): that lane reverses source-over compositing
+ * against a known pure-channel key; this one only needs "background gone, 1px
+ * anti-spill feather" for an arbitrary measured background color. Consolidating
+ * the shared border/median primitives with the sprites lane is tracked separately.
+ *
+ * Algorithm (deliberately conservative — "not sure" means "don't touch it"):
+ * 1. Sample the border pixels; take the per-channel median as the candidate
+ * background color. If less than `KEY_MIN_BORDER_COVERAGE` of the border sits
+ * within `KEY_TOLERANCE` of it, the background isn't solid → pass through.
+ * 2. Flood-fill from every matching border pixel (4-neighborhood) → alpha 0.
+ * 3. Key enclosed pockets (background color trapped between limbs, unreachable
+ * from the border) with the tighter `KEY_TIGHT_TOLERANCE`, so a subject that
+ * merely contains a similar color isn't punched full of holes.
+ * 4. Feather: foreground pixels adjacent to keyed ones get partial alpha scaled
+ * by their color distance to the background — a 1px anti-spill edge, not a
+ * full matte.
+ * 5. Sanity-gate the result: if almost nothing or almost everything got keyed,
+ * the detection was wrong → pass through untouched.
+ */
+
+import sharp from 'sharp';
+
+/** Euclidean RGB distance for the border/flood match (0–441 scale). */
+export const KEY_TOLERANCE = 30;
+/** Tighter distance for enclosed pockets that can't be reached from the border. */
+export const KEY_TIGHT_TOLERANCE = 15;
+/** Minimum fraction of border pixels that must match for "solid background". */
+export const KEY_MIN_BORDER_COVERAGE = 0.9;
+/** Distance band past KEY_TOLERANCE that maps to partial alpha at the edge. */
+export const KEY_SOFT_BAND = 30;
+/** Keyed-area fraction outside (min, max) means the detection was wrong. */
+export const KEY_MIN_KEYED_RATIO = 0.05;
+export const KEY_MAX_KEYED_RATIO = 0.98;
+
+/** Sources above this pixel count skip Node-side keying entirely: the raw
+ * decode plus the flood/queue/output buffers scale at ~20 bytes per pixel
+ * (a 96 MP gallery image would hold >1 GB and stall the event loop), while
+ * TRELLIS.2 downscales its input to 1024px anyway — the pipeline's own
+ * matting handles oversized sources. */
+export const KEY_MAX_PIXELS = 16_000_000;
+
+// Squared-distance comparisons throughout the hot loops — Math.sqrt only where a
+// real distance is needed (the feather ramp, edge pixels only).
+const KEY_TOLERANCE_SQ = KEY_TOLERANCE ** 2;
+const KEY_TIGHT_TOLERANCE_SQ = KEY_TIGHT_TOLERANCE ** 2;
+
+const distSq = (data, i, [r, g, b]) => (
+ (data[i] - r) ** 2 + (data[i + 1] - g) ** 2 + (data[i + 2] - b) ** 2
+);
+
+const median = (values) => {
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+};
+
+/** Whether an RGBA buffer already carries a meaningful (non-opaque) alpha channel. */
+export function hasMeaningfulAlpha(data) {
+ for (let i = 3; i < data.length; i += 4) {
+ if (data[i] < 250) return true;
+ }
+ return false;
+}
+
+/**
+ * Detect a solid border color in a raw RGBA buffer. Returns `[r, g, b]` when at
+ * least `KEY_MIN_BORDER_COVERAGE` of the border pixels sit within `KEY_TOLERANCE`
+ * of the border's median color, else null.
+ * @param {{data: Buffer|Uint8Array, width: number, height: number}} image
+ * @returns {[number, number, number]|null}
+ */
+export function detectSolidBorderColor({ data, width, height }) {
+ const offsets = [];
+ for (let x = 0; x < width; x += 1) { offsets.push(x * 4, ((height - 1) * width + x) * 4); }
+ for (let y = 1; y < height - 1; y += 1) { offsets.push(y * width * 4, (y * width + width - 1) * 4); }
+
+ const color = [0, 1, 2].map((c) => median(offsets.map((i) => data[i + c])));
+ let matching = 0;
+ for (const i of offsets) { if (distSq(data, i, color) <= KEY_TOLERANCE_SQ) matching += 1; }
+ return matching / offsets.length >= KEY_MIN_BORDER_COVERAGE ? color : null;
+}
+
+/**
+ * Key a solid background out of a raw RGBA buffer. Pure — returns a NEW buffer
+ * plus stats, or null when the image has no detectable solid background (or the
+ * detection failed its own sanity gates). See the module doc for the algorithm.
+ * @param {{data: Buffer|Uint8Array, width: number, height: number}} image
+ * @returns {{data: Uint8Array, background: [number, number, number], keyedRatio: number}|null}
+ */
+export function keySolidBackground({ data, width, height }) {
+ const background = detectSolidBorderColor({ data, width, height });
+ if (!background) return null;
+
+ const pixelCount = width * height;
+ const keyed = new Uint8Array(pixelCount); // 1 = background
+ const queue = new Int32Array(pixelCount);
+ let queueLength = 0;
+
+ const enqueue = (p) => {
+ if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TOLERANCE_SQ) {
+ keyed[p] = 1;
+ queue[queueLength] = p;
+ queueLength += 1;
+ }
+ };
+ for (let x = 0; x < width; x += 1) { enqueue(x); enqueue((height - 1) * width + x); }
+ for (let y = 1; y < height - 1; y += 1) { enqueue(y * width); enqueue(y * width + width - 1); }
+
+ for (let head = 0; head < queueLength; head += 1) {
+ const p = queue[head];
+ const x = p % width;
+ if (x > 0) enqueue(p - 1);
+ if (x < width - 1) enqueue(p + 1);
+ if (p >= width) enqueue(p - width);
+ if (p < pixelCount - width) enqueue(p + width);
+ }
+
+ // Enclosed pockets: background color trapped between limbs never touches the
+ // border, so the flood can't reach it — key it only on the tight tolerance.
+ // The flood already counted itself (queueLength); count pockets as they key.
+ let keyedCount = queueLength;
+ for (let p = 0; p < pixelCount; p += 1) {
+ if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TIGHT_TOLERANCE_SQ) {
+ keyed[p] = 1;
+ keyedCount += 1;
+ }
+ }
+
+ const keyedRatio = keyedCount / pixelCount;
+ if (keyedRatio < KEY_MIN_KEYED_RATIO || keyedRatio > KEY_MAX_KEYED_RATIO) return null;
+
+ const out = new Uint8Array(data.length);
+ out.set(data);
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const p = y * width + x;
+ if (keyed[p]) { out[p * 4 + 3] = 0; continue; }
+ // Feather only against pixels that actually border the keyed region — a
+ // background-adjacent edge texel carrying spill gets partial alpha; interior
+ // pixels that merely resemble the background stay fully opaque.
+ const touchesKeyed = (x > 0 && keyed[p - 1]) || (x < width - 1 && keyed[p + 1])
+ || (y > 0 && keyed[p - width]) || (y < height - 1 && keyed[p + width]);
+ if (!touchesKeyed) continue;
+ const d = Math.sqrt(distSq(data, p * 4, background));
+ if (d < KEY_TOLERANCE + KEY_SOFT_BAND) {
+ // Max(0): an enclosed pixel inside KEY_TOLERANCE (but above the tight
+ // pocket threshold) lands here with a negative ramp value.
+ out[p * 4 + 3] = Math.max(0, Math.round(((d - KEY_TOLERANCE) / KEY_SOFT_BAND) * 255));
+ }
+ }
+ }
+ return { data: out, background, keyedRatio };
+}
+
+/**
+ * Resolve whether a render should consume a keyed copy of its source. Reads
+ * `sourcePath`; when it has no meaningful alpha and sits on a solid background,
+ * writes a keyed PNG to `targetPath` and returns that path. Returns null in
+ * every non-keyable case (real alpha already present — the pipeline uses it
+ * directly — or no solid background, or the sanity gates tripped): the caller
+ * renders the original.
+ *
+ * I/O failures (unreadable file) reject; the caller treats keying as
+ * best-effort (a keying failure must never fail a render the model could still
+ * attempt on the raw image).
+ *
+ * @param {{sourcePath: string, targetPath: string}} opts
+ * @returns {Promise<string|null>} the keyed image path, or null to use the original
+ */
+export async function prepareSourceImage({ sourcePath, targetPath }) {
+ // Header-only probe: bail before the full decode when the source is too
+ // large to key affordably (KEY_MAX_PIXELS), and when it has no alpha channel
+ // at all, skip the full-buffer meaningful-alpha scan below (ensureAlpha
+ // fabricates the channel).
+ const { hasAlpha, width, height } = await sharp(sourcePath).metadata();
+ if (!width || !height || width * height > KEY_MAX_PIXELS) return null;
+ const { data, info } = await sharp(sourcePath)
+ .ensureAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ if (hasAlpha && hasMeaningfulAlpha(data)) return null;
+ const result = keySolidBackground({ data, width: info.width, height: info.height });
+ if (!result) return null;
+ await sharp(result.data, { raw: { width: info.width, height: info.height, channels: 4 } })
+ .png()
+ .toFile(targetPath);
+ return targetPath;
+}
diff --git a/server/services/imageTo3d/sourceKeying.test.js b/server/services/imageTo3d/sourceKeying.test.js
new file mode 100644
index 0000000000..bcf95cb003
--- /dev/null
+++ b/server/services/imageTo3d/sourceKeying.test.js
@@ -0,0 +1,159 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import sharp from 'sharp';
+import {
+ detectSolidBorderColor,
+ hasMeaningfulAlpha,
+ keySolidBackground,
+ prepareSourceImage,
+} from './sourceKeying.js';
+
+// Build a raw RGBA buffer from a painter function (x, y) => [r, g, b, a?].
+const makeImage = (width, height, paint) => {
+ const data = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const [r, g, b, a = 255] = paint(x, y);
+ const i = (y * width + x) * 4;
+ data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = a;
+ }
+ }
+ return { data, width, height };
+};
+
+const GREEN = [30, 200, 40];
+const BROWN = [140, 90, 50];
+
+// A 20×20 "subject on green screen": a 10×10 brown block centered on flat green.
+const subjectOnGreen = () => makeImage(20, 20, (x, y) => (
+ x >= 5 && x < 15 && y >= 5 && y < 15 ? BROWN : GREEN
+));
+
+// A 20×20 image with no dominant border color (photo-like busy background).
+const noisyImage = () => makeImage(20, 20, (x, y) => [
+ (x * 37 + y * 91) % 256, (x * 13 + y * 7) % 256, (x * 71 + y * 3) % 256,
+]);
+
+const alphaAt = (image, x, y) => image.data[(y * image.width + x) * 4 + 3];
+
+describe('detectSolidBorderColor', () => {
+ it('detects a flat border color', () => {
+ expect(detectSolidBorderColor(subjectOnGreen())).toEqual(GREEN);
+ });
+
+ it('returns null for a busy border', () => {
+ expect(detectSolidBorderColor(noisyImage())).toBeNull();
+ });
+
+ it('tolerates minor border noise within the match tolerance', () => {
+ const slightlyNoisy = makeImage(20, 20, (x, y) => (
+ x >= 5 && x < 15 && y >= 5 && y < 15
+ ? BROWN
+ : [GREEN[0] + ((x + y) % 5), GREEN[1] - ((x * y) % 5), GREEN[2]]
+ ));
+ const color = detectSolidBorderColor(slightlyNoisy);
+ expect(color).not.toBeNull();
+ });
+});
+
+describe('keySolidBackground', () => {
+ it('keys the background transparent and leaves the subject opaque', () => {
+ const result = keySolidBackground(subjectOnGreen());
+ expect(result).not.toBeNull();
+ const keyed = { data: result.data, width: 20, height: 20 };
+ expect(alphaAt(keyed, 0, 0)).toBe(0); // background corner
+ expect(alphaAt(keyed, 10, 10)).toBe(255); // subject center
+ expect(alphaAt(keyed, 6, 6)).toBe(255); // subject interior near the edge
+ });
+
+ it('keys enclosed background pockets the flood fill cannot reach', () => {
+ // A brown ring with a green hole in the middle — unreachable from the border.
+ const ring = makeImage(20, 20, (x, y) => {
+ const inRing = x >= 4 && x < 16 && y >= 4 && y < 16;
+ const inHole = x >= 8 && x < 12 && y >= 8 && y < 12;
+ if (inHole) return GREEN;
+ if (inRing) return BROWN;
+ return GREEN;
+ });
+ const result = keySolidBackground(ring);
+ expect(result).not.toBeNull();
+ const keyed = { data: result.data, width: 20, height: 20 };
+ expect(alphaAt(keyed, 10, 10)).toBe(0); // the enclosed pocket
+ expect(alphaAt(keyed, 5, 10)).toBe(255); // the ring itself
+ });
+
+ it('returns null when the whole image is background (nothing to keep)', () => {
+ expect(keySolidBackground(makeImage(20, 20, () => GREEN))).toBeNull();
+ });
+
+ it('returns null when there is no solid background to key', () => {
+ expect(keySolidBackground(noisyImage())).toBeNull();
+ });
+});
+
+describe('hasMeaningfulAlpha', () => {
+ it('distinguishes an all-opaque alpha channel from a real one', () => {
+ expect(hasMeaningfulAlpha(subjectOnGreen().data)).toBe(false);
+ const withAlpha = makeImage(4, 4, (x) => [0, 0, 0, x === 0 ? 0 : 255]);
+ expect(hasMeaningfulAlpha(withAlpha.data)).toBe(true);
+ });
+});
+
+describe('prepareSourceImage', () => {
+ let dir;
+ const tempDir = async () => {
+ dir = dir || await mkdtemp(join(tmpdir(), 'portos-keying-'));
+ return dir;
+ };
+ afterAll(async () => { if (dir) await rm(dir, { recursive: true, force: true }); });
+
+ const writePng = async (name, image) => {
+ const path = join(await tempDir(), name);
+ await sharp(Buffer.from(image.data), {
+ raw: { width: image.width, height: image.height, channels: 4 },
+ }).png().toFile(path);
+ return path;
+ };
+
+ it('returns null for a transparent source — the pipeline uses real alpha directly', async () => {
+ const withAlpha = makeImage(20, 20, (x, y) => (
+ x >= 5 && x < 15 && y >= 5 && y < 15 ? [...BROWN, 255] : [0, 0, 0, 0]
+ ));
+ const sourcePath = await writePng('transparent.png', withAlpha);
+ const result = await prepareSourceImage({ sourcePath, targetPath: join(await tempDir(), 'never.png') });
+ expect(result).toBeNull();
+ });
+
+ it('keys a solid-background source into the target path and returns it', async () => {
+ const sourcePath = await writePng('green.png', subjectOnGreen());
+ const targetPath = join(await tempDir(), 'keyed.png');
+ const result = await prepareSourceImage({ sourcePath, targetPath });
+ expect(result).toBe(targetPath);
+
+ const { data, info } = await sharp(targetPath).ensureAlpha().raw()
+ .toBuffer({ resolveWithObject: true });
+ const keyed = { data, width: info.width, height: info.height };
+ expect(alphaAt(keyed, 0, 0)).toBe(0);
+ expect(alphaAt(keyed, 10, 10)).toBe(255);
+ });
+
+ it('returns null for a busy-background source — the pipeline’s own matting applies', async () => {
+ const noisy = noisyImage();
+ const sourcePath = await writePng('noisy.png', noisy);
+ const result = await prepareSourceImage({ sourcePath, targetPath: join(await tempDir(), 'never2.png') });
+ expect(result).toBeNull();
+ });
+
+ it('returns null for a source over the pixel cap without decoding it', async () => {
+ // Just over KEY_MAX_PIXELS (16 MP): 4020×4000. Solid color, so the PNG
+ // itself is tiny — only the header is read before the cap bails.
+ const sourcePath = join(await tempDir(), 'huge.png');
+ await sharp({
+ create: { width: 4020, height: 4000, channels: 4, background: { r: 30, g: 200, b: 40, alpha: 1 } },
+ }).png().toFile(sourcePath);
+ const result = await prepareSourceImage({ sourcePath, targetPath: join(await tempDir(), 'never3.png') });
+ expect(result).toBeNull();
+ });
+});
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index 3af7fcf897..18dc424da3 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -26,6 +26,7 @@ import { spawn, execFile } from '../../lib/childProcess.js';
import { rewriteGlbMaterialsOpaque } from './glbMaterials.js';
import { getTarget } from './targets.js';
import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';
+import { renderOptionArgs } from './renderOptions.js';
const HOME = homedir();
const IS_WIN = platform() === 'win32';
@@ -444,7 +445,8 @@ export function selectTrellis2TextureSize(unifiedMemoryGb) {
/**
* The generate invocation:
- * `<venv-python> [4k-adapter] generate.py <image> [--output <stem>] --texture-size <n>`.
+ * `<venv-python> [4k-adapter] generate.py <image> [--output <stem>] --texture-size <n>
+ * [--seed <n>] [--steps <n>]`.
*
* Pure. Throws when no source image is given (a render with no input is a bug, not
* an empty run), and when `textureSize` is not one of PortOS's accepted values
@@ -452,8 +454,13 @@ export function selectTrellis2TextureSize(unifiedMemoryGb) {
* `outputPath` is the desired `.glb` disk path; it is reduced to the stem the port
* expects (see `trellis2OutputStem`).
*
+ * `seed` is passed only when provided — callers that care about reproducible runs
+ * (models.js resolves one per run) always pass it; a bare CLI-style call keeps the
+ * port's own default. `steps: null` deliberately omits `--steps` so the pipeline's
+ * per-phase default (12) applies — see renderOptions.js for the sentinel contract.
+ *
* @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,
- * pipelineType?: string}} opts
+ * pipelineType?: string, steps?: number|null, seed?: number|null}} opts
* @returns {{command: string, args: string[]}}
*/
export function buildGenerateArgs({
@@ -462,6 +469,8 @@ export function buildGenerateArgs({
base,
textureSize = TRELLIS2_DEFAULT_TEXTURE_SIZE,
pipelineType = TRELLIS2_BASELINE_PIPELINE_TYPE,
+ steps = null,
+ seed = null,
} = {}) {
if (!imagePath) throw new Error('buildGenerateArgs: imagePath is required');
if (!TRELLIS2_TEXTURE_SIZES.includes(textureSize)) {
@@ -474,6 +483,9 @@ export function buildGenerateArgs({
`buildGenerateArgs: pipelineType must be one of ${TRELLIS2_PIPELINE_TYPES.join(', ')}`,
);
}
+ // Validates steps/seed and emits their flags — shared with the CUDA lane so
+ // neither the ranges nor the flag names can drift (renderOptions.js).
+ const optionArgs = renderOptionArgs('buildGenerateArgs', { steps, seed });
const generateScript = trellis2GenerateScript(base);
const args = textureSize === TRELLIS2_HIGH_QUALITY_TEXTURE_SIZE
? [trellis2GenerateRunnerScript(), generateScript, imagePath]
@@ -481,6 +493,7 @@ export function buildGenerateArgs({
if (outputPath) args.push('--output', trellis2OutputStem(outputPath));
args.push('--pipeline-type', pipelineType);
args.push('--texture-size', String(textureSize));
+ args.push(...optionArgs);
return { command: trellis2VenvPython(base), args };
}
@@ -736,6 +749,7 @@ export function hfGatedRepoHelp(targetId) {
*
* @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,
* pipelineType?: string, unifiedMemoryGb?: number,
+ * steps?: number|null, seed?: number|null,
* onProgress?: (frame: object) => void,
* spawnImpl?: Function, exists?: (p: string) => boolean,
* env?: NodeJS.ProcessEnv, postprocessGlb?: (path: string) => void|Promise<void>}} opts
@@ -748,6 +762,8 @@ export function runTrellis2Generate({
textureSize,
pipelineType,
unifiedMemoryGb = Math.round(totalmem() / 1024 ** 3),
+ steps = null,
+ seed = null,
onProgress,
spawnImpl = spawn,
exists = existsSync,
@@ -767,6 +783,8 @@ export function runTrellis2Generate({
base,
textureSize: resolvedTextureSize,
pipelineType: resolvedPipelineType,
+ steps,
+ seed,
});
return runGenerateSubprocess({
command,
diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.js
index cf6c43e484..e31601ae69 100644
--- a/server/services/imageTo3d/trellis2.test.js
+++ b/server/services/imageTo3d/trellis2.test.js
@@ -250,6 +250,28 @@ describe('buildGenerateArgs', () => {
it('throws when no source image is given', () => {
expect(() => buildGenerateArgs({ base: BASE })).toThrow(/imagePath is required/);
});
+
+ it('passes --seed and --steps when provided and omits both by default', () => {
+ const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE, seed: 1234, steps: 24 });
+ expect(args.slice(-4)).toEqual(['--seed', '1234', '--steps', '24']);
+
+ const { args: defaults } = buildGenerateArgs({ imagePath: 'in.png', base: BASE });
+ expect(defaults).not.toContain('--seed');
+ expect(defaults).not.toContain('--steps');
+ });
+
+ it('rejects out-of-range or non-integer steps and seed instead of letting argparse abort', () => {
+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, steps: 0 }))
+ .toThrow(/steps must be an integer/);
+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, steps: 65 }))
+ .toThrow(/steps must be an integer/);
+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, steps: 12.5 }))
+ .toThrow(/steps must be an integer/);
+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, seed: -1 }))
+ .toThrow(/seed must be an integer/);
+ expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, seed: 2147483648 }))
+ .toThrow(/seed must be an integer/);
+ });
});
describe('selectTrellis2PipelineType', () => {
diff --git a/server/services/imageTo3d/trellis2Cuda.js b/server/services/imageTo3d/trellis2Cuda.js
index e65c312d57..cbc51164a6 100644
--- a/server/services/imageTo3d/trellis2Cuda.js
+++ b/server/services/imageTo3d/trellis2Cuda.js
@@ -46,6 +46,7 @@ import {
trellis2OutputStem,
} from './trellis2.js';
import { textMatcher, runInstallSteps, runGenerateSubprocess } from './laneRunner.js';
+import { renderOptionArgs } from './renderOptions.js';
const HOME = homedir();
@@ -241,8 +242,13 @@ export function selectTrellis2CudaExportBudget(vramGb) {
* disk path, reduced to the stem the runner appends `.glb` to (shared with the MPS
* lane via `trellis2OutputStem`).
*
+ * `seed`/`steps` mirror the MPS lane's contract (see `buildGenerateArgs` in
+ * trellis2.js): both optional, `steps: null` omits the flag so the pipeline's
+ * per-phase default applies.
+ *
* @param {{imagePath: string, outputPath?: string, base?: string, python?: string,
- * textureSize?: number, decimationTarget?: number}} opts
+ * textureSize?: number, decimationTarget?: number,
+ * steps?: number|null, seed?: number|null}} opts
* @returns {{command: string, args: string[]}}
*/
export function buildCudaGenerateArgs({
@@ -252,6 +258,8 @@ export function buildCudaGenerateArgs({
python,
textureSize = TRELLIS2_CUDA_DEFAULT_TEXTURE_SIZE,
decimationTarget = TRELLIS2_CUDA_DEFAULT_DECIMATION,
+ steps = null,
+ seed = null,
} = {}) {
if (!imagePath) throw new Error('buildCudaGenerateArgs: imagePath is required');
if (!TRELLIS2_CUDA_TEXTURE_SIZES.includes(textureSize)) {
@@ -259,6 +267,8 @@ export function buildCudaGenerateArgs({
`buildCudaGenerateArgs: textureSize must be one of ${TRELLIS2_CUDA_TEXTURE_SIZES.join(', ')}`,
);
}
+ // Shared validate-and-emit with the MPS lane — see renderOptions.js.
+ const optionArgs = renderOptionArgs('buildCudaGenerateArgs', { steps, seed });
const args = [
trellis2CudaGenerateRunnerScript(),
imagePath,
@@ -267,6 +277,7 @@ export function buildCudaGenerateArgs({
'--decimation-target', String(decimationTarget),
];
if (outputPath) args.push('--output', trellis2OutputStem(outputPath));
+ args.push(...optionArgs);
return { command: python || trellis2CudaPython({}) || 'python', args };
}
@@ -348,6 +359,7 @@ export function installTrellis2Cuda({
*
* @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,
* decimationTarget?: number, vramGb?: number|null,
+ * steps?: number|null, seed?: number|null,
* onProgress?: (frame: object) => void, spawnImpl?: Function,
* exists?: (p: string) => boolean, env?: NodeJS.ProcessEnv,
* postprocessGlb?: (path: string) => void|Promise<void>}} opts
@@ -360,6 +372,8 @@ export function runTrellis2CudaGenerate({
textureSize,
decimationTarget,
vramGb = null,
+ steps = null,
+ seed = null,
onProgress,
spawnImpl = spawn,
exists = existsSync,
@@ -382,6 +396,8 @@ export function runTrellis2CudaGenerate({
python,
textureSize: textureSize ?? budget.textureSize,
decimationTarget: decimationTarget ?? budget.decimationTarget,
+ steps,
+ seed,
});
return runGenerateSubprocess({
command,
diff --git a/server/services/imageTo3d/trellis2Cuda.test.js b/server/services/imageTo3d/trellis2Cuda.test.js
index 99cbddc8dd..68222b8734 100644
--- a/server/services/imageTo3d/trellis2Cuda.test.js
+++ b/server/services/imageTo3d/trellis2Cuda.test.js
@@ -198,6 +198,21 @@ describe('buildCudaGenerateArgs', () => {
expect(() => args({ textureSize: 8192 })).toThrow(/must be one of/);
expect(TRELLIS2_CUDA_TEXTURE_SIZES).not.toContain(8192);
});
+
+ it('passes --seed and --steps when provided and omits both by default (MPS-lane parity)', () => {
+ const { args: argv } = args({ seed: 1234, steps: 24 });
+ expect(argv[argv.indexOf('--seed') + 1]).toBe('1234');
+ expect(argv[argv.indexOf('--steps') + 1]).toBe('24');
+
+ const { args: defaults } = args();
+ expect(defaults).not.toContain('--seed');
+ expect(defaults).not.toContain('--steps');
+ });
+
+ it('rejects out-of-range steps and seed here rather than in the child’s argparse', () => {
+ expect(() => args({ steps: 0 })).toThrow(/steps must be an integer/);
+ expect(() => args({ seed: -1 })).toThrow(/seed must be an integer/);
+ });
});
describe('installTrellis2Cuda', () => {
diff --git a/server/services/imageTo3d/trellis2CudaGenerateRunner.py b/server/services/imageTo3d/trellis2CudaGenerateRunner.py
index 09efabc6ee..4f7d0d1b6a 100644
--- a/server/services/imageTo3d/trellis2CudaGenerateRunner.py
+++ b/server/services/imageTo3d/trellis2CudaGenerateRunner.py
@@ -50,6 +50,14 @@ def parse_args():
default="microsoft/TRELLIS.2-4B",
help="Hugging Face repo id for the pipeline weights",
)
+ # Both mirror the Apple-Silicon port's generate.py so the two lanes accept the
+ # same knobs: --seed matches its fixed default, --steps overrides the sampler
+ # step count for all three flow phases (None -> the pipeline JSON default, 12).
+ parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)")
+ parser.add_argument(
+ "--steps", type=int, default=None,
+ help="Override sampler steps for all three flow phases (default: pipeline JSON)",
+ )
return parser.parse_args()
@@ -84,11 +92,19 @@ def main():
pipeline.cuda()
image = Image.open(image_path)
- log("Generating 3D model...")
+ log(f"Generating 3D model (seed={args.seed})...")
started = time.time()
# The pipeline's own sampling loops print tqdm bars; the parent scales those into
- # its sampling band, so nothing extra is emitted here.
- mesh = pipeline.run(image)[0]
+ # its sampling band, so nothing extra is emitted here. The sampler override shape
+ # mirrors the Apple-Silicon port's generate.py exactly.
+ sampler_overrides = {"steps": args.steps} if args.steps else {}
+ mesh = pipeline.run(
+ image,
+ seed=args.seed,
+ sparse_structure_sampler_params=sampler_overrides,
+ shape_slat_sampler_params=sampler_overrides,
+ tex_slat_sampler_params=sampler_overrides,
+ )[0]
# nvdiffrast cannot rasterize past 2^24 triangles; upstream simplifies to that
# ceiling before any export work. This is the hard renderer limit, distinct from