import { useId, useRef, useState } from 'react' import { Box, Download, Loader2, Paintbrush, Square } from 'lucide-react' import { useGenerate3dModel } from '@tanstack/ai-react' import type { Fal3dModelProviderOptions } from '@tanstack/ai-fal' import type { MediaPrompt, MediaPromptPart } from '@tanstack/ai/client' import type { Model3dFile } from '@tanstack/ai' import { GlbViewer } from '@/components/GlbViewer' import { SeedImageField } from '@/components/SeedImageField' import { byok, callWithByok, falByok } from '@/lib/byok' import { readMediaFile, toImagePart } from '@/lib/media' import { MESH_TOOL_MODELS, MODEL3D_MODELS } from '@/lib/models' import { generate3dModelFn } from '@/lib/server-functions' /** Which step made the model on screen. */ type Step = 'base' | 'retexture' const STEP_LABELS: Record = { base: 'Image to 3D', retexture: 'Retexture', } interface Run { step: Step model: string prompt: MediaPrompt modelOptions?: Record } interface Progress { value: number message?: string } const FOCUS_RING = 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-400' const FIELD_CLASS = `w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 disabled:opacity-50 ${FOCUS_RING}` function describeProgress(progress: Progress | null) { switch (progress?.message) { case undefined: return 'Sending the request…' case 'pending': return 'Waiting in the fal queue…' case 'processing': return 'Building the model…' case 'completed': return 'Reading the result…' default: return 'Working…' } } function describeFile(file: Model3dFile, index: number) { const role = file.role ? ` (${file.role})` : '' const kind = file.format ? file.format.toUpperCase() : (file.contentType ?? 'file') return `File ${index + 1}: ${kind}${role}` } function meshPart(url: string): MediaPromptPart { return { type: 'model3d', source: { type: 'url', value: url } } } /** * Image-to-3D with fal, then an optional retexture of the result: new * textures from a reference image. Retexture takes the current model as a * `model3d` prompt part, so it can run again on its own result. */ export default function Model3dGenerator() { const [files, setFiles] = useState>([]) const [modelId, setModelId] = useState(MODEL3D_MODELS[0].id) const [textHint, setTextHint] = useState('') const [styleFiles, setStyleFiles] = useState>([]) const [step, setStep] = useState('base') const [progress, setProgress] = useState(null) // The step that made the model on screen, and an image read error. const [resultStep, setResultStep] = useState('base') const [readError, setReadError] = useState(null) const stepRef = useRef('base') // Guard Generate and Retexture from file read through generation so a // second click cannot overwrite the accepted run. const inFlightRef = useRef(false) // The hook builds its client once. Each run stores its endpoint on this // map, keyed by the generate input object, so the fetcher does not read a // shared current-endpoint ref after BYOK. const endpointByInput = useRef(new WeakMap()) const modelSelectId = useId() const textHintId = useId() const resultHeadingId = useId() const toolsHeadingId = useId() const selected = MODEL3D_MODELS.find((model) => model.id === modelId) ?? MODEL3D_MODELS[0] const { generate, result, isLoading, error, stop } = useGenerate3dModel({ threadId: 'media-3d', byok, byokProvider: () => falByok.id, fetcher: (input, options) => callWithByok( generate3dModelFn({ data: { model: endpointByInput.current.get(input) ?? MODEL3D_MODELS[0].id, prompt: input.prompt, ...(input.modelOptions ? { modelOptions: input.modelOptions } : {}), }, signal: options.signal, headers: options.headers, }), ), onProgress: (value, message) => setProgress({ value, message }), onResult: () => { setResultStep(stepRef.current) }, }) const run = (next: Run) => { const input = { prompt: next.prompt, ...(next.modelOptions ? { modelOptions: next.modelOptions } : {}), } endpointByInput.current.set(input, next.model) stepRef.current = next.step setStep(next.step) setProgress(null) void generate(input).finally(() => { inFlightRef.current = false }) } const handleGenerate = async () => { const file = files[0] if (!file || isLoading || inFlightRef.current) return inFlightRef.current = true setReadError(null) try { const image = toImagePart(await readMediaFile(file)) const text = textHint.trim() const sendText = selected.takesText && text.length > 0 run({ step: 'base', model: selected.id, prompt: sendText ? [{ type: 'text', content: text }, image] : [image], }) } catch { inFlightRef.current = false setReadError(`Could not read ${file.name}.`) } } // A failed run keeps the previous model on the hook. After a failed base // run, hide it so it does not look like the result of that run. After a // failed retexture, keep it, so the user can retexture it again. const shown = result && !isLoading && (!error || step === 'retexture') ? result : null const isGlb = shown?.format === 'glb' const handleRetexture = async () => { const styleFile = styleFiles[0] if (!shown || !styleFile || isLoading || inFlightRef.current) return inFlightRef.current = true setReadError(null) try { const reference = toImagePart(await readMediaFile(styleFile)) const modelOptions = { enable_pbr: true, texture_resolution: '2k', } satisfies Fal3dModelProviderOptions< typeof MESH_TOOL_MODELS.retexture.id > run({ step: 'retexture', model: MESH_TOOL_MODELS.retexture.id, prompt: [meshPart(shown.url), reference], modelOptions, }) } catch { inFlightRef.current = false setReadError(`Could not read ${styleFile.name}.`) } } const statusText = isLoading ? `${STEP_LABELS[step]}: ${describeProgress(progress)}` : shown && !error ? `${STEP_LABELS[resultStep]} is ready.` : '' const errorText = readError ?? (error && !isLoading ? error.message : null) const progressValue = progress && progress.value > 0 ? progress.value : undefined const downloads: Array = shown ? (shown.files ?? [{ url: shown.url, format: shown.format }]) : [] return (

Source image

{selected.takesText ? (
setTextHint(event.target.value)} disabled={isLoading} placeholder="For example: a wooden chair with a red cushion" className={FIELD_CLASS} />
) : null}
{isLoading ? ( ) : null}

{statusText}

{isLoading ? ( ) : null} {errorText ? (

{errorText}

) : null}
{shown ? (

Result: {STEP_LABELS[resultStep]}

{isGlb ? ( ) : (

This model is a {shown.format.toUpperCase()} file. The preview and the mesh tools need a GLB file. Use the download links.

)} {shown.previewImageUrl ? ( Preview render of the generated 3D model ) : null}

Downloads

{isGlb ? (

Retexture

Paints the model above with the look of a reference image, and shows the new result.

) : null}
) : null}
) }