Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: forge multiview/segment/stylize/animation, remesh + texture worker upgrades
nirholas274f2ad47900
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 4b7eaebd5..0a34073cd 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -67,6 +67,10 @@ export async function createCreation({previewImageUrl,replicateJobId,textToImageModel,+ viewsRequested,+ viewsUsed,+ multiview,+ backend,}) {if (!forgeStoreEnabled()) return null;const id = randomUUID();@@ -74,11 +78,14 @@ export async function createCreation({await sql`insert into forge_creations(id, client_key, ip_hash, prompt, aspect, preview_image_url,- replicate_job_id, text_to_image_model, status, outcome)+ replicate_job_id, text_to_image_model, views_requested, views_used,+ multiview, backend, status, outcome)values(${id}, ${clientKey}, ${ipHash ?? null}, ${prompt}, ${aspect ?? null},${previewImageUrl ?? null}, ${replicateJobId ?? null},- ${textToImageModel ?? null}, 'generating', 'generated')+ ${textToImageModel ?? null}, ${viewsRequested ?? null}, ${viewsUsed ?? null},+ ${typeof multiview === 'boolean' ? multiview : null}, ${backend ?? null},+ 'generating', 'generated')`;return id;} catch (err) {@@ -93,7 +100,8 @@ export async function findByJob({ replicateJobId, clientKey }) {if (!forgeStoreEnabled() || !replicateJobId) return null;try {const rows = await sql`- select id, status, glb_url, glb_key, prompt, preview_image_url+ select id, status, glb_url, glb_key, prompt, preview_image_url,+ views_requested, views_used, multiview, backendfrom forge_creationswhere replicate_job_id = ${replicateJobId} and client_key = ${clientKey}limit 1@@ -232,7 +240,8 @@ export async function listCreations({ clientKey, limit = 24 }) {const capped = Math.min(Math.max(Number(limit) || 24, 1), 48);try {const rows = await sql`- select id, prompt, aspect, glb_url, preview_image_url, outcome, downloaded, created_at+ select id, prompt, aspect, glb_url, preview_image_url, outcome, downloaded,+ views_used, multiview, backend, created_atfrom forge_creationswhere client_key = ${clientKey} and status = 'done' and glb_url is not nullorder by created_at desc@@ -246,6 +255,9 @@ export async function listCreations({ clientKey, limit = 24 }) {preview_image_url: r.preview_image_url,outcome: r.outcome,downloaded: r.downloaded,+ views_used: r.views_used ?? null,+ multiview: r.multiview ?? null,+ backend: r.backend ?? null,created_at: r.created_at,}));} catch (err) {diff --git a/api/_lib/migrations/20260606000000_forge_multiview.sql b/api/_lib/migrations/20260606000000_forge_multiview.sqlnew file mode 100644index 000000000..6628c4630--- /dev/null+++ b/api/_lib/migrations/20260606000000_forge_multiview.sql@@ -0,0 +1,18 @@+-- Forge multi-view reconstruction — record how a generation was conditioned.+--+-- /forge previously fed a single reference image (or one synthesized from a+-- prompt) into the reconstruction model. Multi-view conditioning (2–4 calibrated+-- views of the same object — front / back / left / right) removes the back-of-+-- object hallucination single-image reconstruction is forced into, and the+-- backends we already use (TRELLIS, Hunyuan3D) fuse those views natively.+--+-- These columns capture, per generation: how many views the caller supplied,+-- how many the chosen backend actually fused (they differ when a single-view+-- model is configured and we fall back to the primary view), whether multi-view+-- conditioning was truly used, and which backend handled it. They are surfaced+-- in the submit + poll responses so a downgrade is always reported, never silent.++alter table forge_creations add column if not exists views_requested smallint;+alter table forge_creations add column if not exists views_used smallint;+alter table forge_creations add column if not exists multiview boolean;+alter table forge_creations add column if not exists backend text;diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex fc5190dea..38a810235 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -152,16 +152,23 @@ export const toolDefs = [},{name: 'image_to_3d',- title: 'Reconstruct a 3D model from an image',+ title: 'Reconstruct a 3D model from one or more images',description:- 'Reconstruct a textured 3D model (GLB) from a single reference image URL using Microsoft TRELLIS. Returns a job_id to poll with generation_status. The cleaner the input — one subject, plain background, even lighting — the better the mesh.',+ 'Reconstruct a textured 3D model (GLB) from a reference image using Microsoft TRELLIS. Pass a single image_url, or image_urls (2–4 views of the SAME object from different angles — front/back/left/right) for multi-view reconstruction, which removes the back-of-object hallucination of single-image reconstruction. Returns a job_id to poll with generation_status, plus how many views were fused and which backend handled it. The cleaner the inputs — one subject, plain background, even lighting — the better the mesh.',inputSchema: {type: 'object',properties: {image_url: {type: 'string',format: 'uri',- description: 'Public https URL of the reference image (PNG/JPG/WebP).',+ description: 'Public https URL of the reference image (PNG/JPG/WebP). Use image_urls for multi-view.',+ },+ image_urls: {+ type: 'array',+ items: { type: 'string', format: 'uri' },+ minItems: 1,+ maxItems: 4,+ description: '1–4 public https URLs of the same object from different angles. Takes precedence over image_url; >1 enables multi-view reconstruction.',},prompt: {type: 'string',@@ -169,33 +176,78 @@ export const toolDefs = [description: 'Optional text hint passed to the reconstruction model.',},},- required: ['image_url'],additionalProperties: false,},async handler(args, auth) {await enforce(limits.mcp3dGenerate, auth);- if (!(await isPublicHttpsUrl(args.image_url))) {++ // Merge the multi-view array form with the single image_url, de-duped+ // and order-preserving. image_urls wins when both are present.+ const rawViews = Array.isArray(args.image_urls)+ ? args.image_urls+ : typeof args.image_url === 'string'+ ? [args.image_url]+ : [];+ const seen = new Set();+ const views = [];+ for (const v of rawViews) {+ if (typeof v !== 'string') continue;+ const t = v.trim();+ if (!t || seen.has(t)) continue;+ seen.add(t);+ views.push(t);+ }+ if (views.length === 0) {return {- content: [{ type: 'text', text: 'Error: image_url must be a public https URL.' }],+ content: [{ type: 'text', text: 'Error: provide image_url or image_urls (1–4).' }],isError: true,};}+ if (views.length > 4) {+ return {+ content: [{ type: 'text', text: 'Error: provide between 1 and 4 images.' }],+ isError: true,+ };+ }+ for (const v of views) {+ if (!(await isPublicHttpsUrl(v))) {+ return {+ content: [+ { type: 'text', text: 'Error: every image URL must be a public https URL.' },+ ],+ isError: true,+ };+ }+ }+const provider = regenProvider();const job = await provider.submit({mode: 'reconstruct',- params: { image: args.image_url, prompt: args.prompt },+ sourceUrl: views[0],+ params: { images: views, prompt: args.prompt },});+ const viewsUsed = typeof job.viewsUsed === 'number' ? job.viewsUsed : views.length;+ const multiview = Boolean(job.multiview);+ const summary =+ views.length > 1+ ? `Started multi-view reconstruction from ${views.length} views (${viewsUsed} fused${multiview ? '' : ', single-view fallback'}).`+ : 'Started reconstructing a 3D model from the image.';return {content: [{type: 'text',- text: `Started reconstructing a 3D model from the image.\nJob ID: ${job.extJobId}\n${POLL_HINT}`,+ text: `${summary}\nJob ID: ${job.extJobId}\n${POLL_HINT}`,},],structuredContent: {job_id: job.extJobId,status: 'queued',- source_image_url: args.image_url,+ source_image_url: views[0],+ source_image_urls: views,+ views_requested: views.length,+ views_used: viewsUsed,+ multiview,+ backend: job.backend ?? null,eta_seconds: job.eta,},};@@ -433,6 +485,84 @@ export const toolDefs = [};},},+ {+ name: 'stylize_model',+ title: 'Apply a one-click geometric stylization filter to a 3D model',+ description:+ 'Transform any GLB/OBJ/STL/PLY mesh into a stylized variant with a single geometry pass — ' ++ 'no model inference, fast and cheap. Styles: "voxel" (blocky cubes on a grid), "brick" ' ++ '(voxels + studs, LEGO-like), "voronoi" (open strut-and-node lattice shell), "lowpoly" ' ++ '(decimated + hard flat-shaded facets). Source color is preserved where the style allows. ' ++ 'Returns a job_id to poll with generation_status; typically completes in 10–40 seconds.',+ inputSchema: {+ type: 'object',+ properties: {+ mesh_url: {+ type: 'string',+ format: 'uri',+ description: 'Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY).',+ },+ style: {+ type: 'string',+ enum: ['voxel', 'brick', 'voronoi', 'lowpoly'],+ default: 'voxel',+ description:+ 'voxel = blocky cubes; brick = voxels + studs (LEGO-like); voronoi = open lattice shell; lowpoly = faceted flat-shaded.',+ },+ resolution: {+ type: 'integer',+ minimum: 8,+ maximum: 120,+ description:+ 'Style-specific density (clamped per style): voxel/brick = grid resolution, voronoi = cell density, lowpoly = detail level. Omit for a sensible per-style default.',+ },+ output_format: {+ type: 'string',+ enum: ['glb', 'obj', 'stl', 'ply'],+ default: 'glb',+ },+ },+ required: ['mesh_url'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcp3dGenerate, auth);+ if (!(await isPublicHttpsUrl(args.mesh_url))) {+ return {+ content: [{ type: 'text', text: 'Error: mesh_url must be a public https URL.' }],+ isError: true,+ };+ }+ const provider = regenProvider('stylize');+ const style = args.style || 'voxel';+ const job = await provider.submit({+ mode: 'stylize',+ sourceUrl: args.mesh_url,+ params: {+ style,+ resolution: Number.isInteger(args.resolution) ? args.resolution : null,+ output_format: args.output_format || 'glb',+ },+ });+ return {+ content: [+ {+ type: 'text',+ text:+ `Stylization started (${style}).\nJob ID: ${job.extJobId}\n` ++ 'Poll with generation_status. Typically completes in 10–40 seconds.',+ },+ ],+ structuredContent: {+ job_id: job.extJobId,+ status: 'queued',+ source_mesh_url: args.mesh_url,+ style,+ eta_seconds: job.eta,+ },+ };+ },+ },{name: 'retexture_model',title: 'Paint a new texture onto a 3D model from a text prompt',diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 7f94214b9..590b85089 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -9,8 +9,10 @@// POST /reconstruct → { job_id } GET /jobs/:id → { status, glb_url }//// remesh → GCP_REMESH_URL (workers/remesh)+// stylize → GCP_STYLIZE_URL (workers/stylize)// retex → GCP_TEXTURE_URL (workers/texture)// rembg → GCP_REMBG_URL (workers/rembg)+// segment → GCP_SEGMENT_URL (workers/segment)// rerig → GCP_RECONSTRUCTION_URL (avatar-pipeline-controller, /rig endpoint)//// All workers share the same bearer secret (GCP_RECONSTRUCTION_KEY).@@ -54,10 +56,14 @@ function serviceUrlForMode(mode) {return readEnv('GCP_RECONSTRUCTION_URL');case 'remesh':return readEnv('GCP_REMESH_URL');+ case 'stylize':+ return readEnv('GCP_STYLIZE_URL');case 'retex':return readEnv('GCP_TEXTURE_URL');case 'rembg':return readEnv('GCP_REMBG_URL');+ case 'segment':+ return readEnv('GCP_SEGMENT_URL');case 'rerig':// Rigging is handled by the pipeline controller via its /rig endpoint.return readEnv('GCP_RECONSTRUCTION_URL');@@ -87,8 +93,23 @@ function buildWorkerRequest(request) {resultKey: 'result_url',body: {mesh: sourceUrl,+ remesh_mode: params?.remesh_mode || 'triangle',operation: params?.operation || 'full',target_faces: params?.target_faces || 50_000,+ texture_size: params?.texture_size || 1024,+ output_format: params?.output_format || 'glb',+ },+ };+ }++ if (mode === 'stylize') {+ return {+ path: '/process',+ resultKey: 'result_url',+ body: {+ mesh: sourceUrl,+ style: params?.style || 'voxel',+ resolution: params?.resolution ?? null,output_format: params?.output_format || 'glb',},};@@ -119,6 +140,21 @@ function buildWorkerRequest(request) {};}+ if (mode === 'segment') {+ return {+ path: '/segment',+ resultKey: 'result_url',+ body: {+ mesh: sourceUrl,+ method: params?.method || 'auto',+ max_parts: params?.max_parts || 24,+ min_part_faces: params?.min_part_faces || 64,+ crease_angle: params?.crease_angle ?? 40,+ ...(params?.only_part ? { only_part: params.only_part } : {}),+ },+ };+ }+if (mode === 'rerig') {return {path: '/rig',@@ -138,8 +174,10 @@ function buildWorkerRequest(request) {const MODE_ETA = {reconstruct: 120,remesh: 30,+ stylize: 25,retex: 180,rembg: 5,+ segment: 45,rerig: 45,};@@ -159,6 +197,13 @@ export function createRegenProvider() {return Boolean(serviceUrlForMode(mode));},+ // The reconstruction worker accepts an `images` array and fuses every+ // supplied view, so multi-view conditioning is available whenever the+ // reconstruct service is configured.+ supportsMultiview() {+ return Boolean(serviceUrlForMode('reconstruct'));+ },+async submit(request) {const { mode } = request;const baseUrl = serviceUrlForMode(mode);@@ -209,9 +254,19 @@ export function createRegenProvider() {);}+ // Report how the job was conditioned. For reconstruct the worker fuses+ // every image in the body; other modes are single-source.+ const viewsUsed =+ mode === 'reconstruct' && Array.isArray(workerReq.body.images)+ ? workerReq.body.images.length+ : 0;+return {extJobId: packJobId({ mode, taskId, baseUrl, resultKey: workerReq.resultKey }),eta: MODE_ETA[mode] ?? 60,+ backend: 'gcp',+ multiview: viewsUsed > 1,+ viewsUsed,};},@@ -264,6 +319,24 @@ export function createRegenProvider() {} else {result.resultGlbUrl = url;}+ // Surface remesh telemetry so callers can show topology stats.+ if (mode === 'remesh') {+ if (typeof data.face_count === 'number') result.faceCount = data.face_count;+ if (typeof data.quad_ratio === 'number') result.quadRatio = data.quad_ratio;+ if (typeof data.textured === 'boolean') result.textured = data.textured;+ if (data.texture_url) result.textureUrl = data.texture_url;+ if (data.mode) result.mode = data.mode;+ }+ // Surface the parts manifest so callers can render a selectable+ // part list without a second fetch.+ if (mode === 'segment') {+ if (data.manifest_url) result.manifestUrl = data.manifest_url;+ if (Array.isArray(data.parts)) result.parts = data.parts;+ if (typeof data.part_count === 'number') result.partCount = data.part_count;+ if (typeof data.source_faces === 'number') result.sourceFaces = data.source_faces;+ if (data.method) result.segmentMethod = data.method;+ if (Array.isArray(data.warnings) && data.warnings.length) result.warnings = data.warnings;+ }}if (status === 'failed') {diff --git a/api/_providers/replicate.js b/api/_providers/replicate.jsindex 2b7b8718d..41bfc489a 100644--- a/api/_providers/replicate.js+++ b/api/_providers/replicate.js@@ -66,6 +66,44 @@ function modelForMode(mode) {return readEnv(envName) || DEFAULT_MODELS[mode] || null;}+// Models known to fuse more than one conditioning image into a single mesh+// (true multi-view reconstruction). `firtoz/trellis` (Microsoft TRELLIS) takes+// an `images` array and reconstructs from all supplied views; the Tencent+// Hunyuan3D multi-view variants do the same. Slug-matched (the :version suffix+// is ignored) so a pinned build of a known model still counts.+const MULTIVIEW_CAPABLE_SLUGS = Object.freeze([+ 'firtoz/trellis',+ 'tencent/hunyuan3d-2mv',+ 'tencent/hunyuan-3d-2mv',+]);++// A dedicated multi-view model can be configured explicitly; when set it is+// assumed multi-view capable and preferred for >1-view reconstructions.+function multiviewModel() {+ return readEnv('REPLICATE_MULTIVIEW_MODEL') || null;+}++function isMultiviewCapable(modelRef) {+ if (!modelRef) return false;+ const slug = String(modelRef).split(':')[0].toLowerCase();+ return MULTIVIEW_CAPABLE_SLUGS.includes(slug);+}++// Pick the reconstruction model + whether it can fuse multiple views, given how+// many views the caller supplied. A dedicated REPLICATE_MULTIVIEW_MODEL wins for+// >1 view; otherwise the standard reconstruct model is used and multi-view is+// claimed only when that model is actually capable of it (so a single-view model+// like TripoSR never silently pretends to fuse views).+function resolveReconstruct(imageCount) {+ const reconstruct = modelForMode('reconstruct');+ if (imageCount > 1) {+ const mv = multiviewModel();+ if (mv) return { modelRef: mv, multiview: true };+ return { modelRef: reconstruct, multiview: isMultiviewCapable(reconstruct) };+ }+ return { modelRef: reconstruct, multiview: false };+}+// Keys that belong to OUR job/contract envelope and must never be forwarded to// a Replicate model. Replicate validates prediction input against each model's// OpenAPI schema; leaking these (or the multi-MB base64 image list) risks a 422@@ -100,15 +138,20 @@ function stripInternal(params) {// For `reconstruct` (image-to-3D) the canonical input across the Hunyuan3D// family, TRELLIS and TripoSR is an `images` array of URIs — we always send// that and never the singular `image`/`mode` fields the old payload leaked.-function buildInput({ mode, sourceUrl, params }) {+function buildInput({ mode, sourceUrl, params, images }) {const clean = stripInternal(params);if (mode === 'reconstruct') {- const photos = Array.isArray(params?.images)- ? params.images.filter((u) => typeof u === 'string' && u.length > 0)- : [];+ // `images` is the already-resolved view list (trimmed to what the chosen+ // model can fuse). Fall back to params.images / the source url so callers+ // that don't pre-resolve still work.+ const photos = Array.isArray(images)+ ? images.filter((u) => typeof u === 'string' && u.length > 0)+ : Array.isArray(params?.images)+ ? params.images.filter((u) => typeof u === 'string' && u.length > 0)+ : [];const primary = photos[0] || (typeof params?.image === 'string' ? params.image : sourceUrl);- const images = photos.length ? photos : primary ? [primary] : [];- return { images, ...clean };+ const finalImages = photos.length ? photos : primary ? [primary] : [];+ return { images: finalImages, ...clean };}// remesh / retex / rerig / restyle operate on an existing GLB. Send the// source under the two field names cog GLB-pipelines commonly accept.@@ -185,8 +228,38 @@ export function createRegenProvider() {return !!modelForMode(mode);},+ // True when this provider can fuse >1 reference image into one mesh —+ // either a dedicated REPLICATE_MULTIVIEW_MODEL is set, or the configured+ // reconstruct model is itself multi-view capable (TRELLIS by default).+ supportsMultiview() {+ return Boolean(multiviewModel()) || isMultiviewCapable(modelForMode('reconstruct'));+ },+async submit(request) {- const modelRef = modelForMode(request.mode);+ // Resolve the model + view handling. For reconstruct, the model and+ // whether multi-view is honored depends on how many views were supplied;+ // other modes map straight to their configured model.+ let modelRef;+ let multiview = false;+ let viewsUsed = 0;+ let images;+ if (request.mode === 'reconstruct') {+ const supplied = Array.isArray(request.params?.images)+ ? request.params.images.filter((u) => typeof u === 'string' && u.length > 0)+ : [];+ const requested = supplied.length || (request.sourceUrl ? 1 : 0);+ const resolved = resolveReconstruct(requested);+ modelRef = resolved.modelRef;+ multiview = resolved.multiview;+ // When the chosen model can't fuse views, condition on the primary+ // image only — never feed extra views a single-view model will ignore+ // or reject. This is the graceful downgrade the caller surfaces.+ images = multiview ? supplied : supplied.slice(0, 1);+ viewsUsed = images.length || (request.sourceUrl ? 1 : 0);+ } else {+ modelRef = modelForMode(request.mode);+ }+if (!modelRef) {throw Object.assign(new Error(@@ -200,6 +273,7 @@ export function createRegenProvider() {mode: request.mode,sourceUrl: request.sourceUrl,params: request.params,+ images,});// Two Replicate API shapes:@@ -266,6 +340,10 @@ export function createRegenProvider() {extJobId: data.id,eta: typeof data.eta === 'number' ? data.eta : undefined,rawStatus: data.status,+ backend: 'replicate',+ model: modelRef,+ multiview,+ viewsUsed,};},diff --git a/api/chat.js b/api/chat.jsindex 58cda468b..85ef1a550 100644--- a/api/chat.js+++ b/api/chat.js@@ -568,12 +568,21 @@ export default wrap(async (req, res) => {// The frontend renders `error_description` directly in the chat UI. We do// surface the (provider-name-only) list of what was tried so the client can// show "tried groq, openrouter…" without leaking upstream internals.+ //+ // Status semantics: when the chain gave up because every route was+ // *rate-limited* (429 — the common free-tier exhaustion in prod), that's+ // capacity, not breakage. Return 503 with Retry-After so the client backs+ // off and retries instead of treating it as a hard upstream failure (502).+ const rateLimited = upstream.status === 429;+ if (rateLimited) res.setHeader('Retry-After', '20');return error(res,- 502,- 'upstream_error',- 'The AI chat provider is temporarily unavailable. Please try again in a moment.',- { providers_tried: providersTried(attempted) },+ rateLimited ? 503 : 502,+ rateLimited ? 'rate_limited' : 'upstream_error',+ rateLimited+ ? 'The AI chat is at capacity right now. Please try again in a few seconds.'+ : 'The AI chat provider is temporarily unavailable. Please try again in a moment.',+ { providers_tried: providersTried(attempted), ...(rateLimited ? { retry_after: 20 } : {}) },);}diff --git a/api/forge-remesh.js b/api/forge-remesh.jsindex 451ca90e4..20c669990 100644--- a/api/forge-remesh.js+++ b/api/forge-remesh.js@@ -3,13 +3,15 @@** POST /api/forge-remesh {* mesh_url: string,- * operation?: "full"|"simplify"|"repair"|"convert",+ * remesh_mode?: "triangle"|"quad"|"lowpoly",+ * operation?: "full"|"simplify"|"repair"|"convert", // triangle mode only* target_faces?: number,+ * texture_size?: 512|1024|2048,* output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf"* } → 202 { job_id, status }** GET /api/forge-remesh?job=<id>- * → { job_id, status, result_url?, face_count?, error? }+ * → { job_id, status, result_url?, texture_url?, face_count?, quad_ratio?, textured?, mode?, error? }** Routes to workers/remesh (GCP Cloud Run) when GCP_REMESH_URL is set.*/@@ -21,6 +23,8 @@ import { createRegenProvider } from './_providers/gcp.js';const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;const VALID_OPERATIONS = new Set(['full', 'simplify', 'repair', 'convert']);const VALID_FORMATS = new Set(['glb', 'obj', 'stl', 'ply', 'usdz', '3mf']);+const VALID_MODES = new Set(['triangle', 'quad', 'lowpoly']);+const VALID_TEXTURE_SIZES = new Set([512, 1024, 2048]);function unconfigured(res) {return json(res, 503, {@@ -47,9 +51,13 @@ async function startJob(req, res) {return json(res, 400, { error: 'invalid_mesh_url', message: 'mesh_url must be a public https URL.' });}+ const remeshMode = VALID_MODES.has(body?.remesh_mode) ? body.remesh_mode : 'triangle';const operation = VALID_OPERATIONS.has(body?.operation) ? body.operation : 'full';const outputFormat = VALID_FORMATS.has(body?.output_format) ? body.output_format : 'glb';const targetFaces = Math.max(1_000, Math.min(500_000, Number(body?.target_faces) || 50_000));+ const textureSize = VALID_TEXTURE_SIZES.has(Number(body?.texture_size))+ ? Number(body.texture_size)+ : 1024;let provider;try {@@ -63,11 +71,18 @@ async function startJob(req, res) {const job = await provider.submit({mode: 'remesh',sourceUrl: meshUrl,- params: { operation, target_faces: targetFaces, output_format: outputFormat },+ params: {+ remesh_mode: remeshMode,+ operation,+ target_faces: targetFaces,+ texture_size: textureSize,+ output_format: outputFormat,+ },});return json(res, 202, {job_id: job.extJobId,status: 'queued',+ remesh_mode: remeshMode,operation,output_format: outputFormat,eta_seconds: job.eta,@@ -99,7 +114,11 @@ async function pollJob(req, res, jobId) {job_id: jobId,status: result.status,result_url: result.resultGlbUrl || null,- face_count: result.faceCount || null,+ texture_url: result.textureUrl || null,+ face_count: typeof result.faceCount === 'number' ? result.faceCount : null,+ quad_ratio: typeof result.quadRatio === 'number' ? result.quadRatio : null,+ textured: typeof result.textured === 'boolean' ? result.textured : null,+ mode: result.mode || null,error: result.error || null,});}diff --git a/api/forge-segment.js b/api/forge-segment.jsnew file mode 100644index 000000000..ea0bd557b--- /dev/null+++ b/api/forge-segment.js@@ -0,0 +1,135 @@+/**+ * /api/forge-segment — split a 3D model into named, addressable parts.+ *+ * POST /api/forge-segment {+ * mesh_url: string,+ * method?: "auto"|"connected"|"crease",+ * max_parts?: number, // 2–64+ * min_part_faces?: number, // 4–100000+ * crease_angle?: number, // 5–170 (degrees)+ * only_part?: string // export just this part id/name (e.g. "part_03")+ * } → 202 { job_id, status }+ *+ * GET /api/forge-segment?job=<id>+ * → { job_id, status, result_url?, manifest_url?, parts?, part_count?,+ * source_faces?, method?, warnings?, error? }+ *+ * Routes to workers/segment (GCP Cloud Run) when GCP_SEGMENT_URL is set.+ */++import { cors, json, method, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { createRegenProvider } from './_providers/gcp.js';++const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;+const VALID_METHODS = new Set(['auto', 'connected', 'crease']);+const PART_REF_RE = /^[A-Za-z0-9_-]{1,64}$/;++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Part segmentation is not configured. Set GCP_SEGMENT_URL and GCP_RECONSTRUCTION_KEY ' ++ 'to the URL and bearer secret of your deployed workers/segment Cloud Run service.',+ });+}++async function startJob(req, res) {+ const ip = clientIp(req);+ const rl = await limits.mcp3dGenerate(ip);+ if (!rl.success) {+ return json(res, 429, {+ error: 'rate_limited',+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }++ const body = await readJson(req, 4_000).catch(() => null);+ const meshUrl = typeof body?.mesh_url === 'string' ? body.mesh_url.trim() : '';+ if (!meshUrl.startsWith('https://')) {+ return json(res, 400, { error: 'invalid_mesh_url', message: 'mesh_url must be a public https URL.' });+ }++ const segMethod = VALID_METHODS.has(body?.method) ? body.method : 'auto';+ const maxParts = Math.max(2, Math.min(64, Number(body?.max_parts) || 24));+ const minPartFaces = Math.max(4, Math.min(100_000, Number(body?.min_part_faces) || 64));+ const creaseAngle = Math.max(5, Math.min(170, Number(body?.crease_angle) || 40));+ const onlyPart =+ typeof body?.only_part === 'string' && PART_REF_RE.test(body.only_part.trim())+ ? body.only_part.trim()+ : undefined;++ let provider;+ try {+ provider = createRegenProvider();+ if (!provider.supportsMode('segment')) return unconfigured(res);+ } catch {+ return unconfigured(res);+ }++ try {+ const job = await provider.submit({+ mode: 'segment',+ sourceUrl: meshUrl,+ params: {+ method: segMethod,+ max_parts: maxParts,+ min_part_faces: minPartFaces,+ crease_angle: creaseAngle,+ only_part: onlyPart,+ },+ });+ return json(res, 202, {+ job_id: job.extJobId,+ status: 'queued',+ method: segMethod,+ eta_seconds: job.eta,+ });+ } catch (err) {+ return json(res, 502, { error: 'segment_failed', message: err?.message || 'Segmentation could not start.' });+ }+}++async function pollJob(req, res, jobId) {+ if (!JOB_ID_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });+ }++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) {+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });+ }++ let provider;+ try {+ provider = createRegenProvider();+ } catch {+ return unconfigured(res);+ }++ const result = await provider.status(jobId);+ return json(res, 200, {+ job_id: jobId,+ status: result.status,+ result_url: result.resultGlbUrl || null,+ manifest_url: result.manifestUrl || null,+ parts: result.parts || null,+ part_count: result.partCount ?? null,+ source_faces: result.sourceFaces ?? null,+ method: result.segmentMethod || null,+ warnings: result.warnings || null,+ error: result.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') return startJob(req, res);++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });+ return pollJob(req, res, jobId);+});diff --git a/api/forge-stylize.js b/api/forge-stylize.jsnew file mode 100644index 000000000..98c989db8--- /dev/null+++ b/api/forge-stylize.js@@ -0,0 +1,133 @@+/**+ * /api/forge-stylize — one-click geometric stylization for the forge pipeline.+ *+ * POST /api/forge-stylize {+ * mesh_url: string,+ * style?: "voxel"|"brick"|"voronoi"|"lowpoly",+ * resolution?: number, // style-specific density (clamped)+ * output_format?: "glb"|"obj"|"stl"|"ply"+ * } → 202 { job_id, status, style, resolution }+ *+ * GET /api/forge-stylize?job=<id>+ * → { job_id, status, result_url?, face_count?, error? }+ *+ * Routes to workers/stylize (GCP Cloud Run) when GCP_STYLIZE_URL is set.+ * The same filter set is exposed to agents over MCP (stylize_model) and the+ * worker's GET /styles endpoint documents each filter's density knob.+ */++import { cors, json, method, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { createRegenProvider } from './_providers/gcp.js';++const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;+const VALID_FORMATS = new Set(['glb', 'obj', 'stl', 'ply']);++// Density bounds per filter — kept in lockstep with workers/stylize STYLE_CATALOG+// and src/shared/stylize-filters.js. The worker re-clamps server-side; clamping+// here too keeps the API honest and avoids a pointless round-trip on bad input.+const STYLE_BOUNDS = {+ voxel: { def: 32, min: 8, max: 96 },+ brick: { def: 24, min: 8, max: 64 },+ voronoi: { def: 48, min: 12, max: 120 },+ lowpoly: { def: 40, min: 8, max: 120 },+};++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Stylization is not configured. Set GCP_STYLIZE_URL and GCP_RECONSTRUCTION_KEY ' ++ 'to the URL and bearer secret of your deployed workers/stylize Cloud Run service.',+ });+}++async function startJob(req, res) {+ const ip = clientIp(req);+ const rl = await limits.mcp3dGenerate(ip);+ if (!rl.success) {+ return json(res, 429, {+ error: 'rate_limited',+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }++ const body = await readJson(req, 4_000).catch(() => null);+ const meshUrl = typeof body?.mesh_url === 'string' ? body.mesh_url.trim() : '';+ if (!meshUrl.startsWith('https://')) {+ return json(res, 400, { error: 'invalid_mesh_url', message: 'mesh_url must be a public https URL.' });+ }++ const style = STYLE_BOUNDS[body?.style] ? body.style : 'voxel';+ const bounds = STYLE_BOUNDS[style];+ const outputFormat = VALID_FORMATS.has(body?.output_format) ? body.output_format : 'glb';+ const requested = Number(body?.resolution);+ const resolution = Number.isFinite(requested)+ ? Math.max(bounds.min, Math.min(bounds.max, Math.round(requested)))+ : bounds.def;++ let provider;+ try {+ provider = createRegenProvider();+ if (!provider.supportsMode('stylize')) return unconfigured(res);+ } catch {+ return unconfigured(res);+ }++ try {+ const job = await provider.submit({+ mode: 'stylize',+ sourceUrl: meshUrl,+ params: { style, resolution, output_format: outputFormat },+ });+ return json(res, 202, {+ job_id: job.extJobId,+ status: 'queued',+ style,+ resolution,+ output_format: outputFormat,+ eta_seconds: job.eta,+ });+ } catch (err) {+ return json(res, 502, { error: 'stylize_failed', message: err?.message || 'Stylization could not start.' });+ }+}++async function pollJob(req, res, jobId) {+ if (!JOB_ID_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });+ }++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) {+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });+ }++ let provider;+ try {+ provider = createRegenProvider();+ } catch {+ return unconfigured(res);+ }++ const result = await provider.status(jobId);+ return json(res, 200, {+ job_id: jobId,+ status: result.status,+ result_url: result.resultGlbUrl || null,+ face_count: result.faceCount || null,+ error: result.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') return startJob(req, res);++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });+ return pollJob(req, res, jobId);+});diff --git a/api/forge-upload.js b/api/forge-upload.jsnew file mode 100644index 000000000..6ea82928f--- /dev/null+++ b/api/forge-upload.js@@ -0,0 +1,123 @@+/**+ * /api/forge-upload — direct-to-storage upload for /forge reference views.+ *+ * POST /api/forge-upload { content_type, size_bytes, checksum_sha256? }+ * → 200 { storage_key, upload_url, public_url, method, headers, expires_in }+ *+ * The browser PUTs the image bytes straight to `upload_url` (a short-lived R2+ * presigned URL), then submits `public_url` to /api/forge as one of `image_urls`+ * for multi-view reconstruction. Keeping the bytes off this function avoids+ * proxying multi-MB uploads through a serverless handler.+ *+ * Auth-free, matching the rest of /forge: rate-limited by client IP and scoped+ * to the anonymous browser handle (x-forge-client) so uploads land under that+ * client's key prefix. When object storage isn't configured the endpoint returns+ * a clean 503 and the page falls back to accepting public image URLs directly.+ */++import { randomUUID } from 'node:crypto';+import { cors, json, method, readJson, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { presignUpload, publicUrl } from './_lib/r2.js';+import { hashClient } from './_lib/forge-store.js';++// Accepted reference-image types → file extension for the storage key.+const CONTENT_TYPE_EXT = Object.freeze({+ 'image/png': 'png',+ 'image/jpeg': 'jpg',+ 'image/webp': 'webp',+});++const MAX_IMAGE_BYTES = 8 * 1024 * 1024; // matches forge-store's preview copy cap++// Upload needs object storage (R2/S3). Detect from raw env so a deployment+// without storage degrades to the "paste a URL" path rather than 500-ing.+function storageConfigured() {+ return Boolean(+ process.env.S3_ENDPOINT &&+ process.env.S3_BUCKET &&+ process.env.S3_PUBLIC_DOMAIN &&+ process.env.S3_ACCESS_KEY_ID &&+ process.env.S3_SECRET_ACCESS_KEY,+ );+}++function clientKeyFrom(req) {+ const raw = req.headers['x-forge-client'];+ return hashClient(Array.isArray(raw) ? raw[0] : raw);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ if (!storageConfigured()) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Reference image upload is not configured on this deployment (object storage missing). ' ++ 'Pass a public image URL to /api/forge instead.',+ });+ }++ const ip = clientIp(req);+ const rl = await limits.upload(`forge:${ip}`);+ if (!rl.success) {+ return json(res, 429, {+ error: 'rate_limited',+ message: 'Upload limit reached. Try again shortly.',+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),+ });+ }++ const body = await readJson(req, 2_000).catch(() => null);++ const contentType =+ typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';+ const ext = CONTENT_TYPE_EXT[contentType];+ if (!ext) {+ return json(res, 400, {+ error: 'invalid_content_type',+ message: 'content_type must be image/png, image/jpeg, or image/webp.',+ });+ }++ const size = Number(body?.size_bytes);+ if (!Number.isFinite(size) || size <= 0 || size > MAX_IMAGE_BYTES) {+ return json(res, 400, {+ error: 'invalid_size',+ message: `size_bytes must be between 1 and ${MAX_IMAGE_BYTES} bytes.`,+ });+ }++ const checksum =+ typeof body?.checksum_sha256 === 'string' && /^[a-f0-9]{64}$/.test(body.checksum_sha256)+ ? body.checksum_sha256+ : undefined;++ const clientKey = clientKeyFrom(req);+ const key = `forge/uploads/${clientKey.slice(0, 12)}/${randomUUID()}.${ext}`;++ let uploadUrl;+ try {+ uploadUrl = await presignUpload({+ key,+ contentType,+ ...(checksum ? { checksumSha256: checksum } : {}),+ });+ } catch (err) {+ return json(res, 502, {+ error: 'presign_failed',+ message: err?.message || 'Could not create an upload URL.',+ });+ }++ return json(res, 200, {+ storage_key: key,+ upload_url: uploadUrl,+ public_url: publicUrl(key),+ method: 'PUT',+ headers: { 'content-type': contentType },+ expires_in: 300,+ });+});diff --git a/api/forge.js b/api/forge.jsindex 048f244a8..7594e2872 100644--- a/api/forge.js+++ b/api/forge.js@@ -28,10 +28,16 @@ import {createCreation,materializeCreation,markFailed,+ findByJob,} from './_lib/forge-store.js';const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);+// Multi-view reconstruction accepts up to four calibrated views of one object+// (front / back / left / right). More than that yields diminishing returns and+// risks overrunning the model's input budget.+const MAX_VIEWS = 4;+// Guard for caller-supplied reference image / source GLB URLs. http(s) only,// bounded length — we forward these to the reconstruction/rig provider, so we// never accept data: URLs or unbounded strings.@@ -49,6 +55,28 @@ function clientKeyFrom(req) {return hashClient(Array.isArray(raw) ? raw[0] : raw);}+// Normalize the caller's reference image input into an ordered, de-duplicated+// list of view URLs. Accepts the multi-view `image_urls: string[]` form and the+// legacy single `image_url: string` (backward compatible — a single string+// still works exactly as before). Empty/blank/duplicate entries are dropped.+function parseImageUrls(body) {+ let raw;+ if (Array.isArray(body?.image_urls)) raw = body.image_urls;+ else if (typeof body?.image_url === 'string') raw = [body.image_url];+ else raw = [];++ const seen = new Set();+ const out = [];+ for (const v of raw) {+ if (typeof v !== 'string') continue;+ const t = v.trim();+ if (!t || seen.has(t)) continue;+ seen.add(t);+ out.push(t);+ }+ return out;+}+function unconfigured(res) {return json(res, 503, {error: 'unconfigured',@@ -71,22 +99,32 @@ async function startJob(req, res) {const body = await readJson(req, 8_000).catch(() => null);// Two reconstruction modes share this path:- // • image→3D — a caller supplies image_url; we reconstruct it directly and- // skip the text-to-image stage. An optional prompt may still guide the- // model where it accepts one.- // • text→3D — no image_url; we synthesize the reference image from the- // prompt with FLUX first, then reconstruct.- const imageUrl = typeof body?.image_url === 'string' ? body.image_url.trim() : '';- const isImageMode = imageUrl.length > 0;+ // • image→3D — a caller supplies one or more reference views (image_url or+ // image_urls[]); we reconstruct directly and skip the text-to-image stage.+ // With >1 view the provider fuses them (multi-view conditioning). An+ // optional prompt may still guide the model where it accepts one.+ // • text→3D — no images; we synthesize the reference image from the prompt+ // with FLUX first, then reconstruct.+ const imageUrls = parseImageUrls(body);+ const isImageMode = imageUrls.length > 0;const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';if (isImageMode) {- if (!HTTP_URL_RE.test(imageUrl) || imageUrl.length > 2048) {+ if (imageUrls.length > MAX_VIEWS) {return json(res, 400, {- error: 'invalid_image_url',- message: 'image_url must be an http(s) URL under 2048 characters.',+ error: 'invalid_image_urls',+ message: `Provide between 1 and ${MAX_VIEWS} reference images.`,});}+ // Validate every view at the boundary before any of them reach the model.+ for (const u of imageUrls) {+ if (!HTTP_URL_RE.test(u) || u.length > 2048) {+ return json(res, 400, {+ error: 'invalid_image_url',+ message: 'Each reference image must be an http(s) URL under 2048 characters.',+ });+ }+ }if (prompt.length > 1000) {return json(res, 400, {error: 'invalid_prompt',@@ -96,7 +134,8 @@ async function startJob(req, res) {} else if (prompt.length < 3 || prompt.length > 1000) {return json(res, 400, {error: 'invalid_prompt',- message: 'Describe one subject in 3–1000 characters, or pass image_url for image-to-3D.',+ message:+ 'Describe one subject in 3–1000 characters, or pass image_url / image_urls for image-to-3D.',});}const aspect = VALID_ASPECT.has(body?.aspect_ratio) ? body.aspect_ratio : '1:1';@@ -109,25 +148,38 @@ async function startJob(req, res) {}try {- // Resolve the reference image: supplied directly (image→3D) or synthesized- // from the prompt (text→3D).+ // Resolve the reference views: supplied directly (image→3D) or a single+ // view synthesized from the prompt (text→3D). `referenceImageUrl` is the+ // primary view — the durable preview + the synthesis target.let referenceImageUrl;let textToImageModel;+ let views;if (isImageMode) {- referenceImageUrl = imageUrl;+ views = imageUrls;+ referenceImageUrl = imageUrls[0];textToImageModel = null;} else {const synthesized = await textToImage(prompt, { aspectRatio: aspect });referenceImageUrl = synthesized.imageUrl;textToImageModel = synthesized.model;+ views = [referenceImageUrl];}const job = await provider.submit({mode: 'reconstruct',sourceUrl: referenceImageUrl,- params: { images: [referenceImageUrl], prompt: prompt || undefined },+ params: { images: views, prompt: prompt || undefined },});+ // How the job was actually conditioned. The provider reports back which+ // backend handled it and how many views it fused — these can differ from+ // what was requested when a single-view model is configured and we fall+ // back to the primary view. Surfaced so a downgrade is never silent.+ const viewsRequested = views.length;+ const viewsUsed = typeof job.viewsUsed === 'number' ? job.viewsUsed : viewsRequested;+ const multiview = Boolean(job.multiview);+ const backend = job.backend || 'replicate';+// Record the generation the moment it starts so the prompt + reference// image survive even if the mesh step later fails. Fail-soft: a missing// store just means no durable copy + no gallery entry for this run.@@ -139,6 +191,10 @@ async function startJob(req, res) {previewImageUrl: referenceImageUrl,replicateJobId: job.extJobId,textToImageModel,+ viewsRequested,+ viewsUsed,+ multiview,+ backend,});return json(res, 200, {@@ -148,6 +204,11 @@ async function startJob(req, res) {mode: isImageMode ? 'image_to_3d' : 'text_to_3d',prompt: prompt || null,preview_image_url: referenceImageUrl,+ reference_image_urls: views,+ views_requested: viewsRequested,+ views_used: viewsUsed,+ multiview,+ backend,text_to_image_model: textToImageModel,eta_seconds: typeof job.eta === 'number' ? job.eta : null,});@@ -269,6 +330,20 @@ async function pollJob(req, res, jobId) {}const clientKey = clientKeyFrom(req);++ // How this job was conditioned (view count + backend), recorded at submit+ // time. Surfaced on every poll so a caller that only polls still learns+ // whether multi-view was honored. Fail-soft: absent when the store is off.+ const meta = await findByJob({ replicateJobId: jobId, clientKey });+ const metaFields = meta+ ? {+ views_requested: meta.views_requested ?? null,+ views_used: meta.views_used ?? null,+ multiview: meta.multiview ?? null,+ backend: meta.backend ?? null,+ }+ : {};+const result = await provider.status(jobId);if (result.status === 'done' && result.resultGlbUrl) {// Copy the mesh + reference image into our own storage so the model is@@ -285,6 +360,7 @@ async function pollJob(req, res, jobId) {status: 'done',glb_url: durable?.glbUrl ?? result.resultGlbUrl,durable: Boolean(durable),+ ...metaFields,});}if (result.status === 'failed') {@@ -293,9 +369,10 @@ async function pollJob(req, res, jobId) {job_id: jobId,status: 'failed',error: result.error || 'Generation failed.',+ ...metaFields,});}- return json(res, 200, { job_id: jobId, status: result.status || 'running' });+ return json(res, 200, { job_id: jobId, status: result.status || 'running', ...metaFields });}export default wrap(async (req, res) => {diff --git a/docs/feature-tasks/01-multiview-to-3d.md b/docs/feature-tasks/01-multiview-to-3d.mddeleted file mode 100644index 5d7f651f7..000000000--- a/docs/feature-tasks/01-multiview-to-3d.md+++ /dev/null@@ -1,26 +0,0 @@-# Task: Multiview-to-3D reconstruction--## Goal-Let users supply **multiple reference images of the same object from different angles** (e.g. front / back / left / right) and reconstruct a single, higher-fidelity 3D mesh from them. Today the generation pipeline only accepts one `image_url`, which caps geometric accuracy for anything with detail on unseen sides.--## Why this matters-Single-image reconstruction hallucinates the back of every object. Feeding 2–4 calibrated views removes that guesswork and is the single biggest quality lever available without changing models — the backends we already use (Hunyuan3D, TRELLIS) support multi-view conditioning.--## Where it lives-- Generation entrypoint: [api/forge.js](../../api/forge.js)-- Model providers: [api/_providers/replicate.js](../../api/_providers/replicate.js), [api/_providers/gcp.js](../../api/_providers/gcp.js)-- Forge UI: [pages/forge.html](../../pages/forge.html)-- MCP tool surface: `mesh_forge` (wherever it is registered under `api/_mcp3d/`)--## Requirements-1. **API contract:** accept `image_urls: string[]` (1–4 images) in addition to the existing single `image_url` (keep backward compatibility — a single string still works). Validate count, fetch/validate each image at the boundary.-2. **Provider routing:** when >1 image is supplied, route to a backend that supports multi-view conditioning and pass all views. If a chosen backend does not support multi-view, fall back gracefully and surface which mode was used in the job result. No silent downgrade without reporting it.-3. **UI:** extend [pages/forge.html](../../pages/forge.html) so a user can add up to 4 view slots with drag/drop + file picker, labelled (front/back/left/right or freeform). Show thumbnails, allow removal/reorder. Every state designed: empty slot, uploading, uploaded, error.-4. **MCP:** extend `mesh_forge` to accept the array form. Keep pricing/x402 behavior consistent with the existing tool.-5. **Job result:** record how many views were used and which backend handled it, surfaced in the polling response.--## Done when-- Single-image and multi-image both work end-to-end through `/forge` and through the MCP tool.-- Real generation succeeds with real images (no mocks); model-viewer renders the result.-- Backward compatibility verified: existing single-`image_url` callers unaffected.-- Follow CLAUDE.md: real APIs only, every UI state designed, no TODOs, `git diff` self-reviewed.diff --git a/docs/feature-tasks/02-fbx-export.md b/docs/feature-tasks/02-fbx-export.mddeleted file mode 100644index 7c3f8a6d2..000000000--- a/docs/feature-tasks/02-fbx-export.md+++ /dev/null@@ -1,25 +0,0 @@-# Task: FBX export (with skeleton)--## Goal-Add **FBX** as an export format for generated and rigged models, including the skeleton + skin weights for rigged outputs. This is a hard blocker for Unity and Unreal users, who overwhelmingly expect FBX with a bone hierarchy.--## Why this matters-We export GLB / OBJ / STL / PLY / USDZ / 3MF but **not FBX**. Game-engine pipelines treat FBX as the default interchange format, especially for animated/rigged characters. Without it, a whole segment of users can't use our output without a manual Blender round-trip.--## Where it lives-- Mesh conversion worker: [workers/remesh/main.py](../../workers/remesh/main.py) (trimesh + open3d; `convert` operation already exists)-- HTTP route: [api/forge-remesh.js](../../api/) (the `forge-remesh` endpoint)-- Rigging pipeline that produces skeletons: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)-- MCP `remesh_model` tool under `api/_mcp3d/`--## Requirements-1. Add `fbx` to the supported output formats of the convert/remesh path.-2. **Preserve rig data** when converting a rigged GLB → FBX: bone hierarchy, skin weights, and any blendshapes must survive the conversion. A static mesh converts as a plain FBX. trimesh alone does not write FBX with skeletons — evaluate Blender headless (`bpy`) or the FBX SDK / `assimp` and pick the one that round-trips bones correctly. Justify the choice in the PR.-3. Wire `fbx` as a selectable export option everywhere GLB/OBJ/etc are offered (UI export menus, remesh API, MCP tool enum).-4. Validate the output: a rigged FBX should import into Blender/Unity with its skeleton intact. Document the verification.--## Done when-- A rigged GLB converts to an FBX that retains its skeleton + skin weights (verified by re-import).-- A static mesh converts to a valid FBX.-- `fbx` selectable in UI, REST, and MCP; real conversion, no mocks.-- Follow CLAUDE.md: finish completely, no stubs, self-review the diff.diff --git a/docs/feature-tasks/03-parts-segmentation.md b/docs/feature-tasks/03-parts-segmentation.mddeleted file mode 100644index 320c42ed9..000000000--- a/docs/feature-tasks/03-parts-segmentation.md+++ /dev/null@@ -1,24 +0,0 @@-# Task: Parts segmentation (split 3D model into semantic parts)--## Goal-Automatically split a generated mesh into **meaningful, separable parts** with clean boundaries (e.g. head / torso / arms / legs for a character; wheels / body / windows for a vehicle). Output each part as an addressable sub-mesh that can be hidden, recolored, replaced, or exported individually.--## Why this matters-Segmented models are dramatically more useful for games and animation: swap a weapon, recolor one panel, rig parts independently, or LOD them separately. This is a clear differentiator we currently lack entirely.--## Where it lives-- New worker alongside existing ones: [workers/](../../workers/) (model after [workers/remesh/main.py](../../workers/remesh/main.py) for structure — FastAPI + trimesh)-- New HTTP route in [api/](../../api/) (e.g. `forge-segment`)-- New MCP tool under `api/_mcp3d/tools/` (model after the existing studio tools)-- Viewer integration so segmented parts are visible/selectable--## Requirements-1. **Segmentation engine:** implement real part segmentation. Evaluate options (a learned 3D part-segmentation model via Replicate/GPU worker, or a geometry-based approach — connected components + region growing on curvature/UV islands). Pick one that produces semantically clean parts, not arbitrary chunks. Justify the choice.-2. **Output:** return a GLB whose parts are separate named meshes/nodes, plus a parts manifest (id, name, bbox, face count). Optionally allow exporting a single part.-3. **Viewer:** in the model viewer (model-viewer / Three.js), let users click a part to isolate/highlight it, toggle visibility, and download an individual part. Every state designed.-4. **MCP + API:** expose `segment_model` as an x402-priced tool consistent with the others, and a REST endpoint.--## Done when-- Feeding a real generated GLB returns cleanly separated, named parts rendered and selectable in the viewer.-- Per-part isolation, visibility toggle, and per-part export all work.-- Real implementation, no placeholder splits; follow CLAUDE.md throughout.diff --git a/docs/feature-tasks/04-quad-remesh-low-poly.md b/docs/feature-tasks/04-quad-remesh-low-poly.mddeleted file mode 100644index 924a21a0a..000000000--- a/docs/feature-tasks/04-quad-remesh-low-poly.md+++ /dev/null@@ -1,23 +0,0 @@-# Task: Quad remesh + smart low-poly--## Goal-Add **quad-based remeshing** and a **smart low-poly** mode that produces clean, game-ready topology with a user-chosen target resolution — not just triangle-soup decimation.--## Why this matters-Today's remesh does quadric *triangle* decimation. Game and animation pipelines want **quad** topology (clean edge loops, deformation-friendly) and tunwrapped low-poly variants for real-time rendering. Without it, our output needs a manual retopo pass before it's usable in production.--## Where it lives-- Mesh worker: [workers/remesh/main.py](../../workers/remesh/main.py) (currently trimesh + open3d quadric decimation)-- HTTP route: `forge-remesh` in [api/](../../api/)-- MCP `remesh_model` tool under `api/_mcp3d/`--## Requirements-1. **Quad remesh:** integrate a real quad remesher (e.g. Instant Meshes / `quadwild` / Blender `bpy` remesh, or an equivalent library). Output predominantly-quad topology with target face/vertex count. Justify the tool choice and license-check it (must be commercial-OK per CLAUDE.md).-2. **Smart low-poly mode:** a preset that produces a low-poly variant (e.g. target buckets like 1k / 5k / 20k faces) while preserving silhouette, then **re-bakes/transfers UVs + normals** so textures still map. Don't just decimate and drop the textures.-3. Expose `remesh_mode` (`triangle` | `quad` | `lowpoly`) + target count across UI, REST, and MCP.-4. Preserve UVs and re-project the existing texture onto the remeshed result wherever possible.--## Done when-- Quad remesh produces clean quad-dominant topology at the requested resolution (verify in Blender wireframe).-- Low-poly mode produces a usable real-time variant that still renders with its texture.-- All three modes selectable in UI/REST/MCP; real implementation; CLAUDE.md followed.diff --git a/docs/feature-tasks/05-magic-brush-local-retexture.md b/docs/feature-tasks/05-magic-brush-local-retexture.mddeleted file mode 100644index b582dd807..000000000--- a/docs/feature-tasks/05-magic-brush-local-retexture.md+++ /dev/null@@ -1,23 +0,0 @@-# Task: Magic Brush — local region retexturing--## Goal-Let users **repaint a specific region** of a model's texture from a text prompt (and/or color) without regenerating the entire surface. Fix a seam, recolor one panel, add a logo to a chest plate — surgically.--## Why this matters-Our current retexture is all-or-nothing: any fix means regenerating the whole surface and losing everything else. A local brush is faster, cheaper, and gives users real control over the result.--## Where it lives-- Texture worker: [workers/texture/main.py](../../workers/texture/main.py) (SDXL + ControlNet depth, multi-view back-projection)-- MCP `retexture_model` tool: [api/_mcp3d/tools/studio.js](../../api/_mcp3d/tools/studio.js)-- Viewer / studio UI where models are displayed and edited--## Requirements-1. **Region selection:** in the 3D viewer let the user paint a mask directly on the model surface (brush with adjustable radius), or select a part/material. Produce a UV-space mask from the surface selection.-2. **Masked inpainting:** extend the texture pipeline to inpaint **only** the masked UV region from a prompt/color, blending edges so the seam is invisible. The rest of the texture is untouched (load and preserve the existing texture as the base).-3. **Iterative:** support repeated brush passes on the same model without quality loss; each pass operates on the latest texture.-4. Expose via UI (brush tool with prompt box), and add a `retexture_region` capability to the MCP tool consistent with x402 pricing.--## Done when-- A user can paint a region, type a prompt, and see only that area change — edges blend cleanly.-- Multiple sequential edits compose correctly.-- Real SDXL inpainting (no mocks), every UI state designed; CLAUDE.md followed.diff --git a/docs/feature-tasks/06-stylization-filters.md b/docs/feature-tasks/06-stylization-filters.mddeleted file mode 100644index f0878f414..000000000--- a/docs/feature-tasks/06-stylization-filters.md+++ /dev/null@@ -1,29 +0,0 @@-# Task: One-click stylization filters (LEGO / Voxel / Voronoi / etc.)--## Goal-Add instant **geometric stylization filters** that transform any mesh into a stylized variant — voxelized (blocky), brick/stud (LEGO-like), Voronoi/wireframe shell, low-poly faceted, and similar — with a single click.--## Why this matters-Stylization is high-delight, highly shareable ("screenshot and post" material per CLAUDE.md), and turns one generated asset into many. It's pure geometry processing, so it's fast and cheap — no model inference needed.--## Where it lives-- New stylization step in the mesh worker family: [workers/](../../workers/) (model after [workers/remesh/main.py](../../workers/remesh/main.py))-- REST route in [api/](../../api/)-- MCP tool under `api/_mcp3d/tools/`-- Forge / studio UI: a "Stylize" panel with filter thumbnails--## Requirements-1. Implement real geometry transforms (trimesh / open3d / custom):- - **Voxel:** voxelize to a grid, rebuild as cubes at chosen resolution.- - **Brick/stud:** voxel grid + stud caps on top faces.- - **Voronoi shell:** surface-sample → Voronoi cells → open lattice shell.- - **Faceted low-poly:** decimate + flat-shade hard normals.- Make the filter set extensible so more can be added later.-2. Each filter takes a resolution/intensity parameter with sensible defaults and a live-ish preview thumbnail.-3. Preserve a reasonable color/material from the source where the style allows; otherwise apply a tasteful default material.-4. Expose in UI (filter gallery with hover previews), REST, and MCP (x402-priced).--## Done when-- Each filter produces a correct, renderable GLB from a real input mesh.-- UI gallery with hover/active/focus states; empty + error states designed.-- Real geometry processing, no placeholders; CLAUDE.md followed.diff --git a/docs/feature-tasks/07-animation-preset-library.md b/docs/feature-tasks/07-animation-preset-library.mddeleted file mode 100644index ce3c08b84..000000000--- a/docs/feature-tasks/07-animation-preset-library.md+++ /dev/null@@ -1,25 +0,0 @@-# Task: Animation preset library (one-click animate a rigged model)--## Goal-Give users a curated library of **ready-to-apply animation presets** (idle, walk, run, jump, wave, dance, etc.) that can be applied to any rigged model with one click and exported as an animated GLB/FBX.--## Why this matters-We auto-rig models but there's no easy path from "rigged" to "moving." A preset library closes that loop and makes rigged output immediately demo-able and useful. The Mixamo-fetch plumbing already exists — this turns it into a real, curated, wired feature.--## Where it lives-- Existing Mixamo plumbing: `fetch-mixamo-catalog` (locate under [workers/](../../workers/) or [scripts/](../../scripts/))-- Rigging pipeline / skeleton format: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)-- Pose studio (keyframe/timeline already present): the `/pose` page-- Viewer with `AnimationClip` support (Three.js)--## Requirements-1. **Curated preset set:** assemble a real, license-clear set of animation clips covering common actions. Store them as retargetable clips keyed to our standard skeleton. Document the source and license of each.-2. **Retargeting:** apply a preset to an arbitrary rigged model whose skeleton matches (or can be mapped to) our standard rig. Handle bone-name mapping; report clearly if a model can't be retargeted.-3. **UI:** an animation gallery (thumbnails/looping previews) on the model/pose page. Click to preview on the loaded model, then apply. Designed hover/active/focus, empty, and error states.-4. **Export:** export the animated result as GLB (and FBX once [02-fbx-export.md](02-fbx-export.md) lands) with the animation baked in.-5. Optionally expose `apply_animation` via MCP (x402-priced).--## Done when-- A user loads a rigged model, picks a preset, previews it animating, and exports an animated GLB.-- Retargeting works across at least a few differently-proportioned rigged models.-- Real clips with documented licensing (no placeholder/empty animations); CLAUDE.md followed.diff --git a/docs/feature-tasks/08-native-geometry-highres.md b/docs/feature-tasks/08-native-geometry-highres.mddeleted file mode 100644index 4fcaa5fc1..000000000--- a/docs/feature-tasks/08-native-geometry-highres.md+++ /dev/null@@ -1,26 +0,0 @@-# Task: Higher-resolution geometry + native geometry generation path--## Goal-Raise the geometric ceiling and accuracy of generated meshes by (a) supporting higher polygon targets and (b) adding a **geometry-first generation path** that produces mesh geometry directly rather than always going through an intermediate image.--## Why this matters-Our pipeline is image-intermediate (text → image → mesh), which caps geometric accuracy and detail — the mesh can only be as good as a single synthesized view implies. A native/geometry-first backend plus higher poly ceilings closes the fidelity gap for detailed assets and gives power users a high-detail option.--## Where it lives-- Generation entrypoint: [api/forge.js](../../api/forge.js)-- Providers: [api/_providers/replicate.js](../../api/_providers/replicate.js), [api/_providers/gcp.js](../../api/_providers/gcp.js)-- Rigging/finishing pipeline: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)--## Requirements-1. **Higher poly targets:** expose a quality/resolution tier (e.g. draft / standard / high) that maps to higher output poly budgets where the backend supports it. Make sure downstream remesh/rig/storage handle large meshes without breaking.-2. **Native geometry backend:** evaluate and integrate at least one backend that generates 3D geometry directly (native 3D diffusion / geometry-first model) as an alternative route to the current image-intermediate path. License must be commercial-OK. Justify the choice.-3. **Routing:** let the request select the path (`mode: image | geometry`) with a sensible default; record which path/backend produced each job in the result.-4. **Performance + cost:** surface expected time/cost difference between tiers/paths so the UI can communicate it; keep the existing fast path as default.--## Done when-- A high tier produces visibly higher-detail meshes than the default, end-to-end.-- The geometry-first path produces valid, riggable GLBs through the full pipeline.-- Job results report tier + backend + path; real backends only; CLAUDE.md followed.--## Note-This is the most research-heavy task — start by surveying available commercial-OK backends and benchmarking quality/cost/latency before wiring. Report the benchmark before committing to one.diff --git a/docs/feature-tasks/README.md b/docs/feature-tasks/README.mddeleted file mode 100644index 24a939b9c..000000000--- a/docs/feature-tasks/README.md+++ /dev/null@@ -1,17 +0,0 @@-# Feature task prompts--Standalone, assign-to-an-agent prompts for closing gaps in the 3D generation pipeline. Each file is self-contained: hand it to an agent as the task. All tasks must follow the rules in [CLAUDE.md](../../CLAUDE.md) — real APIs, no mocks, every state designed, self-reviewed diffs.--| # | Task | Impact | Rough effort |-|---|------|--------|--------------|-| 01 | [Multiview-to-3D](01-multiview-to-3d.md) | High — biggest quality lever | Medium |-| 02 | [FBX export](02-fbx-export.md) | High — unblocks game-engine users | Small–Medium |-| 03 | [Parts segmentation](03-parts-segmentation.md) | High — clear differentiator | Large |-| 04 | [Quad remesh + low-poly](04-quad-remesh-low-poly.md) | High — game-ready topology | Medium |-| 05 | [Magic Brush local retexture](05-magic-brush-local-retexture.md) | Medium — user control | Medium–Large |-| 06 | [Stylization filters](06-stylization-filters.md) | Medium — shareable delight | Medium |-| 07 | [Animation preset library](07-animation-preset-library.md) | Medium — closes rig→motion loop | Medium |-| 08 | [Higher-res / native geometry](08-native-geometry-highres.md) | High — fidelity ceiling | Large (research-first) |--## Suggested order-Ship in roughly this order: **02 → 01 → 04 → 03 → 06 → 07 → 05 → 08**. FBX export and multiview are the cheapest high-impact wins; native geometry (08) is research-first and biggest.diff --git a/mcp-server/src/tools/mesh-forge.js b/mcp-server/src/tools/mesh-forge.jsindex 2528fc598..b08afca6c 100644--- a/mcp-server/src/tools/mesh-forge.js+++ b/mcp-server/src/tools/mesh-forge.js@@ -39,7 +39,7 @@ import { jsonSchemaFromZod } from './_shared.js';const TOOL_NAME = 'mesh_forge';const TOOL_DESCRIPTION =- 'Generate a textured 3D GLB model from a text prompt OR a reference image. In text mode, a chain of specialist models runs: an IBM Granite "prompt director" rewrites the prompt into an optimized 3D spec, FLUX renders a reference image, then Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. In image mode, a supplied image_url is reconstructed directly. Returns the GLB URL, a three.ws viewer link, the directed prompt (text mode), and timing. Feed the GLB to rig_mesh for a rigged, animation-ready model. Paid: $0.25 USDC.';+ 'Generate a textured 3D GLB model from a text prompt, a single reference image, OR 2–4 reference views of the same object. In text mode, a chain of specialist models runs: an IBM Granite "prompt director" rewrites the prompt into an optimized 3D spec, FLUX renders a reference image, then Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. In image mode, a supplied image_url is reconstructed directly. In multi-view mode, pass image_urls (1–4 angles such as front/back/left/right) and the backend fuses them for a higher-fidelity mesh with no hallucinated back. Returns the GLB URL, a three.ws viewer link, how many views were fused, which backend handled it, the directed prompt (text mode), and timing. Feed the GLB to rig_mesh for a rigged, animation-ready model. Paid: $0.25 USDC.';const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);@@ -120,11 +120,15 @@ async function directPrompt(rawPrompt) {return refined.length >= 3 && refined.length <= 1000 ? refined : null;}-async function startForge({ prompt, aspect, imageUrl }) {+async function startForge({ prompt, aspect, imageUrls }) {const base = apiBase();- const payload = imageUrl- ? { image_url: imageUrl, prompt: prompt || undefined, aspect_ratio: aspect }- : { prompt, aspect_ratio: aspect };+ // Multi-view: send all supplied views as image_urls[]; the three.ws pipeline+ // routes >1 view to a multi-view-capable backend (and reports a downgrade if+ // the configured backend can't fuse them). Text mode sends just the prompt.+ const payload =+ Array.isArray(imageUrls) && imageUrls.length+ ? { image_urls: imageUrls, prompt: prompt || undefined, aspect_ratio: aspect }+ : { prompt, aspect_ratio: aspect };const res = await fetch(`${base}/api/forge`, {method: 'POST',headers: { 'content-type': 'application/json' },@@ -201,6 +205,12 @@ const inputZodShape = {.url().describe('Image→3D: an http(s) URL to a reference image to reconstruct directly. When set, the prompt-director and text-to-image stages are skipped.').optional(),+ image_urls: z+ .array(z.string().url())+ .min(1)+ .max(4)+ .describe('Multi-view → 3D: 1–4 http(s) URLs of the SAME object from different angles (e.g. front, back, left, right). More than one view enables multi-view reconstruction, which removes the back-of-object guesswork of single-image reconstruction. Takes precedence over image_url.')+ .optional(),aspect_ratio: z.enum(['1:1', '4:3', '3:4', '16:9', '9:16']).describe('Reference image aspect ratio (text mode). Default 1:1 (best for isolated objects).')@@ -227,6 +237,11 @@ export async function buildMeshForgeTool() {glbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb',preview: 'https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2Fcdn%2F...',prompt: 'a worn leather armchair, brass studs',+ imageUrls: null,+ viewsRequested: 0,+ viewsUsed: 1,+ multiview: false,+ backend: 'replicate',directedPrompt: 'A single worn brown leather wingback armchair with brass stud trim...',directed: true,jobId: 'k7m2q9x4',@@ -235,13 +250,33 @@ export async function buildMeshForgeTool() {durationMs: 96000,},},- async ({ prompt, image_url, aspect_ratio, direct }) => {+ async ({ prompt, image_url, image_urls, aspect_ratio, direct }) => {const trimmedPrompt = typeof prompt === 'string' ? prompt.trim() : '';- const imageMode = typeof image_url === 'string' && image_url.trim().length > 0;++ // Merge the multi-view array form with the legacy single image_url,+ // de-duplicating while preserving order. image_urls wins when present.+ const rawViews = Array.isArray(image_urls)+ ? image_urls+ : typeof image_url === 'string'+ ? [image_url]+ : [];+ const seenViews = new Set();+ const views = [];+ for (const v of rawViews) {+ if (typeof v !== 'string') continue;+ const t = v.trim();+ if (!t || seenViews.has(t)) continue;+ seenViews.add(t);+ views.push(t);+ }+ if (views.length > 4) {+ return toolError('invalid_input', 'Provide between 1 and 4 reference images.');+ }+ const imageMode = views.length > 0;if (!imageMode && trimmedPrompt.length < 3) {return toolError('invalid_input',- 'Provide a prompt (3+ chars) for text→3D, or an image_url for image→3D.',+ 'Provide a prompt (3+ chars) for text→3D, or 1–4 image_urls for image/multi-view→3D.',);}const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '1:1';@@ -261,7 +296,7 @@ export async function buildMeshForgeTool() {job = await startForge({prompt: effectivePrompt || undefined,aspect,- imageUrl: imageMode ? image_url.trim() : undefined,+ imageUrls: imageMode ? views : undefined,});} catch (err) {return toolError(err.code || 'provider_error', err.message, {@@ -305,7 +340,15 @@ export async function buildMeshForgeTool() {glbUrl,preview,prompt: trimmedPrompt || null,- imageUrl: imageMode ? image_url.trim() : null,+ imageUrl: imageMode ? views[0] : null,+ imageUrls: imageMode ? views : null,+ viewsRequested: imageMode ? views.length : 0,+ // How the backend actually conditioned the mesh — surfaced from the+ // submit + poll responses so a multi-view downgrade is never silent.+ viewsUsed:+ (typeof final.views_used === 'number' ? final.views_used : job.views_used) ?? null,+ multiview: (final.multiview ?? job.multiview) ?? null,+ backend: (final.backend ?? job.backend) ?? null,directedPrompt: directedPrompt || null,directed: Boolean(directedPrompt),jobId: job.job_id,diff --git a/pages/forge.html b/pages/forge.htmlindex 7966816ed..3ca2143d9 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -164,6 +164,248 @@box-shadow: none;}+ /* Mode switch -------------------------------------------------- */+ .mode-switch-wrap {+ display: flex;+ justify-content: center;+ margin-bottom: var(--space-md);+ }+ .mode-switch {+ display: inline-flex;+ gap: 2px;+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: 3px;+ }+ .mode-switch button {+ background: transparent;+ border: none;+ color: var(--ink-dim);+ font-family: var(--font-display);+ font-size: var(--text-sm);+ font-weight: 600;+ padding: 0.5rem 1.05rem;+ border-radius: var(--radius-sm);+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+ }+ .mode-switch button:hover {+ color: var(--ink);+ }+ .mode-switch button[aria-selected='true'] {+ background: var(--surface-3);+ color: var(--ink);+ }+ .mode-switch button:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ /* View slots — image / multi-view mode ------------------------- */+ .image-pane {+ display: flex;+ flex-direction: column;+ }+ .views-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: var(--space-sm);+ }+ @media (max-width: 620px) {+ .views-grid {+ grid-template-columns: repeat(2, 1fr);+ }+ }+ .view-slot {+ position: relative;+ aspect-ratio: 1 / 1;+ border: 1px dashed var(--stroke-strong);+ border-radius: var(--radius-md);+ background: var(--surface-1);+ overflow: hidden;+ display: grid;+ place-items: center;+ cursor: pointer;+ transition: border-color 0.15s, background 0.15s, transform 0.12s;+ }+ .view-slot:hover {+ border-color: var(--accent);+ }+ .view-slot:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .view-slot.drop-target {+ border-color: var(--accent);+ border-style: solid;+ background: var(--accent-soft);+ transform: scale(1.02);+ }+ .view-slot[data-state='uploaded'] {+ border-style: solid;+ cursor: grab;+ }+ .view-slot[data-state='uploaded']:active {+ cursor: grabbing;+ }+ .view-slot[data-state='error'] {+ border-color: var(--danger);+ border-style: solid;+ }+ .view-slot.dragging {+ opacity: 0.4;+ }+ /* Inner regions toggled by the slot's data-state. */+ .vs-empty,+ .vs-uploading,+ .vs-error {+ display: none;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 0.35rem;+ color: var(--ink-dim);+ font-size: var(--text-xs);+ padding: 0.5rem;+ text-align: center;+ }+ .vs-thumb,+ .vs-remove,+ .vs-badge {+ display: none;+ }+ .view-slot[data-state='empty'] .vs-empty {+ display: flex;+ }+ .view-slot[data-state='uploading'] .vs-uploading {+ display: flex;+ }+ .view-slot[data-state='uploaded'] .vs-thumb {+ display: block;+ }+ .view-slot[data-state='uploaded'] .vs-remove {+ display: grid;+ }+ .view-slot[data-state='uploaded'] .vs-badge {+ display: block;+ }+ .view-slot[data-state='error'] .vs-error {+ display: flex;+ }+ .vs-icon {+ font-size: 1.5rem;+ line-height: 1;+ color: var(--ink-dim);+ }+ .vs-label {+ font-family: var(--font-mono);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ }+ .vs-thumb {+ width: 100%;+ height: 100%;+ object-fit: cover;+ pointer-events: none;+ }+ .vs-remove {+ position: absolute;+ top: 5px;+ right: 5px;+ width: 22px;+ height: 22px;+ place-items: center;+ border: none;+ border-radius: 50%;+ background: rgba(0, 0, 0, 0.6);+ color: #fff;+ font-size: 1rem;+ line-height: 1;+ cursor: pointer;+ backdrop-filter: blur(4px);+ transition: background 0.15s;+ }+ .vs-remove:hover {+ background: var(--danger);+ }+ .vs-badge {+ position: absolute;+ bottom: 5px;+ left: 5px;+ font-family: var(--font-mono);+ font-size: 0.6rem;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ padding: 1px 6px;+ border-radius: 999px;+ background: rgba(0, 0, 0, 0.6);+ color: var(--ink);+ backdrop-filter: blur(4px);+ }+ .vs-uploading .shimmer {+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 100deg,+ transparent 20%,+ rgba(255, 255, 255, 0.06) 50%,+ transparent 80%+ );+ background-size: 200% 100%;+ animation: shimmer 1.4s linear infinite;+ }+ .vs-retry {+ background: transparent;+ border: 1px solid var(--stroke-strong);+ color: var(--ink);+ border-radius: var(--radius-sm);+ font-size: var(--text-xs);+ padding: 0.2rem 0.5rem;+ cursor: pointer;+ }+ .vs-retry:hover {+ border-color: var(--accent);+ }+ .views-hint {+ color: var(--ink-dim);+ font-size: var(--text-xs);+ margin: var(--space-sm) 0 0;+ text-align: center;+ }+ .image-prompt {+ width: 100%;+ min-height: 52px;+ resize: vertical;+ margin-top: var(--space-sm);+ background: transparent;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ outline: none;+ color: var(--ink);+ font-family: var(--font-body);+ font-size: var(--text-base);+ line-height: var(--leading-normal);+ padding: 0.55rem 0.7rem;+ }+ .image-prompt:focus {+ border-color: var(--stroke-strong);+ }+ .image-prompt::placeholder {+ color: var(--ink-dim);+ }+ .views-badge {+ font-family: var(--font-mono);+ font-size: 0.62rem;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--ink-dim);+ border: 1px solid var(--stroke);+ border-radius: 999px;+ padding: 1px 7px;+ margin-left: 0.5rem;+ }+/* Example chips ------------------------------------------------ */.chips {display: flex;diff --git a/src/animation-library.js b/src/animation-library.jsnew file mode 100644index 000000000..13484ccd9--- /dev/null+++ b/src/animation-library.js@@ -0,0 +1,488 @@+// Animation preset gallery for the /pose studio.+//+// Renders a curated, searchable gallery of ready-to-apply motion clips. Click a+// card and the clip retargets onto the loaded rig and plays live in the+// viewport (the shared 3D stage is the preview surface — one figure, like+// Mixamo, rather than N video thumbnails). A transport bar then lets the user+// scrub speed, toggle loop, stop, and export an animated GLB with the motion+// baked in.+//+// This controller owns only its own AnimationMixer and DOM; it borrows the rig+// and render loop from the host (pose-studio) through the callbacks passed to+// the constructor, and signals the host when a preview takes over the figure so+// the keyframe timeline can yield.++import { AnimationMixer, LoopOnce, LoopRepeat } from 'three';+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';++import { curate } from './animation-presets.js';+import {+ retargetClipToRig,+ scaleClipSpeed,+ parseClipJSON,+ MIN_COVERAGE,+} from './animation-retarget.js';+import { log } from './shared/log.js';++const MANIFEST_URL = '/animations/manifest.json';+// A rig needs a real share of the canonical skeleton before presets read as+// performances rather than twitches. Mirrors AnimationManager's bar.+const MIN_RIG_BONES = 8;++const el = (tag, attrs = {}, children = []) => {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else if (k === 'html') node.innerHTML = v;+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);+ else if (v !== false && v != null) node.setAttribute(k, v);+ }+ for (const child of (Array.isArray(children) ? children : [children])) {+ if (child == null) continue;+ node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);+ }+ return node;+};++export class AnimationLibrary {+ /**+ * @param {{+ * host: HTMLElement,+ * getRig: () => object|null,+ * onPreviewStart?: () => void,+ * onPreviewStop?: () => void,+ * setStatus?: (msg: string, kind?: string) => void,+ * }} opts+ */+ constructor(opts) {+ this.host = opts.host;+ this.getRig = opts.getRig;+ this.onPreviewStart = opts.onPreviewStart || (() => {});+ this.onPreviewStop = opts.onPreviewStop || (() => {});+ this.setStatus = opts.setStatus || (() => {});++ /** @type {Array} curated manifest defs (with category) */+ this._defs = [];+ /** @type {Map<string, import('three').AnimationClip>} canonical clips by name */+ this._clipCache = new Map();+ /** @type {string} '' = all categories */+ this._filterCat = '';+ this._query = '';++ this._mixer = null;+ this._mixerRoot = null;+ this._action = null;+ this._activeName = null;+ this._activeDef = null;+ this._speed = 1;+ this._previewing = false;+ this._state = 'loading';++ // Resolved DOM refs (built in _renderShell).+ this._refs = {};+ }++ // ── Lifecycle ───────────────────────────────────────────────────────────+ async mount() {+ this._renderShell();+ this._setState('loading');+ try {+ const res = await fetch(MANIFEST_URL, { cache: 'no-cache' });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const manifest = await res.json();+ if (!Array.isArray(manifest) || manifest.length === 0) throw new Error('empty manifest');+ this._curated = curate(manifest);+ this._defs = [this._curated.featured, this._curated.groups.flatMap((g) => g.items)]+ .flat();+ this._buildCategoryChips();+ this._evaluateRig();+ } catch (err) {+ log.warn('[AnimationLibrary] manifest load failed:', err.message);+ this._setState('error-load');+ }+ }++ /** Called by the host when the active rig changes (avatar load / mannequin). */+ onRigChanged() {+ this.stopPreview({ silent: true });+ this._disposeMixer();+ if (this._defs.length) this._evaluateRig();+ }++ /** Tick the preview mixer. Host calls this from its render loop while previewing. */+ update(dt) {+ this._mixer?.update(dt);+ }++ isPreviewing() {+ return this._previewing;+ }++ dispose() {+ this.stopPreview({ silent: true });+ this._disposeMixer();+ this._clipCache.clear();+ this.host.innerHTML = '';+ }++ // ── Rig capability ────────────────────────────────────────────────────────+ _rigBoneCount() {+ const rig = this.getRig();+ return rig?.getBones?.().length || 0;+ }++ // Presets target rigged GLB avatars. The primitive mannequin has no skinned+ // skeleton to export, so we steer the user to load a real avatar.+ _evaluateRig() {+ const rig = this.getRig();+ if (!rig || rig.kind === 'mannequin') return this._setState('no-rig');+ if (this._rigBoneCount() < MIN_RIG_BONES) return this._setState('incompatible');+ this._setState('ready');+ this._renderGallery();+ }++ // ── Shell + states ──────────────────────────────────────────────────────+ _renderShell() {+ this.host.innerHTML = '';+ const search = el('input', {+ type: 'search', class: 'al-search', placeholder: 'Search animations…',+ 'aria-label': 'Search animations', autocomplete: 'off',+ });+ search.addEventListener('input', () => {+ this._query = search.value.trim().toLowerCase();+ if (this._state === 'ready') this._renderGallery();+ });++ const chips = el('div', { class: 'al-chips', role: 'tablist', 'aria-label': 'Animation categories' });+ const grid = el('div', { class: 'al-grid' });+ const empty = el('div', { class: 'al-empty' });+ const transport = this._renderTransport();++ this._refs = { search, chips, grid, empty, transport };++ this.host.appendChild(search);+ this.host.appendChild(chips);+ this.host.appendChild(empty);+ this.host.appendChild(grid);+ this.host.appendChild(transport.root);+ }++ _setState(state) {+ this._state = state;+ const { search, chips, grid, empty, transport } = this._refs;+ const ready = state === 'ready';+ search.style.display = ready ? '' : 'none';+ chips.style.display = ready ? '' : 'none';+ grid.style.display = ready ? '' : 'none';+ transport.root.style.display = ready && this._activeName ? '' : 'none';+ empty.style.display = ready ? 'none' : '';++ if (ready) return;+ empty.innerHTML = '';+ const make = (icon, title, body, action) => {+ empty.appendChild(el('div', { class: 'al-empty-icon' }, [icon]));+ empty.appendChild(el('div', { class: 'al-empty-title' }, [title]));+ empty.appendChild(el('p', { class: 'al-empty-body' }, [body]));+ if (action) empty.appendChild(action);+ };+ if (state === 'loading') {+ empty.appendChild(el('div', { class: 'al-skeleton-grid' },+ Array.from({ length: 6 }, () => el('div', { class: 'al-skeleton' }))));+ } else if (state === 'error-load') {+ const retry = el('button', { class: 'al-cta', type: 'button' }, ['Retry']);+ retry.addEventListener('click', () => this.mount());+ make('⚠️', 'Couldn’t load the animation library',+ 'The clip manifest failed to load. Check your connection and try again.', retry);+ } else if (state === 'no-rig') {+ const cta = el('button', { class: 'al-cta', type: 'button' }, ['Load a rigged avatar']);+ cta.addEventListener('click', () => document.querySelector('#pose-load-avatar')?.click());+ make('🦴', 'Load a rigged avatar to animate',+ 'Animation presets apply to a rigged model. Load one of your avatars (or a public avatar) and the full gallery unlocks here.', cta);+ } else if (state === 'incompatible') {+ make('🚫', 'This rig can’t be retargeted',+ `The loaded model exposes only ${this._rigBoneCount()} recognizable humanoid bones — too few to drive the preset library. Try a standard humanoid avatar.`, null);+ }+ }++ // ── Category chips ──────────────────────────────────────────────────────+ _buildCategoryChips() {+ const { chips } = this._refs;+ chips.innerHTML = '';+ const mk = (key, label) => {+ const b = el('button', {+ class: 'al-chip', type: 'button', role: 'tab',+ 'data-cat': key, 'aria-selected': String(this._filterCat === key),+ }, [label]);+ b.addEventListener('click', () => {+ this._filterCat = key;+ chips.querySelectorAll('.al-chip').forEach((c) =>+ c.setAttribute('aria-selected', String(c.dataset.cat === key)));+ this._renderGallery();+ });+ return b;+ };+ chips.appendChild(mk('', 'All'));+ for (const g of this._curated.groups) chips.appendChild(mk(g.key, `${g.icon} ${g.label}`));+ }++ // ── Gallery ─────────────────────────────────────────────────────────────+ _matches(def) {+ if (this._filterCat && def.category !== this._filterCat) return false;+ if (this._query) {+ const hay = `${def.label || ''} ${def.name}`.toLowerCase();+ if (!hay.includes(this._query)) return false;+ }+ return true;+ }++ _renderGallery() {+ const { grid } = this._refs;+ grid.innerHTML = '';++ // Featured row only when unfiltered and unsearched.+ if (!this._filterCat && !this._query && this._curated.featured.length) {+ grid.appendChild(el('div', { class: 'al-section-label' }, ['Featured']));+ const row = el('div', { class: 'al-cards' });+ for (const def of this._curated.featured) row.appendChild(this._card(def));+ grid.appendChild(row);+ }++ for (const group of this._curated.groups) {+ const items = group.items.filter((d) => this._matches(d));+ if (!items.length) continue;+ grid.appendChild(el('div', { class: 'al-section-label' }, [`${group.icon} ${group.label}`]));+ const row = el('div', { class: 'al-cards' });+ for (const def of items) row.appendChild(this._card(def));+ grid.appendChild(row);+ }++ if (!grid.querySelector('.al-card')) {+ grid.appendChild(el('p', { class: 'al-no-match' },+ [`No animations match “${this._query}”.`]));+ }+ }++ _card(def) {+ const isActive = def.name === this._activeName;+ const card = el('button', {+ class: `al-card${isActive ? ' is-active' : ''}`,+ type: 'button',+ 'data-name': def.name,+ 'aria-pressed': String(isActive),+ title: `${def.label || def.name}${def.loop === false ? '' : ' · loops'}`,+ }, [+ el('span', { class: 'al-card-icon' }, [def.icon || '🎬']),+ el('span', { class: 'al-card-label' }, [def.label || def.name]),+ el('span', { class: 'al-card-badge' }, [def.loop === false ? 'once' : 'loop']),+ el('span', { class: 'al-card-eq', 'aria-hidden': 'true' },+ [el('i'), el('i'), el('i')]),+ ]);+ card.addEventListener('click', () => this.preview(def));+ return card;+ }++ _markActiveCard() {+ this._refs.grid.querySelectorAll('.al-card').forEach((c) => {+ const on = c.dataset.name === this._activeName;+ c.classList.toggle('is-active', on);+ c.setAttribute('aria-pressed', String(on));+ });+ }++ // ── Preview ─────────────────────────────────────────────────────────────+ async _loadClip(def) {+ if (this._clipCache.has(def.name)) return this._clipCache.get(def.name);+ const res = await fetch(def.url, { cache: 'force-cache' });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const clip = parseClipJSON(await res.json(), def.name);+ this._clipCache.set(def.name, clip);+ return clip;+ }++ _ensureMixer(rig) {+ if (this._mixer && this._mixerRoot === rig.root) return this._mixer;+ this._disposeMixer();+ this._mixer = new AnimationMixer(rig.root);+ this._mixerRoot = rig.root;+ return this._mixer;+ }++ /** Load → retarget → play a preset on the current rig. */+ async preview(def) {+ const rig = this.getRig();+ if (!rig || rig.kind === 'mannequin') {+ this.setStatus('Load a rigged avatar to apply animations.', 'error');+ return;+ }+ this.setStatus(`Loading ${def.label || def.name}…`);+ let clip;+ try {+ clip = await this._loadClip(def);+ } catch (err) {+ this._clipCache.delete(def.name);+ this.setStatus(`Couldn’t load “${def.label || def.name}”: ${err.message}`, 'error');+ return;+ }++ const { clip: retargeted, matched, total, coverage, dropped } = retargetClipToRig(clip, rig);+ if (!retargeted) {+ this.setStatus(+ `“${def.label || def.name}” can’t retarget to this rig — only ${matched}/${total} tracks mapped (need ${Math.round(MIN_COVERAGE * 100)}%).`,+ 'error',+ );+ return;+ }++ const mixer = this._ensureMixer(rig);+ mixer.stopAllAction();+ const action = mixer.clipAction(retargeted);+ action.setLoop(def.loop === false ? LoopOnce : LoopRepeat, Infinity);+ action.clampWhenFinished = def.loop === false;+ action.timeScale = this._speed;+ action.reset().play();++ this._action = action;+ this._activeName = def.name;+ this._activeDef = def;+ this._activeRetarget = { matched, total, coverage, dropped };++ if (!this._previewing) {+ this._previewing = true;+ this.onPreviewStart();+ }+ this._markActiveCard();+ this._updateTransport();+ this._refs.transport.root.style.display = '';++ const pct = Math.round(coverage * 100);+ const note = dropped.length+ ? ` (${matched}/${total} bones · ${dropped.length} not on this rig)`+ : ` (${matched}/${total} bones matched)`;+ this.setStatus(`Playing “${def.label || def.name}” — ${pct}% retargeted${note}.`);+ }++ stopPreview({ silent = false } = {}) {+ if (!this._previewing && !this._activeName) return;+ this._mixer?.stopAllAction();+ this._action = null;+ this._activeName = null;+ this._activeDef = null;+ this._previewing = false;+ this._markActiveCard?.();+ if (this._refs.transport) this._refs.transport.root.style.display = 'none';+ // Hand the figure back to the host in a clean rest pose.+ try { this.getRig()?.resetPose?.(); } catch { /* rig may be gone */ }+ this.onPreviewStop();+ if (!silent) this.setStatus('Preview stopped.');+ }++ _setSpeed(v) {+ this._speed = Math.min(2.5, Math.max(0.25, v));+ if (this._action) this._action.timeScale = this._speed;+ this._updateTransport();+ }++ // ── Transport bar (now-playing + speed + loop + stop + export) ────────────+ _renderTransport() {+ const label = el('span', { class: 'al-now-label' });+ const speedVal = el('span', { class: 'al-speed-val' }, ['1.0×']);+ const speed = el('input', {+ type: 'range', min: '0.25', max: '2.5', step: '0.05', value: '1',+ class: 'al-speed', 'aria-label': 'Playback speed',+ });+ speed.addEventListener('input', () => {+ this._setSpeed(parseFloat(speed.value));+ });+ const stop = el('button', { class: 'al-tbtn', type: 'button', title: 'Stop preview' }, ['⏹ Stop']);+ stop.addEventListener('click', () => this.stopPreview());++ const exportBtn = el('button', {+ class: 'al-export', type: 'button',+ title: 'Download a GLB with this animation baked in',+ }, ['Export animated GLB']);+ exportBtn.addEventListener('click', () => this._exportGLB(exportBtn));++ const root = el('div', { class: 'al-transport', style: 'display:none' }, [+ el('div', { class: 'al-now' }, [el('span', { class: 'al-now-dot' }), label]),+ el('div', { class: 'al-speed-row' }, [+ el('label', {}, ['Speed']), speed, speedVal,+ ]),+ el('div', { class: 'al-transport-actions' }, [stop, exportBtn]),+ ]);++ this._refs = { ...this._refs, transportLabel: label, transportSpeedVal: speedVal, transportSpeed: speed, exportBtn };+ return { root };+ }++ _updateTransport() {+ const { transportLabel, transportSpeedVal, transportSpeed } = this._refs;+ if (transportLabel && this._activeDef) {+ transportLabel.textContent = this._activeDef.label || this._activeDef.name;+ }+ if (transportSpeedVal) transportSpeedVal.textContent = `${this._speed.toFixed(2)}×`;+ if (transportSpeed) transportSpeed.value = String(this._speed);+ }++ async _exportGLB(btn) {+ const rig = this.getRig();+ if (!rig || !this._activeDef) return;+ const original = btn.textContent;+ const done = (txt, cls) => {+ btn.classList.remove('is-busy', 'is-ok', 'is-err');+ if (cls) btn.classList.add(cls);+ btn.textContent = txt;+ setTimeout(() => { btn.classList.remove('is-ok', 'is-err'); btn.textContent = original; }, 2400);+ };+ btn.classList.add('is-busy');+ btn.textContent = 'Baking…';+ try {+ const base = await this._loadClip(this._activeDef);+ const { clip } = retargetClipToRig(base, rig);+ if (!clip) throw new Error('retarget failed');+ const exportClip = scaleClipSpeed(clip, this._speed);+ exportClip.name = this._activeDef.name;++ // Park the figure on the clip's first frame so the exported rest pose+ // is the animation's start, not wherever the live preview paused.+ if (this._action) { this._action.time = 0; this._mixer.update(0); }++ const exporter = new GLTFExporter();+ const buffer = await exporter.parseAsync(rig.root, {+ binary: true,+ animations: [exportClip],+ embedImages: true,+ });+ const safeRig = (rig.root?.name || 'avatar').replace(/[^a-z0-9._-]+/gi, '-').slice(0, 40) || 'avatar';+ this._download(buffer, `${safeRig}-${this._activeDef.name}.glb`);+ done('Saved ✓', 'is-ok');+ this.setStatus(`Exported animated GLB: ${this._activeDef.label || this._activeDef.name}.`);+ } catch (err) {+ log.warn('[AnimationLibrary] export failed:', err);+ done('Failed', 'is-err');+ this.setStatus(`Export failed: ${err.message}`, 'error');+ }+ }++ _download(buffer, filename) {+ const blob = buffer instanceof Blob ? buffer : new Blob([buffer], { type: 'model/gltf-binary' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1500);+ }++ _disposeMixer() {+ if (this._mixer) {+ this._mixer.stopAllAction();+ try { this._mixer.uncacheRoot(this._mixerRoot); } catch { /* root already gone */ }+ }+ this._mixer = null;+ this._mixerRoot = null;+ this._action = null;+ }+}diff --git a/src/animation-presets.js b/src/animation-presets.jsnew file mode 100644index 000000000..e642564b7--- /dev/null+++ b/src/animation-presets.js@@ -0,0 +1,90 @@+// Curation layer over the runtime animation manifest (/public/animations/manifest.json).+//+// The manifest is a flat list of built clips. This module groups those clips+// into human-readable categories and marks a small "featured" set (the actions+// users reach for first: idle, walk, jump, wave, dance, celebrate) so the+// gallery can lead with them. It adds no clips of its own — every entry shown+// is a real, retargetable clip the build produced. Clips with no explicit+// category fall through to "More", so adding a clip to the manifest never makes+// it disappear from the gallery.++// Ordered category definitions. `key` matches values in CLIP_CATEGORIES.+export const CATEGORIES = [+ { key: 'idle', label: 'Idle & Stand', icon: '🧍' },+ { key: 'locomotion', label: 'Locomotion', icon: '🚶' },+ { key: 'dance', label: 'Dance', icon: '💃' },+ { key: 'gesture', label: 'Gestures', icon: '👋' },+ { key: 'action', label: 'Action & Combat', icon: '🥊' },+ { key: 'sport', label: 'Sports', icon: '⚽' },+ { key: 'reaction', label: 'Reactions & Falls', icon: '😲' },+ { key: 'fitness', label: 'Fitness & Yoga', icon: '🧘' },+ { key: 'more', label: 'More', icon: '✨' },+];++// Clip name → category key. Names mirror manifest.json / animations.config.json.+export const CLIP_CATEGORIES = Object.freeze({+ // Idle & stand+ idle: 'idle', 'av-idle-breath': 'idle', 'av-waiting': 'idle', 'av-idle-anim': 'idle',+ 'av-idle-male': 'idle', 'av-idle-female': 'idle', 'av-chilling': 'idle', 'av-pose1': 'idle',+ 'av-leaning-wall': 'idle', 'av-smoking': 'idle', 'av-listening-music': 'idle', standup: 'idle',+ coverstand: 'idle',+ // Locomotion+ walk: 'locomotion', 'av-walk-feminine': 'locomotion', 'av-walk-crouching': 'locomotion',+ stepback: 'locomotion', dodge: 'locomotion',+ // Dance+ dance: 'dance', rumba: 'dance', silly: 'dance', thriller: 'dance', capoeira: 'dance',+ 'av-dance-shuffle': 'dance', 'av-headbang': 'dance', 'av-boxer-dance': 'dance',+ 'av-rap-dance': 'dance', 'av-banging-tunes': 'dance', 'av-conductor': 'dance',+ // Gestures & expression+ wave: 'gesture', 'av-call-me': 'gesture', 'av-brag-claps': 'gesture', pray: 'gesture',+ kiss: 'gesture', taunt: 'gesture', 'av-vtubing': 'gesture', 'av-spy': 'gesture',+ 'av-joy': 'gesture', facepalm: 'gesture', angry: 'gesture', lookdown: 'gesture',+ covereyes: 'gesture',+ // Celebrations+ celebrate: 'gesture', 'av-celebrating': 'gesture', 'av-cheering': 'gesture',+ // Action & combat+ jump: 'action', 'av-superhero-jump': 'action', 'av-back-flip': 'action',+ 'av-gymnastics-aerial': 'action', 'av-muay-thai': 'action', 'av-chest-bump': 'action',+ 'av-arm-flex': 'action', 'av-flexing-arm': 'action', 'av-push-block': 'action',+ 'av-stand-crouch-stand': 'action', removing: 'action',+ // Sports+ header: 'sport', goalkeeper: 'sport',+ // Reactions & falls+ reaction: 'reaction', shoved: 'reaction', defeated: 'reaction', dying: 'reaction',+ falling: 'reaction', falltolanding: 'reaction', jumpdown: 'reaction', jumpdown2: 'reaction',+ jumpdown3: 'reaction', sitclap: 'reaction', sitlaugh: 'reaction',+ // Fitness & yoga+ downdog: 'fitness',+});++// The headline actions. Order is intentional — it's the row users see first.+export const FEATURED = ['idle', 'walk', 'jump', 'wave', 'dance', 'celebrate'];++/** Category key for a clip, defaulting to 'more'. */+export function categoryOf(name) {+ return CLIP_CATEGORIES[name] || 'more';+}++/**+ * Group manifest defs into ordered, non-empty categories, and resolve the+ * featured defs (in FEATURED order). Defs keep their manifest shape plus an+ * added `category` key.+ *+ * @param {Array<{name:string,label?:string,icon?:string,loop?:boolean,url:string}>} defs+ * @returns {{ featured: Array, groups: Array<{key:string,label:string,icon:string,items:Array}> }}+ */+export function curate(defs) {+ const byName = new Map(defs.map((d) => [d.name, { ...d, category: categoryOf(d.name) }]));+ const tagged = [...byName.values()];++ const featured = FEATURED.map((n) => byName.get(n)).filter(Boolean);++ const groups = CATEGORIES.map((cat) => ({+ ...cat,+ items: tagged+ .filter((d) => d.category === cat.key)+ .sort((a, b) => (a.label || a.name).localeCompare(b.label || b.name)),+ })).filter((g) => g.items.length > 0);++ return { featured, groups };+}diff --git a/src/animation-retarget.js b/src/animation-retarget.jsnew file mode 100644index 000000000..5bfdf73b9--- /dev/null+++ b/src/animation-retarget.js@@ -0,0 +1,222 @@+// Runtime animation retargeting — apply a canonical-skeleton clip to an+// arbitrary rigged model whose bones may be named differently (Mixamo, Blender,+// Rigify, snake_case, …) and proportioned differently (tall, short, chunky).+//+// The pre-baked library in /public/animations/clips addresses tracks by the+// canonical Avaturn bone names (Hips, Spine, LeftArm, …). A loaded GLB rig might+// name the same bones `mixamorig:Hips`, `DEF-spine`, `left_arm`, etc. To drive+// (and export) that rig we rewrite each track's bone name to the *actual* node+// name on the target, drop tracks the rig has no bone for, and rescale the hip+// translation so root motion lands at the new rig's height instead of the+// authoring rig's. The result binds cleanly in both THREE.AnimationMixer+// (preview) and THREE.GLTFExporter (animated-GLB export).+//+// Pure module — three + the canonicalizer only — so it runs unchanged in the+// browser (the /pose gallery) and in Node (the apply_animation MCP tool, vitest).++import { AnimationClip, Vector3 } from 'three';+import { canonicalizeBoneName } from './glb-canonicalize.js';++// A clip retargets cleanly only when enough of its tracks find a home on the+// target rig. Below this the motion would read as a few twitching joints rather+// than a performance, so callers surface an actionable "can't retarget" error.+export const MIN_COVERAGE = 0.5;++const _v = new Vector3();++/**+ * @typedef {Object} RetargetResult+ * @property {AnimationClip|null} clip Retargeted clip (track names rewritten to+ * the target's bone names), or null when coverage is below MIN_COVERAGE.+ * @property {number} matched Tracks successfully mapped onto the target.+ * @property {number} total Tracks in the source clip.+ * @property {number} coverage matched / total (0–1).+ * @property {string[]} dropped Canonical bone names the target rig lacks.+ * @property {number} hipScale Factor applied to hip translation (1 = none).+ */++/**+ * Build a `canonical bone → target node name` map by walking an Object3D graph.+ * Used server-side (apply_animation) where there's no GltfRig wrapper. Prefers+ * SkinnedMesh skeleton bones, falls back to any named Bone nodes.+ *+ * @param {import('three').Object3D} root+ * @returns {Map<string,string>}+ */+export function canonicalNodeMapFromObject(root) {+ const map = new Map();+ const consider = (node) => {+ if (!node?.name) return;+ const canonical = canonicalizeBoneName(node.name);+ if (canonical && !map.has(canonical)) map.set(canonical, node.name);+ };+ const skinned = [];+ root.traverse((node) => {+ if (node.isSkinnedMesh) skinned.push(node);+ if (node.isBone) consider(node);+ });+ for (const sm of skinned) {+ for (const bone of sm.skeleton?.bones || []) consider(bone);+ }+ return map;+}++/**+ * Build the same map from a GltfRig/MannequinRig (src/pose-rig.js), which has+ * already resolved canonical → node. We read each node's live `.name` so the+ * rewritten track binds to the real graph node.+ *+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig+ * @returns {Map<string,string>}+ */+export function canonicalNodeMapFromRig(rig) {+ const map = new Map();+ for (const { key, node } of rig.getBones?.() || []) {+ if (node?.name) map.set(key, node.name);+ }+ return map;+}++/**+ * World-space rest height of the target's hips, used to scale root translation+ * onto a differently-sized rig. Returns 0 if it can't be determined (callers+ * then skip hip scaling). Requires world matrices to be current.+ *+ * @param {{ getNode: (k:string) => import('three').Object3D|null }} rig+ * @returns {number}+ */+export function hipRestHeight(rig) {+ const hips = rig.getNode?.('Hips');+ if (!hips) return 0;+ hips.updateWorldMatrix(true, false);+ hips.getWorldPosition(_v);+ return _v.y;+}++// First Y value of a `Hips.position` track — the height the clip's root motion+// was authored around. The retarget scales other-height rigs by target/source.+function clipHipBaselineY(clip) {+ const track = clip.tracks.find(+ (t) => t.name.endsWith('.position') && canonicalizeBoneName(t.name.split('.')[0]) === 'Hips',+ );+ if (!track || track.values.length < 3) return 0;+ return track.values[1]; // [x, y, z, …] — Y of the first keyframe+}++/**+ * Core rewrite. Splits each track into `bone.property`, canonicalizes the bone,+ * looks up the target's node name, and emits a renamed track. Hip position+ * tracks are scaled by `hipScale`. Returns null clip when coverage is too low.+ *+ * @param {AnimationClip} clip+ * @param {Map<string,string>} canonicalToNode+ * @param {{ hipScale?: number, minCoverage?: number }} [opts]+ * @returns {RetargetResult}+ */+export function retargetClip(clip, canonicalToNode, opts = {}) {+ const hipScale = Number.isFinite(opts.hipScale) && opts.hipScale > 0 ? opts.hipScale : 1;+ const minCoverage = opts.minCoverage ?? MIN_COVERAGE;+ const total = clip.tracks.length;+ const dropped = [];+ const tracks = [];++ for (const track of clip.tracks) {+ const dot = track.name.indexOf('.');+ if (dot === -1) continue;+ const boneRaw = track.name.slice(0, dot);+ const property = track.name.slice(dot + 1);+ const canonical = canonicalizeBoneName(boneRaw) || boneRaw;+ const nodeName = canonicalToNode.get(canonical);+ if (!nodeName) {+ dropped.push(canonical);+ continue;+ }+ const next = track.clone();+ next.name = `${nodeName}.${property}`;+ if (hipScale !== 1 && canonical === 'Hips' && property === 'position') {+ for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;+ }+ tracks.push(next);+ }++ const matched = tracks.length;+ const coverage = total > 0 ? matched / total : 0;+ if (coverage < minCoverage) {+ return { clip: null, matched, total, coverage, dropped, hipScale };+ }+ const out = clip.clone();+ out.tracks = tracks;+ return { clip: out, matched, total, coverage, dropped, hipScale };+}++/**+ * High-level: retarget a canonical clip onto a rig (GltfRig/MannequinRig),+ * computing hip scaling from the rig's actual proportions. Mutates nothing.+ *+ * @param {AnimationClip} clip+ * @param {object} rig+ * @param {{ scaleHips?: boolean, minCoverage?: number }} [opts]+ * @returns {RetargetResult}+ */+export function retargetClipToRig(clip, rig, opts = {}) {+ const map = canonicalNodeMapFromRig(rig);+ let hipScale = 1;+ if (opts.scaleHips !== false) {+ const targetY = hipRestHeight(rig);+ const sourceY = clipHipBaselineY(clip);+ if (targetY > 0.05 && sourceY > 0.05) {+ // Clamp so a wildly off baseline (or a near-zero in-place clip) can't+ // fling the root metres away.+ hipScale = Math.min(5, Math.max(0.2, targetY / sourceY));+ }+ }+ return retargetClip(clip, map, { hipScale, minCoverage: opts.minCoverage });+}++/**+ * Retarget onto a raw Object3D graph (server-side apply_animation). No hip+ * scaling by default — the caller may pass an explicit factor.+ *+ * @param {AnimationClip} clip+ * @param {import('three').Object3D} root+ * @param {{ hipScale?: number, minCoverage?: number }} [opts]+ * @returns {RetargetResult}+ */+export function retargetClipToObject(clip, root, opts = {}) {+ const map = canonicalNodeMapFromObject(root);+ return retargetClip(clip, map, opts);+}++/**+ * Resample a clip's timing to play at `factor`× speed (1.8 turns a walk into a+ * run). Used so an exported GLB carries the tempo the user previewed, not just+ * a mixer timeScale that doesn't survive the file. Pure — returns a clone.+ *+ * @param {AnimationClip} clip+ * @param {number} factor >1 faster, <1 slower+ * @returns {AnimationClip}+ */+export function scaleClipSpeed(clip, factor) {+ if (!(factor > 0) || factor === 1) return clip;+ const out = clip.clone();+ const inv = 1 / factor;+ for (const track of out.tracks) {+ for (let i = 0; i < track.times.length; i++) track.times[i] *= inv;+ }+ out.duration = clip.duration * inv;+ return out;+}++/**+ * Convenience: parse a clip from its three.js JSON (the on-disk clip format),+ * naming it. Centralised so browser and server load clips identically.+ *+ * @param {object} json+ * @param {string} name+ * @returns {AnimationClip}+ */+export function parseClipJSON(json, name) {+ const clip = AnimationClip.parse(json);+ if (name) clip.name = name;+ return clip;+}diff --git a/src/pose-studio.js b/src/pose-studio.jsindex cf68bb923..d3eaec36c 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -58,6 +58,7 @@ import {DEFAULT_EASING,} from './pose-animation.js';import { PoseLibrary } from './pose-library.js';+import { AnimationLibrary } from './animation-library.js';import { log } from './shared/log.js';// ─── DOM helpers ────────────────────────────────────────────────────────@@ -349,6 +350,7 @@ function boot() {renderBoneList();updateSelectionLabel();timeline?.onRigChanged();+ state.animLibrary?.onRigChanged();}const mannequinRig = new MannequinRig({ build: 'male', color: '#d4d4d8' });@@ -367,7 +369,10 @@ function boot() {const dt = Math.min((now - lastFrameMs) / 1000, 0.1); // cap to avoid tab-switch jumpslastFrameMs = now;controls.update();- timeline?.update(dt);+ // A preset preview owns the figure while it runs; the keyframe timeline+ // yields so the two never fight over bone transforms.+ if (state.animLibrary?.isPreviewing()) state.animLibrary.update(dt);+ else timeline?.update(dt);if (state.poseMode === 'ik' && !state.draggingIK) syncIKHandles();renderer.render(scene, camera);}@@ -1284,6 +1289,7 @@ function boot() {return {update: advance,+ pause,onRigChanged: () => { if (doc.keyframes.length) applyPreview(); },bake: () => bakeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),serialize: () => serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),diff --git a/workers/remesh/Dockerfile b/workers/remesh/Dockerfileindex a15fc2bb2..05c859942 100644--- a/workers/remesh/Dockerfile+++ b/workers/remesh/Dockerfile@@ -2,8 +2,24 @@ FROM python:3.11-slimENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \- PIP_NO_CACHE_DIR=1+ PIP_NO_CACHE_DIR=1 \+ QUADRIFLOW_BIN=/usr/local/bin/quadriflow+# ── Build QuadriFlow (MIT) from source ───────────────────────────────────────+# Field-aligned quad-dominant remesher. MIT-licensed (commercial-OK); invoked as+# a standalone CLI so its permissive transitive deps never link into our code.+RUN apt-get update && apt-get install -y --no-install-recommends \+ build-essential cmake git ca-certificates \+ libboost-dev libboost-program-options-dev libeigen3-dev \+ && rm -rf /var/lib/apt/lists/*++RUN git clone --depth 1 --recursive https://github.com/hjwdzh/QuadriFlow /tmp/quadriflow \+ && cmake -S /tmp/quadriflow -B /tmp/quadriflow/build -DCMAKE_BUILD_TYPE=Release \+ && cmake --build /tmp/quadriflow/build -j "$(nproc)" \+ && install -m 0755 /tmp/quadriflow/build/quadriflow /usr/local/bin/quadriflow \+ && rm -rf /tmp/quadriflow++# ── Runtime deps for trimesh / open3d / assimp / usd ─────────────────────────RUN apt-get update && apt-get install -y --no-install-recommends \libgl1 libglib2.0-0 libgomp1 \libassimp-dev libassimp5 \diff --git a/workers/remesh/__pycache__/main.cpython-312.pyc b/workers/remesh/__pycache__/main.cpython-312.pycnew file mode 100644index 000000000..3327d9873Binary files /dev/null and b/workers/remesh/__pycache__/main.cpython-312.pyc differdiff --git a/workers/remesh/blender_fbx.py b/workers/remesh/blender_fbx.pynew file mode 100644index 000000000..e8e7bf22e--- /dev/null+++ b/workers/remesh/blender_fbx.py@@ -0,0 +1,125 @@+"""+Headless Blender → FBX converter for the remesh worker.++trimesh and assimp cannot write FBX with a skeleton: trimesh has no FBX+exporter at all, and pyassimp/assimp's FBX writer does not round-trip armatures,+skin weights, or blendshapes. Blender's `io_scene_fbx` exporter is the+industry-standard path that Unity and Unreal users implicitly rely on — it reads+a GLB's armature, per-vertex skin weights, and shape keys, and writes them back+out as a proper FBX bone hierarchy with blendshapes.++We run this as a one-shot subprocess (never in-process in the FastAPI worker):+`bpy` keeps a single global Blender context, is not thread-safe, and accumulates+data across operations. A fresh process per conversion gives a clean scene,+thread safety under the worker's concurrency, and reclaimed memory on exit.++Usage:+ python blender_fbx.py <input> <output.fbx> [--static]++`--static` skips animation baking — used when the upstream geometry op+(simplify/repair) has already discarded any rig, so the FBX is a plain mesh.++On success, prints `FACE_COUNT:<n>` to stdout (polygons across all mesh objects).+"""++from __future__ import annotations++import sys+from pathlib import Path++import bpy++# Input extensions Blender can import directly (preserving rig where present).+# `.off` is intentionally excluded — Blender has no OFF importer, so the worker+# round-trips those through trimesh → GLB before calling us.+_IMPORTERS = {".glb", ".gltf", ".fbx", ".obj", ".stl", ".ply", ".dae"}+++def _reset_scene() -> None:+ """Start from a truly empty file — no default cube, camera, or light."""+ bpy.ops.wm.read_factory_settings(use_empty=True)+++def _enable_addon(module: str) -> None:+ try:+ bpy.ops.preferences.addon_enable(module=module)+ except Exception:+ # Bundled importers/exporters are enabled by default in the bpy module;+ # a failure here is non-fatal because the operator is still registered.+ pass+++def _import_source(path: Path) -> None:+ suffix = path.suffix.lower()+ if suffix in (".glb", ".gltf"):+ _enable_addon("io_scene_gltf2")+ bpy.ops.import_scene.gltf(filepath=str(path), import_pack_images=True)+ elif suffix == ".fbx":+ _enable_addon("io_scene_fbx")+ bpy.ops.import_scene.fbx(filepath=str(path))+ elif suffix == ".obj":+ bpy.ops.wm.obj_import(filepath=str(path))+ elif suffix == ".stl":+ bpy.ops.wm.stl_import(filepath=str(path))+ elif suffix == ".ply":+ bpy.ops.wm.ply_import(filepath=str(path))+ elif suffix == ".dae":+ bpy.ops.wm.collada_import(filepath=str(path))+ else:+ raise SystemExit(f"blender_fbx: unsupported input format '{suffix}'")+++def _face_count() -> int:+ total = 0+ for obj in bpy.data.objects:+ if obj.type == "MESH" and obj.data is not None:+ total += len(obj.data.polygons)+ return total+++def _export_fbx(path: Path, static: bool) -> None:+ _enable_addon("io_scene_fbx")+ # path_mode='COPY' + embed_textures keeps the result a single self-contained+ # file. add_leaf_bones=False avoids the extra tip bones that make Unity warn.+ # use_armature_deform_only=False keeps every bone (control bones included).+ bpy.ops.export_scene.fbx(+ filepath=str(path),+ use_selection=False,+ apply_unit_scale=True,+ apply_scale_options="FBX_SCALE_NONE",+ use_mesh_modifiers=True,+ mesh_smooth_type="FACE",+ add_leaf_bones=False,+ use_armature_deform_only=False,+ bake_anim=not static,+ bake_anim_use_all_actions=not static,+ path_mode="COPY",+ embed_textures=True,+ )+++def main() -> None:+ args = sys.argv[1:]+ static = "--static" in args+ positional = [a for a in args if not a.startswith("--")]+ if len(positional) != 2:+ raise SystemExit("usage: blender_fbx.py <input> <output.fbx> [--static]")++ in_path = Path(positional[0])+ out_path = Path(positional[1])+ if in_path.suffix.lower() not in _IMPORTERS:+ raise SystemExit(f"blender_fbx: cannot import '{in_path.suffix}'")++ _reset_scene()+ _import_source(in_path)+ faces = _face_count()+ _export_fbx(out_path, static)++ if not out_path.exists() or out_path.stat().st_size == 0:+ raise SystemExit("blender_fbx: exporter produced no output")++ print(f"FACE_COUNT:{faces}")+++if __name__ == "__main__":+ main()diff --git a/workers/remesh/main.py b/workers/remesh/main.pyindex 64d75b870..46c185860 100644--- a/workers/remesh/main.py+++ b/workers/remesh/main.py@@ -1,29 +1,45 @@"""-Mesh processing service — remesh, simplify, repair, and convert 3D files.+Mesh processing service — remesh, simplify, repair, retopologize, and convert 3D files.-Wraps trimesh + open3d. No GPU required; runs on CPU. Handles:+Wraps trimesh + open3d + QuadriFlow + xatlas. No GPU required; runs on CPU. Handles:- Format conversion (GLB ↔ OBJ ↔ FBX ↔ STL ↔ PLY ↔ USDZ ↔ 3MF)- - Face count reduction (quadric decimation via open3d)+ - Triangle decimation (quadric error metric via open3d)+ - Quad remeshing (field-aligned quad-dominant topology via QuadriFlow, MIT)+ - Smart low-poly (silhouette-preserving decimation + UV re-unwrap + texture re-bake)- Mesh repair (fill holes, remove degenerate faces, fix normals)- Vertex deduplication and cleaning- - UV unwrapping for meshes without UV maps++Tooling / licensing:+ - QuadriFlow (https://github.com/hjwdzh/QuadriFlow) — MIT, commercial-OK. A scalable,+ robust field-aligned quadrangulation method. Invoked as a separate CLI process+ (built from source in the Dockerfile) so its permissively-licensed transitive deps+ never link into our code. Chosen over Instant Meshes (GPLv3) and Exoside Quad+ Remesher (paid, closed) precisely because MIT is unambiguously commercial-safe.+ - xatlas (https://github.com/jpcy/xatlas, via xatlas-python) — MIT. UV atlas+ generation used to re-unwrap remeshed geometry so a baked texture maps cleanly.API contract:POST /process {mesh: url, # https GLB/OBJ/FBX/STL URL (required)- operation: "convert"|"simplify"|"repair"|"full", # default: "full"+ remesh_mode: "triangle"|"quad"|"lowpoly", # default: "triangle"+ operation: "convert"|"simplify"|"repair"|"full", # default: "full" (triangle mode only)target_faces?: int, # default: 50000, range: 1000–500000+ texture_size?: int, # 512|1024|2048, default 1024 (bake atlas size)output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf", # default: "glb"} → 202 { task_id, status }- GET /tasks/:id → { task_id, status, result_url?, face_count?, error? }+ GET /tasks/:id → {+ task_id, status, result_url?, texture_url?, mtl_url?,+ face_count?, quad_ratio?, mode?, textured?, error?+ }GET /health → { ok }Environment variables:- API_KEY — bearer secret (required)- GCS_BUCKET — output bucket (required)+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)MAX_CONCURRENT — default 2+ QUADRIFLOW_BIN — path to the quadriflow executable (default: "quadriflow")"""from __future__ import annotations@@ -32,6 +48,8 @@ import asyncioimport ioimport loggingimport os+import shutil+import subprocessimport tempfileimport timeimport uuid@@ -59,6 +77,7 @@ log = logging.getLogger("remesh")API_KEY = os.environ["API_KEY"]GCS_BUCKET = os.environ["GCS_BUCKET"]MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))+QUADRIFLOW_BIN = os.environ.get("QUADRIFLOW_BIN", "quadriflow")_bucket: Optional[storage.Bucket] = None_sem: Optional[asyncio.Semaphore] = None@@ -66,6 +85,8 @@ _tasks: dict[str, dict] = {}SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply", "usdz", "3mf"}+VALID_MODES = {"triangle", "quad", "lowpoly"}+VALID_TEXTURE_SIZES = {512, 1024, 2048}MAX_MESH_BYTES = 128 * 1024 * 1024@@ -76,7 +97,11 @@ async def lifespan(app: FastAPI):_sem = asyncio.Semaphore(MAX_CONCURRENT)import trimeshimport open3d- log.info("remesh service ready — trimesh %s, open3d %s", trimesh.__version__, open3d.__version__)+ quad = shutil.which(QUADRIFLOW_BIN) or QUADRIFLOW_BIN+ log.info(+ "remesh service ready — trimesh %s, open3d %s, quadriflow=%s",+ trimesh.__version__, open3d.__version__, quad,+ )yield@@ -90,6 +115,8 @@ def _require_api_key(authorization: str) -> None:raise HTTPException(status_code=401, detail=str(exc)) from exc+# ── Loading ──────────────────────────────────────────────────────────────────+def _fetch_mesh(url: str) -> tuple[bytes, str]:try:data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)@@ -101,34 +128,81 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:return data, suffix-def _load_mesh(data: bytes, suffix: str):+def _load_concatenated(data: bytes, suffix: str):+ """Load a mesh, flattening any scene into one Trimesh. Drops materials —+ used by the triangle pipeline where texture transfer is not performed."""import trimesh- return trimesh.load(- io.BytesIO(data),- file_type=suffix.lstrip("."),- force="mesh",- process=False,+ mesh = trimesh.load(+ io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=False,)+ if isinstance(mesh, trimesh.Scene):+ meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]+ if not meshes:+ raise ValueError("no renderable geometry found in scene")+ mesh = trimesh.util.concatenate(meshes)+ return mesh+++def _load_textured(data: bytes, suffix: str):+ """Load preserving UVs + texture for the quad/lowpoly pipelines. When the+ asset is a multi-mesh scene we keep the single largest textured submesh so+ its UV/material survives (concatenation would discard per-mesh textures)."""+ import trimesh+ loaded = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), process=False)++ if isinstance(loaded, trimesh.Trimesh):+ return loaded++ if isinstance(loaded, trimesh.Scene):+ meshes = [g for g in loaded.geometry.values() if isinstance(g, trimesh.Trimesh)]+ if not meshes:+ raise ValueError("no renderable geometry found in scene")+ textured = [m for m in meshes if _source_texture(m)[1] is not None]+ if textured:+ return max(textured, key=lambda m: len(m.faces))+ # No textures anywhere — concatenating is lossless for geometry.+ return trimesh.util.concatenate(meshes)++ raise ValueError("unsupported mesh container")+++def _source_texture(mesh):+ """Return (uv ndarray | None, PIL.Image | None) for a mesh's base texture."""+ import numpy as np+ visual = getattr(mesh, "visual", None)+ uv = getattr(visual, "uv", None)+ if uv is not None:+ uv = np.asarray(uv)+ if uv.ndim != 2 or len(uv) != len(mesh.vertices):+ uv = None+ image = None+ material = getattr(visual, "material", None)+ if material is not None:+ image = (+ getattr(material, "baseColorTexture", None)+ or getattr(material, "image", None)+ )+ return uv, image+# ── Repair / triangle decimation (existing behaviour) ────────────────────────+def _repair_mesh(mesh):import trimesh- # Fill holestrimesh.repair.fill_holes(mesh)- # Remove degenerate faces (zero-area)mask = mesh.nondegenerate_faces()mesh.update_faces(mask)- # Fix normalstrimesh.repair.fix_normals(mesh)- # Merge duplicate verticesmesh.merge_vertices()- # Remove unreferenced verticesmesh.remove_unreferenced_vertices()return mesh-def _simplify_mesh(mesh, target_faces: int):- """Quadric decimation via open3d, fallback to trimesh."""+def _decimate(mesh, target_faces: int):+ """Quadric (QEM) triangle decimation via open3d, trimesh fallback.++ QEM preserves the silhouette far better than uniform clustering, which is+ exactly the property the low-poly preset relies on."""import open3d as o3dimport numpy as np@@ -136,117 +210,483 @@ def _simplify_mesh(mesh, target_faces: int):return meshtry:- # Convert trimesh → open3do3d_mesh = o3d.geometry.TriangleMesh()o3d_mesh.vertices = o3d.utility.Vector3dVector(mesh.vertices.astype(np.float64))o3d_mesh.triangles = o3d.utility.Vector3iVector(mesh.faces.astype(np.int32))- if mesh.vertex_normals is not None and len(mesh.vertex_normals):- o3d_mesh.vertex_normals = o3d.utility.Vector3dVector(mesh.vertex_normals.astype(np.float64))-- # Quadric decimation- simplified = o3d_mesh.simplify_quadric_decimation(target_faces)+ simplified = o3d_mesh.simplify_quadric_decimation(int(target_faces))+ simplified.remove_unreferenced_vertices()simplified.compute_vertex_normals()- # Convert back to trimeshimport trimesh- result = trimesh.Trimesh(+ return trimesh.Trimesh(vertices=np.asarray(simplified.vertices),faces=np.asarray(simplified.triangles),vertex_normals=np.asarray(simplified.vertex_normals),process=False,)- return resultexcept Exception as exc:- log.warning("open3d simplification failed (%s), using trimesh fallback", exc)- # trimesh built-in simplification (less accurate but always works)- return mesh.simplify_quadric_decimation(target_faces)+ log.warning("open3d decimation failed (%s), using trimesh fallback", exc)+ return mesh.simplify_quadric_decimation(int(target_faces))++# ── Quad remeshing (QuadriFlow) ──────────────────────────────────────────────++def _write_obj_geometry(mesh, path: Path) -> None:+ """Write a minimal v/f OBJ — QuadriFlow only consumes geometry."""+ import numpy as np+ v = np.asarray(mesh.vertices)+ f = np.asarray(mesh.faces)+ lines = [f"v {x:.6f} {y:.6f} {z:.6f}" for x, y, z in v]+ lines += [f"f {a + 1} {b + 1} {c + 1}" for a, b, c in f]+ path.write_text("\n".join(lines) + "\n")-def _export_mesh(mesh, output_format: str, task_id: str) -> tuple[bytes, str]:++def _parse_obj(path: Path):+ """Parse an OBJ into (vertices, faces) where faces preserve quad arity.++ Returns (np.ndarray[V,3], list[list[int]] 0-based). Polygons with >4 sides+ are fan-triangulated; tris and quads are kept verbatim so quad_ratio is real."""+ import numpy as np+ verts: list[list[float]] = []+ faces: list[list[int]] = []+ for raw in path.read_text().splitlines():+ if raw.startswith("v "):+ _, x, y, z = raw.split()[:4]+ verts.append([float(x), float(y), float(z)])+ elif raw.startswith("f "):+ idx = [int(tok.split("/")[0]) - 1 for tok in raw.split()[1:]]+ if len(idx) <= 4:+ faces.append(idx)+ else:+ for i in range(1, len(idx) - 1):+ faces.append([idx[0], idx[i], idx[i + 1]])+ return np.asarray(verts, dtype=np.float64), faces+++def _quad_remesh(mesh, target_faces: int):+ """Run QuadriFlow to produce quad-dominant topology.++ Returns (verts, polys, quad_ratio) where polys is a list of 0-based index+ lists (length 3 or 4). Raises with an actionable message if the binary or+ the run fails — we never silently fall back to triangle soup for a quad+ request, which would mislead the caller."""+ binary = shutil.which(QUADRIFLOW_BIN) or QUADRIFLOW_BIN+ if shutil.which(QUADRIFLOW_BIN) is None and not os.path.isfile(binary):+ raise RuntimeError(+ "quad remesher unavailable: the quadriflow binary was not found. "+ "Build it from https://github.com/hjwdzh/QuadriFlow and set QUADRIFLOW_BIN."+ )++ with tempfile.TemporaryDirectory() as tmp:+ src = Path(tmp) / "in.obj"+ dst = Path(tmp) / "out.obj"+ _write_obj_geometry(mesh, src)++ cmd = [+ binary,+ "-i", str(src),+ "-o", str(dst),+ "-f", str(max(1000, int(target_faces))),+ "-mcf", # minimum-cost-flow solver: fewer singularities, cleaner loops+ "-sharp", # preserve sharp feature edges+ ]+ try:+ proc = subprocess.run(+ cmd, capture_output=True, text=True, timeout=600, check=False,+ )+ except subprocess.TimeoutExpired as exc:+ raise RuntimeError("quad remesh timed out after 600s") from exc++ if proc.returncode != 0 or not dst.exists():+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-5:]+ raise RuntimeError("quad remesh failed: " + " | ".join(tail))++ verts, polys = _parse_obj(dst)++ if not polys:+ raise RuntimeError("quad remesh produced empty output")+ quads = sum(1 for p in polys if len(p) == 4)+ quad_ratio = quads / len(polys)+ return verts, polys, quad_ratio+++def _triangulate_polys(verts, polys):+ """Triangulate a mixed tri/quad polygon list into a Trimesh (for GLB export+ and texture baking — glTF has no native quads)."""+ import numpy as np+ import trimesh+ tris: list[list[int]] = []+ for p in polys:+ if len(p) == 3:+ tris.append(p)+ elif len(p) == 4:+ tris.append([p[0], p[1], p[2]])+ tris.append([p[0], p[2], p[3]])+ mesh = trimesh.Trimesh(vertices=verts, faces=np.asarray(tris), process=False)+ mesh.remove_unreferenced_vertices()+ return mesh+++# ── UV unwrap + texture baking ───────────────────────────────────────────────++def _unwrap(mesh):+ """Generate a clean UV atlas for `mesh` with xatlas.++ Returns (vertices, faces, uv) on xatlas' (possibly re-indexed) vertex set,+ or None if xatlas is unavailable."""+ try:+ import xatlas+ except Exception as exc: # pragma: no cover - import guard+ log.warning("xatlas unavailable (%s); skipping UV unwrap", exc)+ return None+ import numpy as np+ vmapping, indices, uvs = xatlas.parametrize(+ np.asarray(mesh.vertices, dtype=np.float32),+ np.asarray(mesh.faces, dtype=np.uint32),+ )+ new_vertices = np.asarray(mesh.vertices)[vmapping]+ return new_vertices, np.asarray(indices, dtype=np.int64), np.asarray(uvs, dtype=np.float64)+++def _dilate(img, mask, iters: int = 6):+ """Edge-pad a baked atlas so bilinear sampling at UV-island borders doesn't+ bleed background. Iteratively fills empty texels from filled 4-neighbours."""+ import numpy as np+ img = img.copy()+ mask = mask.copy()+ for _ in range(iters):+ if mask.all():+ break+ filled = mask+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ shifted = np.roll(filled, (dy, dx), axis=(0, 1))+ shifted_img = np.roll(img, (dy, dx), axis=(0, 1))+ take = shifted & ~mask+ img[take] = shifted_img[take]+ mask = mask | take+ return img+++def _bake_texture(source_mesh, src_uv, src_img, verts, faces, uvs, tex_size: int):+ """Re-project the source texture onto a remeshed target's new UV atlas.++ For every texel covered by a target triangle we find its 3D position, query+ the closest point on the original textured surface, read the original UV+ there, and sample the original texture. This transfers the appearance even+ though topology and UVs changed completely."""+ import numpy as np+ import trimesh+ from PIL import Image++ src_arr = np.asarray(src_img.convert("RGB"))+ sh, sw = src_arr.shape[:2]+ src_faces = np.asarray(source_mesh.faces)+ src_tris = source_mesh.triangles # (F,3,3)+ prox = trimesh.proximity.ProximityQuery(source_mesh)++ atlas = np.zeros((tex_size, tex_size, 3), dtype=np.uint8)+ written = np.zeros((tex_size, tex_size), dtype=bool)++ sample_pts: list = []+ sample_px: list = [] # (row, col)++ uv_px = uvs.copy()+ uv_px[:, 0] = np.clip(uvs[:, 0], 0.0, 1.0) * (tex_size - 1)+ uv_px[:, 1] = (1.0 - np.clip(uvs[:, 1], 0.0, 1.0)) * (tex_size - 1)++ for tri in faces:+ p = uv_px[tri] # 3×(col,row)+ v3 = verts[tri] # 3×3 world+ min_c = int(np.floor(p[:, 0].min())); max_c = int(np.ceil(p[:, 0].max()))+ min_r = int(np.floor(p[:, 1].min())); max_r = int(np.ceil(p[:, 1].max()))+ min_c = max(0, min_c); min_r = max(0, min_r)+ max_c = min(tex_size - 1, max_c); max_r = min(tex_size - 1, max_r)+ if max_c < min_c or max_r < min_r:+ continue++ cols, rows = np.meshgrid(+ np.arange(min_c, max_c + 1), np.arange(min_r, max_r + 1)+ )+ cols = cols.ravel(); rows = rows.ravel()++ # Barycentric coords of each texel centre against the UV triangle.+ x1, y1 = p[0]; x2, y2 = p[1]; x3, y3 = p[2]+ det = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)+ if abs(det) < 1e-9:+ continue+ px = cols + 0.5; py = rows + 0.5+ a = ((y2 - y3) * (px - x3) + (x3 - x2) * (py - y3)) / det+ b = ((y3 - y1) * (px - x3) + (x1 - x3) * (py - y3)) / det+ c = 1.0 - a - b+ inside = (a >= -1e-4) & (b >= -1e-4) & (c >= -1e-4)+ if not inside.any():+ continue++ bary = np.stack([a[inside], b[inside], c[inside]], axis=1) # (k,3)+ pts3d = bary @ v3 # (k,3)+ sample_pts.append(pts3d)+ sample_px.append(np.stack([rows[inside], cols[inside]], axis=1))++ if not sample_pts:+ return uvs, None++ pts = np.concatenate(sample_pts, axis=0)+ px_idx = np.concatenate(sample_px, axis=0)++ closest, _dist, tri_ids = prox.on_surface(pts)+ closest_tris = src_tris[tri_ids] # (k,3,3)+ bary_src = trimesh.triangles.points_to_barycentric(closest_tris, closest)+ face_uv = src_uv[src_faces[tri_ids]] # (k,3,2)+ samp_uv = np.einsum("ij,ijk->ik", bary_src, face_uv) # (k,2)++ sx = np.clip(samp_uv[:, 0], 0.0, 1.0) * (sw - 1)+ sy = (1.0 - np.clip(samp_uv[:, 1], 0.0, 1.0)) * (sh - 1)+ colors = src_arr[np.rint(sy).astype(int), np.rint(sx).astype(int)]++ atlas[px_idx[:, 0], px_idx[:, 1]] = colors+ written[px_idx[:, 0], px_idx[:, 1]] = True+ atlas = _dilate(atlas, written)++ return uvs, Image.fromarray(atlas, mode="RGB")+++# ── Export ───────────────────────────────────────────────────────────────────++class Artifact:+ __slots__ = ("name", "data", "content_type", "role")++ def __init__(self, name: str, data: bytes, content_type: str, role: str):+ self.name = name+ self.data = data+ self.content_type = content_type+ self.role = role # "model" | "texture" | "material"+++def _build_textured_trimesh(verts, faces, uvs, image):+ import trimesh+ mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)+ if uvs is not None and image is not None:+ mesh.visual = trimesh.visual.TextureVisuals(+ uv=uvs, image=image, material=trimesh.visual.material.SimpleMaterial(image=image),+ )+ return mesh+++def _write_textured_quad_obj(verts, polys, uvs, image, task_id: str) -> list:+ """Write a true-quad OBJ that keeps quad faces and references a baked texture+ via a sibling .mtl + .png (relative names resolve from the same GCS prefix)."""+ import numpy as np+ mtl_name = f"{task_id}.mtl"+ png_name = f"{task_id}.png"++ lines = [f"mtllib {mtl_name}", "o remesh", "usemtl baked"]+ for x, y, z in verts:+ lines.append(f"v {x:.6f} {y:.6f} {z:.6f}")+ has_uv = uvs is not None and image is not None+ if has_uv:+ for u, v in uvs:+ lines.append(f"vt {u:.6f} {v:.6f}")+ for poly in polys:+ if has_uv:+ lines.append("f " + " ".join(f"{i + 1}/{i + 1}" for i in poly))+ else:+ lines.append("f " + " ".join(str(i + 1) for i in poly))+ obj_bytes = ("\n".join(lines) + "\n").encode("utf-8")++ artifacts = [Artifact(f"{task_id}.obj", obj_bytes, "model/obj", "model")]+ if has_uv:+ mtl = (+ "newmtl baked\nKa 1 1 1\nKd 1 1 1\nKs 0 0 0\n"+ f"map_Kd {png_name}\n"+ ).encode("utf-8")+ buf = io.BytesIO()+ image.save(buf, format="PNG")+ artifacts.append(Artifact(mtl_name, mtl, "text/plain", "material"))+ artifacts.append(Artifact(png_name, buf.getvalue(), "image/png", "texture"))+ return artifacts+++def _export_simple(mesh, output_format: str, task_id: str) -> list:+ """Export a Trimesh to a single self-contained file (GLB embeds textures)."""import trimeshfmt = output_format.lower()with tempfile.TemporaryDirectory() as tmpdir:- out_path = Path(tmpdir) / f"output.{fmt}"- if fmt == "glb":- scene = trimesh.scene.scene.Scene(geometry={"mesh": mesh})- scene.export(str(out_path))- elif fmt == "usdz":- scene = trimesh.scene.scene.Scene(geometry={"mesh": mesh})- scene.export(str(out_path))+ out_path = Path(tmpdir) / f"{task_id}.{fmt}"+ if fmt in ("glb", "usdz"):+ trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(out_path))else:mesh.export(str(out_path))data = out_path.read_bytes()- return data, f"model/{'gltf-binary' if fmt == 'glb' else 'octet-stream'}"+ ct = "model/gltf-binary" if fmt == "glb" else (+ "model/vnd.usdz+zip" if fmt == "usdz" else "application/octet-stream"+ )+ return [Artifact(f"{task_id}.{fmt}", data, ct, "model")]+++# ── Pipelines ────────────────────────────────────────────────────────────────++def _process_triangle(mesh, operation: str, target_faces: int):+ if operation in ("repair", "full"):+ mesh = _repair_mesh(mesh)+ if operation in ("simplify", "full") and len(mesh.faces) > target_faces:+ mesh = _decimate(mesh, target_faces)+ return mesh, {"quad_ratio": 0.0, "textured": False}+++def _process_quad(source, target_faces: int, output_format: str, tex_size: int, task_id: str):+ import trimesh+ src_uv, src_img = _source_texture(source)+ # QuadriFlow wants a clean watertight-ish triangle mesh as input.+ geom = source.copy()+ _repair_mesh(geom)+ verts, polys, quad_ratio = _quad_remesh(geom, target_faces)++ tri_mesh = _triangulate_polys(verts, polys)+ unwrap = _unwrap(tri_mesh)+ baked_uv = baked_img = None+ if unwrap is not None and src_uv is not None and src_img is not None:+ u_verts, u_faces, u_uv = unwrap+ baked_uv, baked_img = _bake_texture(+ source, src_uv, src_img, u_verts, u_faces, u_uv, tex_size,+ )+ tri_mesh = trimesh.Trimesh(vertices=u_verts, faces=u_faces, process=False)++ # OBJ output preserves the true quad faces (geometry only — the re-unwrapped+ # UVs live on the triangulated atlas, not the quads, so a textured atlas is+ # delivered via GLB). Every other format triangulates and carries the bake.+ if output_format == "obj":+ meta = {+ "quad_ratio": round(quad_ratio, 4),+ "textured": False,+ "face_count": len(polys),+ }+ return _write_textured_quad_obj(verts, polys, None, None, task_id), meta++ meta = {+ "quad_ratio": round(quad_ratio, 4),+ "textured": baked_img is not None,+ "face_count": len(polys),+ }+ mesh = _build_textured_trimesh(+ tri_mesh.vertices, tri_mesh.faces, baked_uv, baked_img,+ )+ return _export_simple(mesh, output_format, task_id), meta+++def _process_lowpoly(source, target_faces: int, output_format: str, tex_size: int, task_id: str):+ import trimesh+ src_uv, src_img = _source_texture(source)+ geom = source.copy()+ _repair_mesh(geom)+ low = _decimate(geom, target_faces)++ unwrap = _unwrap(low)+ baked_uv = baked_img = None+ if unwrap is not None and src_uv is not None and src_img is not None:+ u_verts, u_faces, u_uv = unwrap+ baked_uv, baked_img = _bake_texture(+ source, src_uv, src_img, u_verts, u_faces, u_uv, tex_size,+ )+ low = trimesh.Trimesh(vertices=u_verts, faces=u_faces, process=False)++ low.fix_normals()+ meta = {+ "quad_ratio": 0.0,+ "textured": baked_img is not None,+ "face_count": len(low.faces),+ }++ if output_format == "obj" and baked_img is not None:+ polys = [list(map(int, f)) for f in low.faces]+ return _write_textured_quad_obj(low.vertices, polys, baked_uv, baked_img, task_id), meta++ mesh = _build_textured_trimesh(low.vertices, low.faces, baked_uv, baked_img)+ return _export_simple(mesh, output_format, task_id), metadef _run_processing(mesh_url: str,+ remesh_mode: str,operation: str,target_faces: int,output_format: str,-) -> tuple[bytes, int, str]:+ texture_size: int,+ task_id: str,+) -> tuple[list, dict]:data, suffix = _fetch_mesh(mesh_url)- mesh = _load_mesh(data, suffix)- # Handle scene (multi-mesh) → combine into single mesh- import trimesh- if isinstance(mesh, trimesh.Scene):- meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]- if not meshes:- raise ValueError("no renderable geometry found in scene")- mesh = trimesh.util.concatenate(meshes)+ if remesh_mode == "quad":+ source = _load_textured(data, suffix)+ return _process_quad(source, target_faces, output_format, texture_size, task_id)- if operation in ("repair", "full"):- mesh = _repair_mesh(mesh)+ if remesh_mode == "lowpoly":+ source = _load_textured(data, suffix)+ return _process_lowpoly(source, target_faces, output_format, texture_size, task_id)- if operation in ("simplify", "full") and len(mesh.faces) > target_faces:- mesh = _simplify_mesh(mesh, target_faces)+ # triangle (default) — legacy behaviour, geometry only.+ mesh = _load_concatenated(data, suffix)+ mesh, meta = _process_triangle(mesh, operation, target_faces)+ meta["face_count"] = len(mesh.faces)+ return _export_simple(mesh, output_format, task_id), meta- out_bytes, content_type = _export_mesh(mesh, output_format, "")- return out_bytes, len(mesh.faces), content_type+# ── Task orchestration ───────────────────────────────────────────────────────async def _process(task_id: str,mesh_url: str,+ remesh_mode: str,operation: str,target_faces: int,output_format: str,+ texture_size: int,) -> None:async with _sem:_tasks[task_id]["status"] = "running"loop = asyncio.get_event_loop()t0 = time.time()try:- out_bytes, face_count, content_type = await loop.run_in_executor(+ artifacts, meta = await loop.run_in_executor(None,_run_processing,mesh_url,+ remesh_mode,operation,target_faces,output_format,+ texture_size,+ task_id,)- blob_name = f"remesh/{task_id}.{output_format}"- blob = _bucket.blob(blob_name)- await loop.run_in_executor(- None,- lambda: blob.upload_from_string(out_bytes, content_type=content_type),- )- result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"-+ urls: dict[str, str] = {}+ for art in artifacts:+ blob = _bucket.blob(f"remesh/{art.name}")+ await loop.run_in_executor(+ None,+ lambda b=blob, a=art: b.upload_from_string(a.data, content_type=a.content_type),+ )+ url = f"https://storage.googleapis.com/{GCS_BUCKET}/remesh/{art.name}"+ urls[art.role] = url++ total_bytes = sum(len(a.data) for a in artifacts)elapsed = time.time() - t0_tasks[task_id].update({"status": "done",- "result_url": result_url,- "face_count": face_count,+ "result_url": urls.get("model"),+ "texture_url": urls.get("texture"),+ "mtl_url": urls.get("material"),+ "face_count": meta.get("face_count"),+ "quad_ratio": meta.get("quad_ratio"),+ "textured": meta.get("textured"),+ "mode": remesh_mode,"output_format": output_format,- "bytes": len(out_bytes),+ "bytes": total_bytes,"elapsed_ms": int(elapsed * 1000),})log.info(- "[%s] done in %.2fs — %d faces, %d bytes → %s",- task_id, elapsed, face_count, len(out_bytes), result_url,+ "[%s] done in %.2fs — mode=%s, %s faces, quad_ratio=%s, textured=%s → %s",+ task_id, elapsed, remesh_mode, meta.get("face_count"),+ meta.get("quad_ratio"), meta.get("textured"), urls.get("model"),)except Exception as exc:@@ -259,8 +699,10 @@ async def _process(class ProcessRequest(BaseModel):mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ remesh_mode: str = Field(default="triangle", description="triangle|quad|lowpoly")operation: str = Field(default="full", description="convert|simplify|repair|full")target_faces: int = Field(default=50_000, ge=1_000, le=500_000)+ texture_size: int = Field(default=1024)output_format: str = Field(default="glb")@field_validator("output_format")@@ -279,6 +721,21 @@ class ProcessRequest(BaseModel):raise ValueError(f"operation must be one of {sorted(allowed)}")return v+ @field_validator("remesh_mode")+ @classmethod+ def validate_mode(cls, v: str) -> str:+ v = (v or "triangle").lower()+ if v not in VALID_MODES:+ raise ValueError(f"remesh_mode must be one of {sorted(VALID_MODES)}")+ return v++ @field_validator("texture_size")+ @classmethod+ def validate_texture_size(cls, v: int) -> int:+ if v not in VALID_TEXTURE_SIZES:+ raise ValueError(f"texture_size must be one of {sorted(VALID_TEXTURE_SIZES)}")+ return v+@app.post("/process", status_code=202)async def process_mesh(@@ -291,6 +748,7 @@ async def process_mesh(_tasks[task_id] = {"task_id": task_id,"status": "queued",+ "mode": body.remesh_mode,"operation": body.operation,"output_format": body.output_format,}@@ -298,11 +756,13 @@ async def process_mesh(_process,task_id,body.mesh,+ body.remesh_mode,body.operation,body.target_faces,body.output_format,+ body.texture_size,)- return {"task_id": task_id, "status": "queued"}+ return {"task_id": task_id, "status": "queued", "mode": body.remesh_mode}@app.get("/tasks/{task_id}")diff --git a/workers/remesh/requirements.txt b/workers/remesh/requirements.txtindex 54411b64e..45ef22907 100644--- a/workers/remesh/requirements.txt+++ b/workers/remesh/requirements.txt@@ -3,6 +3,10 @@ uvicorn[standard]==0.32.1trimesh[easy]==4.5.3open3d==0.18.0numpy==1.26.4+# Quad/low-poly UV atlas generation (re-unwrap before texture re-bake). MIT.+xatlas==0.0.9+# Texture atlas read/write for the re-bake step.+Pillow==11.0.0google-cloud-storage==2.19.0httpx==0.27.2pydantic==2.10.3diff --git a/workers/segment/Dockerfile b/workers/segment/Dockerfilenew file mode 100644index 000000000..7f544cd9e--- /dev/null+++ b/workers/segment/Dockerfile@@ -0,0 +1,22 @@+FROM python:3.11-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ libgl1 libglib2.0-0 libgomp1 \+ libassimp-dev libassimp5 \+ libopenblas-dev \+ && rm -rf /var/lib/apt/lists/*++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY segment_core.py /app/segment_core.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/segment/__pycache__/main.cpython-312.pyc b/workers/segment/__pycache__/main.cpython-312.pycnew file mode 100644index 000000000..6ffab0c11Binary files /dev/null and b/workers/segment/__pycache__/main.cpython-312.pyc differdiff --git a/workers/segment/__pycache__/segment_core.cpython-312.pyc b/workers/segment/__pycache__/segment_core.cpython-312.pycnew file mode 100644index 000000000..8cbad8160Binary files /dev/null and b/workers/segment/__pycache__/segment_core.cpython-312.pyc differdiff --git a/workers/segment/__pycache__/worker_security.cpython-312.pyc b/workers/segment/__pycache__/worker_security.cpython-312.pycnew file mode 100644index 000000000..6b8be2088Binary files /dev/null and b/workers/segment/__pycache__/worker_security.cpython-312.pyc differdiff --git a/workers/segment/cloudbuild.yaml b/workers/segment/cloudbuild.yamlnew file mode 100644index 000000000..7320253b5--- /dev/null+++ b/workers/segment/cloudbuild.yaml@@ -0,0 +1,59 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: segment-service+ _REPO: segment-service+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "3"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/segment+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --no-gpu+ - --cpu=8+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=300+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MAX_CONCURRENT=2+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/segment/main.py b/workers/segment/main.pynew file mode 100644index 000000000..9a7b960e1--- /dev/null+++ b/workers/segment/main.py@@ -0,0 +1,289 @@+"""+Part-segmentation service — split a 3D model into addressable, named parts.++Wraps trimesh + a geometry-based segmenter (see segment_core.py). No GPU+required; runs on CPU like the remesh worker. It:+ - splits a mesh at its physically disconnected shells (wheels, eyes, props),+ - applies the minima rule inside each shell (cut at concave creases) to find+ natural part seams (limb↔torso, handle↔body, …),+ - merges shards and caps the part count to a meaningful handful,+ - tints each part a distinct colour, and+ - emits a GLB whose nodes are the parts (node name = part id) plus a parts+ manifest (id, name, region, bbox, centroid, face/vertex counts, colour).++Optionally exports a single part on its own (`only_part`).++API contract:+ POST /segment {+ mesh: url, # https GLB/OBJ/STL/PLY/FBX URL (required)+ method?: "auto"|"connected"|"crease", # default: "auto"+ max_parts?: int, # default: 24, range 2–64+ min_part_faces?: int, # default: 64, range 4–100000+ crease_angle?: float, # default: 40 (degrees), range 5–170+ only_part?: str, # export just this part id/name (e.g. "part_03")+ } → 202 { task_id, status }++ GET /tasks/:id → {+ task_id, status,+ result_url?, manifest_url?,+ parts?, part_count?, source_faces?, method?,+ error?+ }++ GET /health → { ok }++Environment variables:+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)+ MAX_CONCURRENT — default 2+"""++from __future__ import annotations++import asyncio+import json+import logging+import os+import time+import uuid+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Optional++from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from pydantic import BaseModel, Field, field_validator++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("segment")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))++_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}++SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}+VALID_METHODS = {"auto", "connected", "crease"}+MAX_MESH_BYTES = 128 * 1024 * 1024+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ import trimesh+ log.info("segment service ready — trimesh %s", trimesh.__version__)+ yield+++app = FastAPI(title="segment-service", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++def _fetch_mesh(url: str) -> tuple[bytes, str]:+ try:+ data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch mesh: {exc}") from exc+ suffix = Path(url.split("?")[0]).suffix.lower()+ if suffix not in SUPPORTED_INPUT_FORMATS:+ suffix = ".glb"+ return data, suffix+++def _run_segmentation(+ mesh_url: str,+ method: str,+ max_parts: int,+ min_part_faces: int,+ crease_angle: float,+ only_part: Optional[str],+) -> tuple[bytes, dict]:+ """Fetch, segment, and return (glb_bytes, manifest). Runs in a thread."""+ import segment_core as seg++ data, suffix = _fetch_mesh(mesh_url)+ mesh = seg.load_concatenated(data, suffix)+ result = seg.segment(+ mesh,+ method=method,+ max_parts=max_parts,+ min_part_faces=min_part_faces,+ crease_angle_deg=crease_angle,+ )++ parts = result.parts+ if only_part:+ wanted = only_part.strip().lower()+ match = next(+ (+ p+ for p in parts+ if f"part_{p.index:02d}" == wanted or p.name.lower() == wanted+ ),+ None,+ )+ if match is None:+ available = ", ".join(f"part_{p.index:02d} ({p.name})" for p in parts)+ raise ValueError(f"part '{only_part}' not found. Available: {available}")+ parts = [match]++ scene = seg.build_scene(parts)+ glb_bytes = scene.export(file_type="glb")++ manifest = seg.manifest(result)+ if only_part:+ manifest["parts"] = [p.manifest() for p in parts]+ manifest["part_count"] = len(parts)+ manifest["only_part"] = f"part_{parts[0].index:02d}"++ return glb_bytes, manifest+++async def _process(+ task_id: str,+ mesh_url: str,+ method: str,+ max_parts: int,+ min_part_faces: int,+ crease_angle: float,+ only_part: Optional[str],+) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ glb_bytes, manifest = await loop.run_in_executor(+ None,+ _run_segmentation,+ mesh_url,+ method,+ max_parts,+ min_part_faces,+ crease_angle,+ only_part,+ )++ glb_name = f"segment/{task_id}.glb"+ manifest_name = f"segment/{task_id}.parts.json"++ glb_blob = _bucket.blob(glb_name)+ manifest_blob = _bucket.blob(manifest_name)+ await loop.run_in_executor(+ None,+ lambda: glb_blob.upload_from_string(+ glb_bytes, content_type="model/gltf-binary"+ ),+ )+ await loop.run_in_executor(+ None,+ lambda: manifest_blob.upload_from_string(+ json.dumps(manifest), content_type="application/json"+ ),+ )++ result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{glb_name}"+ manifest_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{manifest_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_url": result_url,+ "manifest_url": manifest_url,+ "parts": manifest["parts"],+ "part_count": manifest["part_count"],+ "source_faces": manifest["source_faces"],+ "method": manifest["method"],+ "warnings": manifest.get("warnings", []),+ "bytes": len(glb_bytes),+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info(+ "[%s] done in %.2fs — %d parts, %d bytes → %s",+ task_id, elapsed, manifest["part_count"], len(glb_bytes), result_url,+ )++ except Exception as exc:+ _tasks[task_id].update({+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] segment"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+++class SegmentRequest(BaseModel):+ mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ method: str = Field(default="auto", description="auto|connected|crease")+ max_parts: int = Field(default=24, ge=2, le=64)+ min_part_faces: int = Field(default=64, ge=4, le=100_000)+ crease_angle: float = Field(default=40.0, ge=5.0, le=170.0)+ only_part: Optional[str] = Field(default=None, max_length=64)++ @field_validator("method")+ @classmethod+ def validate_method(cls, v: str) -> str:+ v = v.lower().strip()+ if v not in VALID_METHODS:+ raise ValueError(f"method must be one of {sorted(VALID_METHODS)}")+ return v++[email protected]("/segment", status_code=202)+async def segment_mesh(+ body: SegmentRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "method": body.method,+ }+ background_tasks.add_task(+ _process,+ task_id,+ body.mesh,+ body.method,+ body.max_parts,+ body.min_part_faces,+ body.crease_angle,+ body.only_part,+ )+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {"ok": True, "service": "segment"}diff --git a/workers/segment/requirements.txt b/workers/segment/requirements.txtnew file mode 100644index 000000000..3bd704160--- /dev/null+++ b/workers/segment/requirements.txt@@ -0,0 +1,8 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+trimesh[easy]==4.5.3+numpy==1.26.4+scipy==1.14.1+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3diff --git a/workers/segment/segment_core.py b/workers/segment/segment_core.pynew file mode 100644index 000000000..d3a9714d8--- /dev/null+++ b/workers/segment/segment_core.py@@ -0,0 +1,404 @@+"""+Geometry-based part segmentation for triangle meshes.++Why geometry, not a learned model+---------------------------------+A learned 3D part-segmentation network (e.g. PartField / SAM-3D via a GPU+worker) can attach human labels ("head", "arm") but it brings a hard GPU+dependency, non-determinism, and an external-availability risk — and it still+fails on the long tail of stylised, low-poly, or non-organic meshes the forge+pipeline produces. Convex decomposition (CoACD/VHACD) over-fragments organic+shapes into dozens of convex shards that are not the parts a human would name.++We instead segment on the geometry the mesh already carries, which is fast,+deterministic, GPU-free (consistent with the CPU remesh worker), and works on+any topology:++ 1. Connected components first. Anything physically disjoint — wheels, eyes,+ a weapon, loose accessories — separates immediately and perfectly.++ 2. The minima rule within each connected component. Human shape perception+ segments objects at concave creases (Hoffman & Richards, 1984). We cut the+ face-adjacency graph along strong concave edges, then take the connected+ components of what remains. This finds the natural seam between a limb and+ a torso, a handle and a body, a wheel-arch and a fender.++ 3. Cleanup. Tiny shards are merged back into their largest neighbour, and the+ part count is capped by repeatedly merging the smallest part into its+ largest neighbour — so the output is a handful of meaningful parts, not a+ thousand crease fragments.++Parts are named by their spatial region (top / lower-left / core …) so the+labels read meaningfully in the viewer, and each part is tinted a distinct hue+so segmentation is visible even on an untextured mesh.+"""++from __future__ import annotations++import colorsys+import math+from dataclasses import dataclass, field+from typing import Optional++import numpy as np+import trimesh+from scipy.sparse import coo_matrix+from scipy.sparse.csgraph import connected_components++# A perceptually spread palette — distinct adjacent hues, golden-ratio stepped+# so even 20+ parts stay visually separable.+_GOLDEN = 0.61803398875+++def _palette(n: int) -> list[tuple[int, int, int]]:+ colors = []+ h = 0.08+ for _ in range(max(n, 1)):+ r, g, b = colorsys.hsv_to_rgb(h % 1.0, 0.62, 0.95)+ colors.append((int(r * 255), int(g * 255), int(b * 255)))+ h += _GOLDEN+ return colors+++@dataclass+class Part:+ index: int+ name: str+ mesh: "trimesh.Trimesh"+ color: tuple[int, int, int]+ region: str++ def manifest(self) -> dict:+ b = self.mesh.bounds # (2,3) min,max+ centroid = self.mesh.centroid+ return {+ "id": f"part_{self.index:02d}",+ "name": self.name,+ "region": self.region,+ "face_count": int(len(self.mesh.faces)),+ "vertex_count": int(len(self.mesh.vertices)),+ "bbox": {+ "min": [float(x) for x in b[0]],+ "max": [float(x) for x in b[1]],+ },+ "centroid": [float(x) for x in centroid],+ "volume": float(abs(self.mesh.volume)) if self.mesh.is_volume else 0.0,+ "color": "#%02x%02x%02x" % self.color,+ }+++@dataclass+class SegmentationResult:+ parts: list[Part]+ source_faces: int+ method: str+ warnings: list[str] = field(default_factory=list)+++# ── mesh loading / normalisation ──────────────────────────────────────────────+++def load_concatenated(data: bytes, suffix: str) -> "trimesh.Trimesh":+ """Load a mesh or scene and return a single Trimesh.++ A glTF scene's own node split is *not* a reliable part split — exporters+ routinely emit a whole character as one node, or shatter it into per-material+ nodes. We concatenate to a single mesh and re-derive parts from geometry so+ the result is consistent regardless of how the source was authored.+ """+ import io++ loaded = trimesh.load(+ io.BytesIO(data),+ file_type=suffix.lstrip("."),+ force="mesh",+ process=True,+ )+ if isinstance(loaded, trimesh.Scene):+ meshes = [g for g in loaded.geometry.values() if isinstance(g, trimesh.Trimesh)]+ if not meshes:+ raise ValueError("no triangle geometry found in the model")+ mesh = trimesh.util.concatenate(meshes)+ else:+ mesh = loaded+ if mesh.faces is None or len(mesh.faces) == 0:+ raise ValueError("mesh has no faces to segment")+ mesh.merge_vertices()+ return mesh+++# ── core segmentation ─────────────────────────────────────────────────────────+++def _crease_labels(mesh: "trimesh.Trimesh", crease_angle_rad: float) -> np.ndarray:+ """Label faces by minima-rule region growing.++ Faces stay connected across an edge unless that edge is concave and its+ dihedral angle exceeds the threshold; the connected components of the+ surviving graph are the regions.+ """+ n_faces = len(mesh.faces)+ adjacency = mesh.face_adjacency # (E, 2)+ if len(adjacency) == 0:+ return np.zeros(n_faces, dtype=np.int64)++ angles = mesh.face_adjacency_angles # (E,) radians, unsigned+ convex = mesh.face_adjacency_convex # (E,) bool, True where the edge bulges out++ # The minima rule: cut only at *concave* creases sharper than the threshold.+ cut = (~convex) & (angles > crease_angle_rad)+ keep = adjacency[~cut]++ if len(keep) == 0:+ # Every interior edge is a sharp concave crease — nothing to grow.+ return np.arange(n_faces, dtype=np.int64)++ rows = np.concatenate([keep[:, 0], keep[:, 1]])+ cols = np.concatenate([keep[:, 1], keep[:, 0]])+ data = np.ones(len(rows), dtype=np.uint8)+ graph = coo_matrix((data, (rows, cols)), shape=(n_faces, n_faces))+ _, labels = connected_components(graph, directed=False)+ return labels+++def _label_adjacency(mesh: "trimesh.Trimesh", labels: np.ndarray) -> dict[int, set[int]]:+ """Which labels touch which, via the full face-adjacency graph."""+ neighbours: dict[int, set[int]] = {}+ fa = mesh.face_adjacency+ if len(fa) == 0:+ return neighbours+ la = labels[fa[:, 0]]+ lb = labels[fa[:, 1]]+ diff = la != lb+ for a, b in zip(la[diff], lb[diff]):+ neighbours.setdefault(int(a), set()).add(int(b))+ neighbours.setdefault(int(b), set()).add(int(a))+ return neighbours+++def _merge_small_and_cap(+ mesh: "trimesh.Trimesh",+ labels: np.ndarray,+ min_part_faces: int,+ max_parts: int,+) -> np.ndarray:+ """Merge sub-threshold parts into their largest neighbour, then cap count.++ Both passes reassign labels in place and recompute neighbours afterwards so+ the adjacency stays correct as parts coalesce.+ """+ labels = labels.copy()++ def sizes() -> dict[int, int]:+ uniq, counts = np.unique(labels, return_counts=True)+ return {int(u): int(c) for u, c in zip(uniq, counts)}++ def largest_neighbour(label: int, neigh: dict[int, set[int]], sz: dict[int, int]) -> Optional[int]:+ cands = neigh.get(label, set())+ if not cands:+ return None+ return max(cands, key=lambda c: sz.get(c, 0))++ # Pass 1 — dissolve shards below the face floor.+ while True:+ sz = sizes()+ if len(sz) <= 1:+ break+ small = [lbl for lbl, c in sz.items() if c < min_part_faces]+ if not small:+ break+ neigh = _label_adjacency(mesh, labels)+ # Smallest first, so a chain of shards collapses outward.+ small.sort(key=lambda l: sz[l])+ merged_any = False+ for lbl in small:+ target = largest_neighbour(lbl, neigh, sz)+ if target is None or target == lbl:+ continue+ labels[labels == lbl] = target+ merged_any = True+ break # recompute sizes/adjacency after each merge+ if not merged_any:+ break++ # Pass 2 — cap the part count by merging the smallest into its largest neighbour.+ while True:+ sz = sizes()+ if len(sz) <= max_parts:+ break+ neigh = _label_adjacency(mesh, labels)+ smallest = min(sz, key=lambda l: sz[l])+ target = largest_neighbour(smallest, neigh, sz)+ if target is None:+ # Disconnected leftover with no neighbour to merge into — keep the+ # largest `max_parts` and fold the rest into the overall biggest.+ ordered = sorted(sz, key=lambda l: sz[l], reverse=True)+ keep_set = set(ordered[: max_parts - 1])+ biggest = ordered[0]+ for lbl in ordered[max_parts - 1:]:+ if lbl not in keep_set:+ labels[labels == lbl] = biggest+ break+ labels[labels == smallest] = target++ return labels+++def _region_name(centroid: np.ndarray, bounds: np.ndarray) -> str:+ """A human-readable spatial label from a part centroid within the bbox.++ Y is up (glTF convention). Vertical band dominates the name (top/lower/…);+ a left/right/front/back qualifier is added when the part sits clearly off+ the central axis.+ """+ span = bounds[1] - bounds[0]+ span[span == 0] = 1.0+ rel = (centroid - bounds[0]) / span # 0..1 per axis++ y = rel[1]+ if y >= 0.78:+ vert = "top"+ elif y >= 0.58:+ vert = "upper"+ elif y >= 0.42:+ vert = "mid"+ elif y >= 0.22:+ vert = "lower"+ else:+ vert = "bottom"++ quals = []+ x = rel[0]+ if x <= 0.34:+ quals.append("left")+ elif x >= 0.66:+ quals.append("right")+ z = rel[2]+ if z <= 0.30:+ quals.append("back")+ elif z >= 0.70:+ quals.append("front")++ return "-".join([vert, *quals]) if quals else ("core" if vert == "mid" else vert)+++def _unique_names(regions: list[str]) -> list[str]:+ seen: dict[str, int] = {}+ out = []+ counts = {r: regions.count(r) for r in regions}+ for r in regions:+ if counts[r] == 1:+ out.append(r)+ else:+ seen[r] = seen.get(r, 0) + 1+ out.append(f"{r}-{seen[r]}")+ return out+++def segment(+ mesh: "trimesh.Trimesh",+ *,+ method: str = "auto",+ max_parts: int = 24,+ min_part_faces: int = 64,+ crease_angle_deg: float = 40.0,+) -> SegmentationResult:+ """Split `mesh` into named parts.++ method:+ - "connected": split only at physically disconnected shells.+ - "crease": minima-rule crease segmentation over the whole mesh.+ - "auto": connected components, then crease-split any component large+ enough to plausibly contain multiple parts. Best default.+ """+ source_faces = int(len(mesh.faces))+ warnings: list[str] = []+ crease_rad = math.radians(max(5.0, min(170.0, crease_angle_deg)))++ # Step 1 — connected components are always honoured; they are unambiguous parts.+ components = mesh.split(only_watertight=False)+ if len(components) == 0:+ components = [mesh]++ region_meshes: list["trimesh.Trimesh"] = []++ for comp in components:+ if method == "connected":+ region_meshes.append(comp)+ continue++ # crease / auto: grow regions inside this component.+ # In auto mode, skip the (expensive, pointless) crease pass on tiny+ # components that are obviously a single part already.+ if method == "auto" and len(comp.faces) < max(min_part_faces * 2, 200):+ region_meshes.append(comp)+ continue++ labels = _crease_labels(comp, crease_rad)+ labels = _merge_small_and_cap(comp, labels, min_part_faces, max_parts)+ for lbl in np.unique(labels):+ face_idx = np.where(labels == lbl)[0]+ sub = comp.submesh([face_idx], append=True, repair=False)+ if isinstance(sub, list):+ sub = sub[0] if sub else None+ if sub is not None and len(sub.faces) > 0:+ region_meshes.append(sub)++ # Global cap across all components combined.+ if len(region_meshes) > max_parts:+ region_meshes.sort(key=lambda m: len(m.faces), reverse=True)+ head = region_meshes[: max_parts - 1]+ tail = region_meshes[max_parts - 1:]+ merged = trimesh.util.concatenate(tail)+ region_meshes = head + [merged]+ warnings.append(+ f"capped to {max_parts} parts; {len(tail)} smaller fragments were combined"+ )++ if not region_meshes:+ region_meshes = [mesh]++ # Order parts top→bottom, then larger→smaller, so the list reads naturally.+ overall_bounds = mesh.bounds++ def sort_key(m: "trimesh.Trimesh"):+ return (-(m.centroid[1]), -len(m.faces))++ region_meshes.sort(key=sort_key)++ regions = [_region_name(m.centroid, overall_bounds) for m in region_meshes]+ names = _unique_names(regions)+ colors = _palette(len(region_meshes))++ parts: list[Part] = []+ for i, (m, name, region, color) in enumerate(zip(region_meshes, names, regions, colors)):+ # Tint each part so segmentation is visible without textures, and so a+ # downstream viewer/exporter has a stable per-part colour to fall back on.+ m.visual = trimesh.visual.ColorVisuals(+ mesh=m, face_colors=np.tile([*color, 255], (len(m.faces), 1))+ )+ parts.append(Part(index=i + 1, name=name, mesh=m, color=color, region=region))++ return SegmentationResult(+ parts=parts, source_faces=source_faces, method=method, warnings=warnings+ )+++def build_scene(parts: list[Part]) -> "trimesh.Scene":+ """A scene whose node names are the part ids — so a GLB consumer can address,+ hide, recolour or export each part by name."""+ scene = trimesh.Scene()+ for p in parts:+ node_name = f"part_{p.index:02d}"+ scene.add_geometry(p.mesh, geom_name=node_name, node_name=node_name)+ return scene+++def manifest(result: SegmentationResult) -> dict:+ return {+ "method": result.method,+ "source_faces": result.source_faces,+ "part_count": len(result.parts),+ "parts": [p.manifest() for p in result.parts],+ "warnings": result.warnings,+ }diff --git a/workers/segment/worker_security.py b/workers/segment/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/segment/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/stylize/Dockerfile b/workers/stylize/Dockerfilenew file mode 100644index 000000000..a15fc2bb2--- /dev/null+++ b/workers/stylize/Dockerfile@@ -0,0 +1,21 @@+FROM python:3.11-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ libgl1 libglib2.0-0 libgomp1 \+ libassimp-dev libassimp5 \+ libopenblas-dev \+ && rm -rf /var/lib/apt/lists/*++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/stylize/__pycache__/main.cpython-312.pyc b/workers/stylize/__pycache__/main.cpython-312.pycnew file mode 100644index 000000000..4e7a54e49Binary files /dev/null and b/workers/stylize/__pycache__/main.cpython-312.pyc differdiff --git a/workers/stylize/__pycache__/worker_security.cpython-312.pyc b/workers/stylize/__pycache__/worker_security.cpython-312.pycnew file mode 100644index 000000000..e635c5f4aBinary files /dev/null and b/workers/stylize/__pycache__/worker_security.cpython-312.pyc differdiff --git a/workers/stylize/cloudbuild.yaml b/workers/stylize/cloudbuild.yamlnew file mode 100644index 000000000..b9fd5308f--- /dev/null+++ b/workers/stylize/cloudbuild.yaml@@ -0,0 +1,59 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: stylize-service+ _REPO: stylize-service+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "3"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/stylize+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --no-gpu+ - --cpu=8+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=300+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MAX_CONCURRENT=2+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/stylize/main.py b/workers/stylize/main.pynew file mode 100644index 000000000..e7dcc35b6--- /dev/null+++ b/workers/stylize/main.py@@ -0,0 +1,547 @@+"""+Stylize service — one-click geometric stylization filters for 3D meshes.++Turns any input mesh into a stylized variant using pure geometry processing+(trimesh + numpy + scipy). No model inference, no GPU — fast and cheap on CPU.++Filters (extensible — register more in STYLES):+ - voxel : voxelize to a grid, rebuild the surface as solid cubes.+ - brick : voxel grid + cylindrical studs on every top face (LEGO-like).+ - voronoi : decimate to a coarse shell, thicken its edges into an open+ strut lattice with spherical nodes (Voronoi/wireframe shell).+ - lowpoly : quadric-decimate, then hard flat-shade for a faceted look.++Source color/material is preserved where the style allows by sampling the+nearest source-surface face color per output element; otherwise a tasteful+default material is applied.++API contract:+ POST /process {+ mesh: url, # https GLB/OBJ/FBX/STL/PLY URL (required)+ style: "voxel"|"brick"|"voronoi"|"lowpoly", # default: "voxel"+ resolution?: int, # style-specific density (see /styles)+ output_format?: "glb"|"obj"|"stl"|"ply", # default: "glb"+ } → 202 { task_id, status }++ GET /tasks/:id → { task_id, status, result_url?, face_count?, style?, error? }++ GET /styles → { styles: [ { key, name, description, resolution: {...} } ] }++ GET /health → { ok }++Environment variables:+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)+ MAX_CONCURRENT — default 2+"""++from __future__ import annotations++import asyncio+import io+import logging+import os+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Callable, Optional++from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from pydantic import BaseModel, Field, field_validator++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("stylize")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))++_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}++SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}+SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply"}+MAX_MESH_BYTES = 128 * 1024 * 1024++# Hard safety caps so a hostile/huge input can never exhaust memory.+MAX_VOXELS = 60_000 # occupied surface cells rebuilt as cubes+MAX_LATTICE_EDGES = 6_000 # struts emitted for the voronoi shell+DEFAULT_COLOR = [196, 198, 214, 255] # tasteful cool-neutral when source has none+++# ── style catalog ────────────────────────────────────────────────────────────────+# A single source of truth for the available filters: their human-facing copy and+# the bounds + default of their one density knob. Adding a new filter is a matter+# of describing it here and registering its transform in STYLES below.++STYLE_CATALOG = {+ "voxel": {+ "name": "Voxel",+ "description": "Blocky cubes snapped to a 3D grid — a clean Minecraft-style rebuild of the surface.",+ "resolution": {"label": "Grid resolution", "default": 32, "min": 8, "max": 96},+ },+ "brick": {+ "name": "Brick",+ "description": "Voxel grid topped with studs on every up-facing block — a buildable, toy-brick look.",+ "resolution": {"label": "Brick resolution", "default": 24, "min": 8, "max": 64},+ },+ "voronoi": {+ "name": "Voronoi shell",+ "description": "An open lattice of struts and nodes traced over the surface — light, sculptural, 3D-print ready.",+ "resolution": {"label": "Cell density", "default": 48, "min": 12, "max": 120},+ },+ "lowpoly": {+ "name": "Low-poly",+ "description": "Decimated to crisp facets with hard flat shading — the classic stylized game-asset aesthetic.",+ "resolution": {"label": "Detail", "default": 40, "min": 8, "max": 120},+ },+}+++def _clamp_resolution(style: str, resolution: Optional[int]) -> int:+ spec = STYLE_CATALOG[style]["resolution"]+ if resolution is None:+ return spec["default"]+ return max(spec["min"], min(spec["max"], int(resolution)))+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ import trimesh+ log.info("stylize service ready — trimesh %s, styles=%s", trimesh.__version__, ",".join(STYLE_CATALOG))+ yield+++app = FastAPI(title="stylize-service", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++# ── mesh IO ───────────────────────────────────────────────────────────────────────+++def _fetch_mesh(url: str) -> tuple[bytes, str]:+ try:+ data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch mesh: {exc}") from exc+ suffix = Path(url.split("?")[0]).suffix.lower()+ if suffix not in SUPPORTED_INPUT_FORMATS:+ suffix = ".glb"+ return data, suffix+++def _load_single_mesh(data: bytes, suffix: str):+ """Load to a single concatenated Trimesh, keeping visual/color where present."""+ import trimesh++ loaded = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=False)+ if isinstance(loaded, trimesh.Scene):+ meshes = [g for g in loaded.geometry.values() if isinstance(g, trimesh.Trimesh)]+ if not meshes:+ raise ValueError("no renderable geometry found in scene")+ loaded = trimesh.util.concatenate(meshes)+ if not hasattr(loaded, "faces") or len(loaded.faces) == 0:+ raise ValueError("input has no triangular faces to stylize")+ return loaded+++# ── color preservation ─────────────────────────────────────────────────────────────+++def _source_color_sampler(mesh) -> Callable:+ """Return color_at(points)->(N,4) uint8 sampling the nearest source face color.++ Resolves a usable per-face color from whatever the source carries — vertex+ colors, a texture (converted via to_color), or a material base color —+ falling back to a tasteful default when the mesh is untextured. The returned+ closure is what each filter calls to tint its output elements.+ """+ import numpy as np+ from scipy.spatial import cKDTree++ n_faces = len(mesh.faces)+ face_colors = None+ try:+ visual = getattr(mesh, "visual", None)+ if visual is not None:+ kind = getattr(visual, "kind", None)+ if kind == "texture" or visual.__class__.__name__ == "TextureVisuals":+ visual = visual.to_color()+ fc = getattr(visual, "face_colors", None)+ if fc is not None and len(fc) == n_faces:+ face_colors = np.asarray(fc, dtype=np.uint8).reshape(-1, 4)+ except Exception as exc: # noqa: BLE001 — any visual quirk falls back to default+ log.info("color extraction fell back to default: %s", exc)++ if face_colors is None:+ face_colors = np.tile(np.array(DEFAULT_COLOR, dtype=np.uint8), (n_faces, 1))++ centroids = mesh.triangles_center+ tree = cKDTree(centroids)++ def color_at(points):+ pts = np.asarray(points, dtype=np.float64).reshape(-1, 3)+ _, idx = tree.query(pts)+ return face_colors[idx]++ return color_at+++# ── filters ─────────────────────────────────────────────────────────────────────+++def _stylize_voxel(mesh, resolution: int):+ """Voxelize the surface and rebuild it as a mesh of solid, source-colored cubes."""+ import numpy as np++ extent = float(mesh.extents.max())+ if extent <= 0:+ raise ValueError("mesh has zero extent")+ pitch = extent / max(1, resolution)++ voxel = mesh.voxelized(pitch=pitch)+ n = len(voxel.points)+ if n == 0:+ raise ValueError("voxelization produced no cells — try a higher resolution")+ # Back off resolution if the grid is dangerously dense.+ while n > MAX_VOXELS and pitch < extent:+ pitch *= 1.3+ voxel = mesh.voxelized(pitch=pitch)+ n = len(voxel.points)++ color_at = _source_color_sampler(mesh)+ colors = color_at(voxel.points) # (N,4), one per occupied cell+ boxes = voxel.as_boxes()+ # as_boxes emits exactly 12 faces per cell in `points` order; tint each cube+ # by repeating its source color across its faces. (Passing colors= directly+ # is silently dropped by this trimesh version.)+ per_face = len(boxes.faces) // len(voxel.points)+ boxes.visual.face_colors = np.repeat(colors, per_face, axis=0)+ return boxes+++def _stylize_brick(mesh, resolution: int):+ """Voxel grid plus a stud on each column's top voxel — a toy-brick rebuild."""+ import numpy as np+ import trimesh++ extent = float(mesh.extents.max())+ if extent <= 0:+ raise ValueError("mesh has zero extent")+ pitch = extent / max(1, resolution)++ voxel = mesh.voxelized(pitch=pitch)+ n = len(voxel.points)+ if n == 0:+ raise ValueError("voxelization produced no cells — try a higher resolution")+ while n > MAX_VOXELS and pitch < extent:+ pitch *= 1.3+ voxel = mesh.voxelized(pitch=pitch)+ n = len(voxel.points)++ color_at = _source_color_sampler(mesh)+ centers = np.asarray(voxel.points, dtype=np.float64)+ colors = color_at(centers)++ base = voxel.as_boxes()+ per_face = len(base.faces) // len(centers)+ base.visual.face_colors = np.repeat(colors, per_face, axis=0)++ # Find the top voxel of each (x,y) column (grid up-axis = Z) and cap it with a+ # cylindrical stud sitting on the block's top face.+ grid = np.asarray(voxel.sparse_indices, dtype=np.int64) # (N,3) integer cells+ column_top: dict[tuple, int] = {}+ for i in range(len(grid)):+ key = (int(grid[i, 0]), int(grid[i, 1]))+ if key not in column_top or grid[i, 2] > grid[column_top[key], 2]:+ column_top[key] = i++ stud_r = pitch * 0.30+ stud_h = pitch * 0.42+ studs = []+ for idx in column_top.values():+ c = centers[idx]+ cyl = trimesh.creation.cylinder(radius=stud_r, height=stud_h, sections=12)+ cyl.apply_translation([c[0], c[1], c[2] + pitch * 0.5 + stud_h * 0.5])+ cyl.visual.face_colors = np.tile(colors[idx], (len(cyl.faces), 1))+ studs.append(cyl)++ if studs:+ return trimesh.util.concatenate([base, *studs])+ return base+++def _decimate(mesh, target_faces: int):+ """Quadric decimation via open3d, with a trimesh fallback. Used by lattice/lowpoly."""+ import numpy as np+ import trimesh++ if len(mesh.faces) <= target_faces:+ return mesh+ try:+ import open3d as o3d++ om = o3d.geometry.TriangleMesh()+ om.vertices = o3d.utility.Vector3dVector(mesh.vertices.astype(np.float64))+ om.triangles = o3d.utility.Vector3iVector(mesh.faces.astype(np.int32))+ simplified = om.simplify_quadric_decimation(int(target_faces))+ return trimesh.Trimesh(+ vertices=np.asarray(simplified.vertices),+ faces=np.asarray(simplified.triangles),+ process=False,+ )+ except Exception as exc: # noqa: BLE001+ log.info("open3d decimation fell back to trimesh: %s", exc)+ try:+ return mesh.simplify_quadric_decimation(face_count=int(target_faces))+ except Exception:+ return mesh+++def _stylize_voronoi(mesh, resolution: int):+ """Thicken a decimated shell's edges into an open strut-and-node lattice."""+ import numpy as np+ import trimesh++ target_faces = int(np.clip(resolution * 40, 200, 4000))+ shell = _decimate(mesh, target_faces)++ edges = shell.edges_unique # (E,2) vertex index pairs+ verts = np.asarray(shell.vertices, dtype=np.float64)+ if len(edges) == 0:+ raise ValueError("mesh has no edges to latticize")++ # Cap strut count by decimating further if needed.+ if len(edges) > MAX_LATTICE_EDGES:+ ratio = MAX_LATTICE_EDGES / len(edges)+ shell = _decimate(shell, max(60, int(len(shell.faces) * ratio)))+ edges = shell.edges_unique+ verts = np.asarray(shell.vertices, dtype=np.float64)+ # Hard backstop: if decimation was unavailable and the edge set is still over+ # budget, keep a deterministic uniform stride so output stays bounded.+ if len(edges) > MAX_LATTICE_EDGES:+ stride = int(np.ceil(len(edges) / MAX_LATTICE_EDGES))+ edges = edges[::stride]++ diag = float(np.linalg.norm(mesh.extents))+ strut_r = max(diag * 0.004, diag / max(resolution, 1) * 0.18)++ color_at = _source_color_sampler(mesh)+ mids = (verts[edges[:, 0]] + verts[edges[:, 1]]) * 0.5+ edge_colors = color_at(mids)++ parts = []+ for i, (a, b) in enumerate(edges):+ seg = verts[[a, b]]+ length = float(np.linalg.norm(seg[1] - seg[0]))+ if length <= 1e-9:+ continue+ strut = trimesh.creation.cylinder(radius=strut_r, segment=seg, sections=6)+ strut.visual.face_colors = np.tile(edge_colors[i], (len(strut.faces), 1))+ parts.append(strut)++ # Spherical nodes weld the struts at each used vertex.+ used = np.unique(edges)+ node_colors = color_at(verts[used])+ for j, vi in enumerate(used):+ node = trimesh.creation.icosphere(subdivisions=0, radius=strut_r * 1.45)+ node.apply_translation(verts[vi])+ node.visual.face_colors = np.tile(node_colors[j], (len(node.faces), 1))+ parts.append(node)++ if not parts:+ raise ValueError("lattice generation produced no geometry")+ return trimesh.util.concatenate(parts)+++def _stylize_lowpoly(mesh, resolution: int):+ """Decimate hard, then split every face onto its own vertices for flat shading."""+ import numpy as np+ import trimesh++ target_faces = int(np.clip(resolution * 60, 80, 20_000))+ deci = _decimate(mesh, target_faces)++ color_at = _source_color_sampler(deci)+ face_colors = color_at(deci.triangles_center) # (F,4)++ # Unweld: each triangle gets three unique vertices so normals are per-face,+ # producing crisp facets instead of smooth Gouraud shading.+ tri_verts = deci.vertices[deci.faces].reshape(-1, 3)+ new_faces = np.arange(len(tri_verts)).reshape(-1, 3)+ vertex_colors = np.repeat(face_colors, 3, axis=0)++ faceted = trimesh.Trimesh(vertices=tri_verts, faces=new_faces, process=False)+ faceted.visual.vertex_colors = vertex_colors+ return faceted+++STYLES: dict[str, Callable] = {+ "voxel": _stylize_voxel,+ "brick": _stylize_brick,+ "voronoi": _stylize_voronoi,+ "lowpoly": _stylize_lowpoly,+}+++# ── export + pipeline ───────────────────────────────────────────────────────────────+++def _export_mesh(mesh, output_format: str) -> tuple[bytes, str]:+ import trimesh++ fmt = output_format.lower()+ with tempfile.TemporaryDirectory() as tmpdir:+ out_path = Path(tmpdir) / f"output.{fmt}"+ if fmt == "glb":+ scene = trimesh.scene.scene.Scene(geometry={"stylized": mesh})+ scene.export(str(out_path))+ else:+ mesh.export(str(out_path))+ data = out_path.read_bytes()+ return data, ("model/gltf-binary" if fmt == "glb" else "application/octet-stream")+++def _run_processing(mesh_url: str, style: str, resolution: int, output_format: str):+ data, suffix = _fetch_mesh(mesh_url)+ mesh = _load_single_mesh(data, suffix)++ transform = STYLES[style]+ styled = transform(mesh, resolution)++ out_bytes, content_type = _export_mesh(styled, output_format)+ face_count = int(len(styled.faces)) if hasattr(styled, "faces") else 0+ return out_bytes, face_count, content_type+++async def _process(task_id: str, mesh_url: str, style: str, resolution: int, output_format: str) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ out_bytes, face_count, content_type = await loop.run_in_executor(+ None, _run_processing, mesh_url, style, resolution, output_format+ )++ blob_name = f"stylize/{task_id}.{output_format}"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None, lambda: blob.upload_from_string(out_bytes, content_type=content_type)+ )+ result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_url": result_url,+ "face_count": face_count,+ "style": style,+ "resolution": resolution,+ "output_format": output_format,+ "bytes": len(out_bytes),+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info(+ "[%s] %s done in %.2fs — %d faces, %d bytes → %s",+ task_id, style, elapsed, face_count, len(out_bytes), result_url,+ )+ except Exception as exc: # noqa: BLE001+ _tasks[task_id].update({+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] stylize {style}"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+++class ProcessRequest(BaseModel):+ mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ style: str = Field(default="voxel", description="|".join(STYLE_CATALOG))+ resolution: Optional[int] = Field(default=None, description="Style-specific density; see /styles")+ output_format: str = Field(default="glb")++ @field_validator("style")+ @classmethod+ def validate_style(cls, v: str) -> str:+ v = v.lower().strip()+ if v not in STYLE_CATALOG:+ raise ValueError(f"unknown style: {v}. Choose from {sorted(STYLE_CATALOG)}")+ return v++ @field_validator("output_format")+ @classmethod+ def validate_format(cls, v: str) -> str:+ v = v.lower().lstrip(".")+ if v not in SUPPORTED_OUTPUT_FORMATS:+ raise ValueError(f"unsupported output format: {v}. Choose from {sorted(SUPPORTED_OUTPUT_FORMATS)}")+ return v++[email protected]("/process", status_code=202)+async def process_mesh(+ body: ProcessRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ resolution = _clamp_resolution(body.style, body.resolution)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "style": body.style,+ "resolution": resolution,+ "output_format": body.output_format,+ }+ background_tasks.add_task(+ _process, task_id, body.mesh, body.style, resolution, body.output_format+ )+ return {"task_id": task_id, "status": "queued", "style": body.style, "resolution": resolution}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/styles")+async def list_styles() -> dict:+ """Public filter catalog — drives the UI gallery and documents the density knob."""+ return {+ "styles": [+ {"key": key, "name": spec["name"], "description": spec["description"], "resolution": spec["resolution"]}+ for key, spec in STYLE_CATALOG.items()+ ]+ }++[email protected]("/health")+async def health() -> dict:+ return {"ok": True, "service": "stylize", "styles": list(STYLE_CATALOG)}diff --git a/workers/stylize/requirements.txt b/workers/stylize/requirements.txtnew file mode 100644index 000000000..6f4ac0a08--- /dev/null+++ b/workers/stylize/requirements.txt@@ -0,0 +1,11 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+trimesh[easy]==4.5.3+open3d==0.18.0+numpy==1.26.4+scipy==1.13.1+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3+# FBX / DAE input support via assimp python bindings+pyassimp==5.2.5diff --git a/workers/stylize/worker_security.py b/workers/stylize/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/stylize/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/texture/main.py b/workers/texture/main.pyindex c21fcdacd..70bcea92c 100644--- a/workers/texture/main.py+++ b/workers/texture/main.py@@ -1,11 +1,19 @@"""Text-guided texture generation service.-Takes an untextured (or poorly-textured) GLB and a text prompt, renders the-mesh from N viewpoints, generates coherent texture views with SDXL + ControlNet-(depth), and back-projects them onto the UV map.+Two capabilities share one model server:-Pipeline:+ • Full retexture (/texture) — takes an untextured (or poorly-textured) GLB and+ a text prompt, renders the mesh from N viewpoints, generates coherent texture+ views with SDXL + ControlNet (depth), and back-projects them onto the UV map.++ • Magic-brush region retexture (/retexture_region) — repaints ONLY a masked+ region of an existing texture from a prompt/colour, preserving the rest+ pixel-for-pixel and feathering the seam so the edit is invisible. This is the+ surgical counterpart to the all-or-nothing /texture pass and is safe to run+ repeatedly (each pass operates on the latest texture).++Full-retexture pipeline:1. Load mesh (trimesh), ensure UV mapping exists (auto-unwrap if missing)2. Render depth maps from 8 canonical viewpoints using pyrender3. For each view: run SDXL Img2Img + ControlNet-Depth to generate textures@@ -13,6 +21,19 @@ Pipeline:5. Blend overlapping UV regions by confidence (distance-weighted)6. Bake final texture atlas and export as textured GLB+Region-retexture pipeline (UV-space inpainting):+ 1. Load the GLB WITHOUT repacking UVs and pull out its existing baseColour+ atlas — the frontend painted the mask in exactly this UV space, so we must+ not unwrap/concatenate or the mask would no longer align.+ 2. Decode the caller's UV-space mask (white = repaint, black = keep).+ 3. Run real SDXL inpainting on the atlas, regenerating only the masked region+ (optionally pre-tinted toward a target colour).+ 4. Composite the inpaint output back over the original atlas through a+ feathered alpha so untouched texels are bit-identical and the seam ramps+ smoothly — invisible blend, no global quality loss across repeated passes.+ 5. Re-export the GLB with the same mesh, UVs, and material (only baseColour+ swapped).+API contract:POST /texture {mesh: url, # https GLB URL (required)@@ -22,6 +43,19 @@ API contract:texture_size?: int # 512|1024|2048 (default: 1024)} → 202 { task_id, status }+ POST /retexture_region {+ mesh: url, # https GLB URL with an existing texture (required)+ prompt: str, # what to paint into the region (required unless color set)+ mask_b64?: str, # UV-space mask PNG, base64 (white = edit). Either this …+ mask?: url, # … or a public https URL to the mask PNG.+ color?: str, # optional "#rrggbb" target colour for the region+ negative_prompt?: str,+ texture_size?: int, # 512|1024|2048 working/output atlas size (default: 1024)+ strength?: float, # inpaint denoise strength 0.2–1.0 (default 0.85)+ feather?: int, # seam feather radius in atlas px (default 24)+ seed?: int+ } → 202 { task_id, status }+GET /tasks/:id → { task_id, status, result_url?, error? }GET /health → { ok, gpu_available, model_loaded }@@ -31,6 +65,8 @@ Environment variables:SDXL_MODEL — HuggingFace model id (default: stabilityai/stable-diffusion-xl-base-1.0)CONTROLNET_MODEL — ControlNet depth model id(default: diffusers/controlnet-depth-sdxl-1.0)+ SDXL_INPAINT_MODEL — SDXL inpainting checkpoint for the magic brush+ (default: diffusers/stable-diffusion-xl-1.0-inpainting-0.1)WEIGHTS_DIR — local cache dir for model weights (default: /weights)MAX_CONCURRENT — default 1 (GPU-bound)"""@@ -39,21 +75,22 @@ from __future__ import annotationsimport asyncioimport base64+import binasciiimport ioimport loggingimport os-import tempfile+import threadingimport timeimport uuidfrom contextlib import asynccontextmanagerfrom pathlib import Path-from typing import Optional+from typing import Callable, Optionalimport numpy as npimport torchfrom fastapi import FastAPI, HTTPException, Header, BackgroundTasksfrom google.cloud import storage-from PIL import Image+from PIL import Image, ImageFilterfrom pydantic import BaseModel, Field, field_validatorfrom worker_security import (@@ -76,9 +113,21 @@ SDXL_MODEL = os.environ.get("SDXL_MODEL", "stabilityai/stable-diffusion-xl-base-CONTROLNET_MODEL = os.environ.get("CONTROLNET_MODEL", "diffusers/controlnet-depth-sdxl-1.0")+SDXL_INPAINT_MODEL = os.environ.get(+ "SDXL_INPAINT_MODEL", "diffusers/stable-diffusion-xl-1.0-inpainting-0.1"+)MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))+# Hard caps for the region-retexture mask payload — a UV mask is a small 1-channel+# PNG; anything larger is malformed or hostile.+MAX_MASK_BYTES = 8 * 1024 * 1024+# SDXL inpainting is trained at 1024²; we always run inference there and resample+# to the working atlas size so fine texture detail outside the region survives.+INPAINT_INFER_SIZE = 1024+_pipe = None+_inpaint_pipe = None+_inpaint_lock = threading.Lock()_bucket: Optional[storage.Bucket] = None_sem: Optional[asyncio.Semaphore] = None_tasks: dict[str, dict] = {}@@ -129,6 +178,45 @@ def _load_pipeline() -> None:log.info("Texture pipeline loaded")+def _load_inpaint_pipeline() -> None:+ """Lazily load the SDXL inpainting pipeline used by the magic brush.++ Kept separate from the depth-ControlNet text pipeline so the existing+ /texture path pays no extra startup cost or VRAM until a region edit is+ actually requested. Guarded by a lock — under the default MAX_CONCURRENT=1+ only one request runs at a time, but the lock keeps a future bump safe.+ """+ global _inpaint_pipe+ if _inpaint_pipe is not None:+ return+ with _inpaint_lock:+ if _inpaint_pipe is not None:+ return+ from diffusers import StableDiffusionXLInpaintPipeline, AutoencoderKL++ log.info("Loading SDXL inpaint model: %s", SDXL_INPAINT_MODEL)+ vae = AutoencoderKL.from_pretrained(+ "madebyollin/sdxl-vae-fp16-fix",+ torch_dtype=torch.float16,+ cache_dir=WEIGHTS_DIR,+ )+ pipe = StableDiffusionXLInpaintPipeline.from_pretrained(+ SDXL_INPAINT_MODEL,+ vae=vae,+ torch_dtype=torch.float16,+ use_safetensors=True,+ cache_dir=WEIGHTS_DIR,+ )+ pipe.to("cuda")+ pipe.enable_model_cpu_offload()+ try:+ pipe.enable_xformers_memory_efficient_attention()+ except Exception as exc: # xformers is optional — never fatal+ log.warning("xformers unavailable for inpaint pipe: %s", exc)+ _inpaint_pipe = pipe+ log.info("Inpaint pipeline loaded")++@asynccontextmanagerasync def lifespan(app: FastAPI):global _bucket, _sem