Compare commits

..

No commits in common. "main" and "v1.4.0" have entirely different histories.
main ... v1.4.0

99 changed files with 646 additions and 13724 deletions

View file

@ -54,7 +54,7 @@ jobs:
# APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- name: Upload installers
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v4
with:
name: 3dgenstudio-${{ matrix.os }}
path: |

8
.gitignore vendored
View file

@ -7,12 +7,8 @@ dist/
# Electron packaged installers
release/
# Local database and assets (Portable Data).
# Leading slash ANCHORS this to the repo root. Unanchored, `data/` matches a
# directory named "data" at ANY depth — which silently excluded the whole
# thirdparty/skintokens/src/data package from the repo, so a fresh clone could
# not import rig.py at all ("No module named 'src.data'").
/data/
# Local database and assets (Portable Data)
data/
# Wiki author mode — presence of this file unlocks editing the Wiki.
# Kept local (never synced) so the published docs are read-only for end users.

View file

@ -19,11 +19,6 @@
| Date | Description |
| --- | --- |
| **2026-07-28** | Fixed Desktop App on Linux<br>ComfyUI: Added Enums<br>Wireframe mode in Mesh Previewer |
| **2026-07-27** | ComfyUI: Custom models folder<br>Mesh Export: Save last output folder<br>DB: Fixed assets linked to a project<br>Kanban: Can add more meshes and images from any column<br>Desktop App: Fixed Graph page slowness |
| **2026-07-23** | Added Brainstorming Boards |
| **2026-07-20** | MCP Server<br>Graph Page: Added Reorganize button<br>Graph Page: Save the last position and zoom level<br>Graph Page: Simplified Image Node Actions<br>Desktop App: Fixed Wiki<br>Desktop App: Auto-start python services in Settings<br>3D Mesh: Thumbnail is now generated by mesh-tools (python) |
| **2026-07-16** | Mesh Preview: FBX Export (Unity, Unreal Engine)<br>Graph Page: Can import a mesh directly from the computer<br>Kanban board: Added Rigging column |
| **2026-07-15** | MeshEditor: Auto Rig with Skintokens<br>Fixed Desktop App Setup |
| **2026-07-10** | Desktop App Installer<br>Speed up Auto Retopo<br>Added Clean Non-Manifold Edges in Auto Retopo |
| **2026-07-08** | Added Hitem3D API v1 |
@ -212,7 +207,7 @@ Open the application and configure your services in the settings area:
## Documentation
A complete Wiki is included with the application.
You will find some documentation here: https://github.com/visualbruno/3DGenStudio/tree/main/docs
---
@ -222,7 +217,6 @@ A complete Wiki is included with the application.
- [**SkinTokens**](https://github.com/VAST-AI-Research/SkinTokens) — used in **Auto Rig** for AI-powered skeleton generation and skinning.
- [**mesh2motion-app**](https://github.com/Mesh2Motion/mesh2motion-app) — used in **Auto Rig** for skeleton/animation reference.
- [**excalidraw**](https://github.com/excalidraw/excalidraw) — used for Brainstorming Boards.
---

View file

@ -1,159 +0,0 @@
# 3D Gen Studio — MCP Server
3D Gen Studio ships an [MCP](https://modelcontextprotocol.io) (Model Context Protocol) server so any AI — Claude Desktop/Code, ChatGPT, local LLM stacks — can automate the app: create projects, build node graphs, run ComfyUI workflows, generate images and meshes, run mesh tools (auto UV, retopo, repair, rig, optimize), and export/import projects.
## Endpoint
The MCP server is part of the app backend. Start the app (dev: `npm run dev`, or launch the desktop app) and the endpoint is live at:
```
http://localhost:3001/mcp (Streamable HTTP, stateless)
```
No extra process is needed — it ships with the backend in both dev and the packaged desktop app.
### Security
- **Local by default** — without a token, only clients on the same machine may connect.
- **Remote access** — set a bearer token in settings (`mcp.token`); remote clients must send `Authorization: Bearer <token>`.
- **Disable** — set `mcp.enabled` to `false` in settings; the endpoint then returns 404.
Settings live in the app database and can be changed via `POST /api/settings` with `{"mcp": {"enabled": true, "token": "..."}}` (or the Settings UI once exposed there).
## Client setup
### Claude Code
```sh
claude mcp add --transport http 3d-gen-studio http://localhost:3001/mcp
```
### Claude Desktop
Add a custom connector (Settings → Connectors) with URL `http://localhost:3001/mcp`, or use the stdio bridge in `claude_desktop_config.json`:
```json
{
"mcpServers": {
"3d-gen-studio": {
"command": "node",
"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]
}
}
}
```
The stdio bridge requires the app to be running; it talks to `http://127.0.0.1:3001` (override with the `GENSTUDIO_URL` env var).
Alternatively, without a checkout: `npx mcp-remote http://localhost:3001/mcp` as the command.
### VS Code (GitHub Copilot)
Requires VS Code 1.102+ with the GitHub Copilot and GitHub Copilot Chat extensions; MCP tools are used from Copilot **Agent mode**. Fastest path: Command Palette → **MCP: Add Server…** → **HTTP** → `http://localhost:3001/mcp` → name it `3d-gen-studio`.
Or add a workspace `.vscode/mcp.json` (VS Code uses the `servers` key, not `mcpServers`):
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp"
}
}
}
```
Start it via the CodeLens in that file (or the MCP view), then open Copilot Chat, switch to **Agent** mode, and select the 3D Gen Studio tools in the tools (🔧) picker. For a token-protected/remote endpoint, add a header and prompt for the token:
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp",
"headers": { "Authorization": "Bearer ${input:genstudio-token}" }
}
},
"inputs": [
{ "id": "genstudio-token", "type": "promptString", "description": "3D Gen Studio MCP token", "password": true }
]
}
```
A `stdio` server (`"type": "stdio"`, `"command": "node"`, `"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]`) also works and requires the app to be running.
### ChatGPT (developer mode) / other clients
Any client that supports Streamable HTTP MCP servers can connect to `http://localhost:3001/mcp` (remote clients need the bearer token, see Security).
### MCP Inspector (debugging)
```sh
npx @modelcontextprotocol/inspector
```
Connect with transport "Streamable HTTP" to `http://localhost:3001/mcp`.
## Tools
| Group | Tools |
|---|---|
| Projects | `list_projects`, `get_project`, `create_project`, `update_project`, `delete_project`, `export_project`, `import_project` |
| Kanban cards | `list_cards`, `move_card`, `delete_card`, `list_card_attributes`, `create_card_attribute`, `update_card_attribute`, `delete_card_attribute` |
| Graph | `get_graph`, `create_node`, `update_node`, `move_node`, `delete_node`, `connect_nodes`, `disconnect_nodes` |
| ComfyUI workflows | `list_workflows`, `inspect_workflow`, `import_workflow`, `update_workflow`, `run_workflow`, `get_run_status` |
| AI actions | `generate_image`, `edit_image`, `generate_mesh`, `generate_mesh_tencent`, `generate_mesh_tripo`, `generate_mesh_hitem`, `get_mesh_result`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` |
| Mesh tools | `auto_uv_mesh`, `auto_retopo_mesh` (fully-typed parameters), `run_mesh_tool` (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx), `export_mesh` |
| Assets | `list_assets`, `list_library_assets`, `view_asset`, `download_asset`, `upload_asset`, `link_asset`, `delete_asset` |
| System | `get_settings` (secrets redacted), `get_system_stats` |
### Displaying results on graph nodes
In graph projects, pass `nodeId` to `run_workflow`, `generate_image`, `edit_image`, or `generate_mesh` to display the results on that node — the first result becomes the node's asset, and additional results become new nodes stacked below it (wired to the same inputs). Without `nodeId` the generated assets are saved to the project but no node displays them.
`run_workflow` saves its output **under the source it was derived from, automatically** — you normally never set `parentAssetId`. The server matches each output to a resolved image/mesh input of the same type (whether that input was wired from the target node in a graph project or passed in `inputs` — so this works the same in **kanban** projects, which have no node wiring): an image output becomes an edit of that source image, a mesh output a version of that source mesh (matching the graph UI). So a re-texture (image + mesh in → mesh out) becomes a version of the input mesh, and a background-removal (image in → image out) an edit of the input image, with nothing extra to pass. Because the server knows the true output type (from the produced file), this holds even when the workflow's declared output type is missing or wrong. Set `parentAssetId` only to override the inferred parent; a parent whose type doesn't match the output type is ignored and a new root asset is created. (`edit_image` likewise saves an edit of its `imageSource`, and `run_mesh_tool` a version of its `assetId`.)
The target node's connected input assets also **auto-fill the workflow's image/mesh parameters**, matched by type (each connected asset used once). A node wired to an image and a mesh feeds a workflow that needs a Source Image + a mesh input without any manual mapping — so for a wired node you should **not** pass `inputs` for file (image/mesh/video) parameters and never need to guess their parameter ids. Set an `inputs` entry for a file parameter only to override a wired input or when nothing is connected; use `inputs` otherwise just for string/number/boolean parameters. Explicit `inputs`/`fileInputs` always take precedence over an auto-filled value.
When you *do* pass an image/mesh parameter in `inputs` (e.g. in a kanban project, which has no wiring), the value is simply the asset's **numeric id** — nothing else. The same plain id works for a root asset, an **edit**, or a **version**: a background-removed image is an edit, so pass that edit's own `id` (from the `children`/`edits` tree in `list_assets`). Do **not** pass a file path or filename, and do **not** pass a `{assetId, editId}` object — a bare id is always correct.
**Connect the input nodes _before_ you run.** `run_workflow`, `edit_image`, and `generate_mesh` read a node's connected input at the moment they execute — the input feeds the workflow/API and determines whether the result is saved as an edit/version. So the correct order is always: (1) `create_node` for the target, (2) `connect_nodes` to wire its input asset(s), then (3) run the workflow or API on that node. Running first and connecting afterwards is wrong: the run sees no input, so it can't use the source image/mesh and saves a stray new root asset instead of an edit/version — and the late connection does **not** re-run or re-parent it. If you ran in the wrong order, delete the stray result, connect the inputs, and run again.
### Parameter-heavy mesh tools
Auto UV and Auto Retopo have many tuning parameters (14 and 20 respectively) that materially change the output. Use the dedicated `auto_uv_mesh` and `auto_retopo_mesh` tools rather than `run_mesh_tool` for these: each declares every parameter in its schema with type, range, default, and description (mirroring the Python service's models), so a client can set exactly what it needs and see the valid bounds. Any subset of options may be set; unset keys fall back to the documented default. For Auto Retopo, the `shell_*` options apply only when `watertight` is `true`. `run_mesh_tool` still accepts `auto_uv`/`auto_retopo` (options ride along as a free-form object) for backward compatibility.
### External mesh-generation providers
Tencent Hunyuan3D, Tripo AI, and Hitem3D each take a different, parameter-heavy option set. Use the dedicated `generate_mesh_tencent`, `generate_mesh_tripo`, and `generate_mesh_hitem` tools: each hardwires its provider and declares every parameter in its `options` schema with type, enum/range, and default (mirroring the backend 1:1), so a client can set exactly what it needs. Provider notes: Tencent `region` is required and `LowPoly` needs model `3.0`; Tripo's `P1` model ignores several options and `generateParts` is incompatible with `texture`/`pbr`/`quad`; Hitem3D requires an `imageSource`. Tencent and Tripo accept either a `prompt` (text-to-3D) or an `imageSource` (image-to-3D). The generic `generate_mesh` still accepts these providers with a free-form `options` object for backward compatibility.
These provider jobs are asynchronous. Unlike the app UI (where you click **Get Result** to poll), the MCP tools poll for you automatically: `generate_mesh*` submits the job and then polls the provider until the mesh is ready, streaming progress, and returns the saved assets — the AI just awaits the call and gets `{status:"completed", assets}`. The mesh is only saved once a poll sees completion, so if a job outlives `timeoutSeconds` (default 1200s) the tool returns `{status:"running", provider, taskId/jobId, region}`; pass those ids to **`get_mesh_result`** to finish and save the job (safe to call repeatedly). Do not re-run generation on timeout — that starts a new job.
Image generation (`generate_image`) is prompt-only by design: OpenAI/Google image parameters (size, quality, aspect ratio) are fixed in each provider's payload template in Settings, not passed per request, so there is nothing extra to set over MCP.
### Long-running operations
`run_workflow`, `generate_mesh`, and `run_mesh_tool` block until the result is ready and stream MCP progress notifications. If a run outlives the tool's `timeoutSeconds`, it keeps running in the background and the tool returns a `promptId`/job info to poll (`get_run_status` for ComfyUI runs; `list_assets`/`list_cards` otherwise).
### Files and assets
- `view_asset` returns the **actual image** as MCP image content, so the AI can visually inspect generated images (for meshes it returns the thumbnail preview when one exists). Inline viewing is capped at ~3.5 MB per image.
- `download_asset` writes any asset file (image/mesh/workflow) to an absolute folder on the machine running the app.
- Asset listings and results otherwise carry direct download URLs (`http://localhost:3001/assets/...`); local files are passed into tools by absolute path (`upload_asset`, `import_workflow filePath`, `run_workflow fileInputs`), and exports write to absolute folders.
## Requirements per capability
| Capability | Needs |
|---|---|
| Projects / cards / graph / assets / export / import | just the app running |
| `run_workflow`, ComfyUI-based edits | ComfyUI running (URL in Settings, default `127.0.0.1:8188`) |
| `generate_image`, `edit_image`, `generate_mesh`, `generate_mesh_tencent`, `generate_mesh_tripo`, `generate_mesh_hitem`, `edit_mesh`, `texture_mesh`, `rig_mesh_api` | provider API keys in Settings |
| `auto_uv_mesh`, `auto_retopo_mesh`, `run_mesh_tool` auto_uv / auto_retopo / repair / convert_fbx | Python mesh-tools service (`:8200`) running — the desktop app can start it from Settings |
| `run_mesh_tool` auto_rig | rigging service (`:8300`) running |
| `run_mesh_tool` optimize | nothing extra (bundled gltfpack) |
## Limitations
- The interactive **Mesh Editor** operations (sculpt, modeling, boolean, painting, projection, texture bake) and **Image Editor** pixel operations (crop, filters, shadow remover) run in the browser (WebGL/canvas) and are not exposed over MCP. AI-driven alternatives: ComfyUI workflows (`run_workflow`), prompt-based edits (`edit_image`), and the mesh-tool services.
- If the app UI is open in a browser while an MCP client mutates data, open Graph/Kanban pages refresh automatically via the app event stream; other pages may need a manual refresh.

View file

@ -35,15 +35,10 @@ files:
- server.js
- storage.js
- wikiStorage.js
# MCP automation server (POST /mcp on the backend + stdio bridge).
- mcp/**/*
- version.json
- package.json
- dist/**/*
- electron/**/*
# App icon shown on the splash/setup windows (electron/splash.html loads it
# from disk, so it must ship even though dist/ has its own copy).
- public/favicon.png
- comfyui_workflows/**/*
- setup/**/*
- tools/**/*

View file

@ -18,7 +18,6 @@ const fs = require('node:fs');
const { spawn } = require('node:child_process');
const {
isReady,
MESHTOOLS_REQS_TAG,
ensureUv,
setupPythonServer,
setupSkintokens,
@ -90,28 +89,10 @@ function startBackend() {
PORT: String(BACKEND_PORT),
NODE_ENV: 'production',
},
// 4th fd = IPC channel: lets the headless backend ask the main process to
// start a Python service on demand (e.g. to render a mesh thumbnail) —
// something it otherwise can't do (ensureService lives here, not there).
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
stdio: ['ignore', 'pipe', 'pipe'],
});
proc.stdout.pipe(out);
proc.stderr.pipe(out);
// Backend → main service requests. Reuses the same ensureService the Start
// buttons and on-demand UI path use (start + health wait + dedupe).
proc.on('message', async (msg) => {
if (!msg || msg.type !== 'services:ensure') return;
const { name, requestId } = msg;
let reply = { type: 'services:ensure:result', requestId };
try {
await ensureService(name);
reply.ok = true;
} catch (err) {
reply = { ...reply, ok: false, error: err?.message || String(err) };
}
try { proc.send(reply); } catch { /* backend gone */ }
});
proc.on('exit', (code, signal) => {
log(`Backend exited (code=${code} signal=${signal})`);
if (!shuttingDown) {
@ -140,45 +121,11 @@ function waitForBackend(timeoutMs = 60000, intervalMs = 400) {
});
}
// Fetch the app settings from the backend over HTTP (the backend owns the DB).
// Resolves null on any error — callers treat that as "no auto-start".
function fetchSettings(timeoutMs = 4000) {
return new Promise((resolve) => {
const req = http.get(`${BACKEND_ORIGIN}/api/settings`, (res) => {
if (res.statusCode !== 200) { res.resume(); return resolve(null); }
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => { try { resolve(JSON.parse(body)); } catch { resolve(null); } });
});
req.on('error', () => resolve(null));
req.setTimeout(timeoutMs, () => req.destroy());
});
}
// Start the services the user opted into auto-starting (Settings → Mesh Tools /
// Auto Rig). Non-blocking and best-effort: failures are logged, never fatal, and
// never delay the window. Setting key `rigtools` maps to service `rigging`.
async function autoStartServices() {
const settings = await fetchSettings();
const apis = settings?.apis || {};
const wanted = [
apis.meshtools?.autoStart ? 'meshtools' : null,
apis.rigtools?.autoStart ? 'rigging' : null,
].filter(Boolean);
for (const name of wanted) {
log(`Auto-starting ${name} service (enabled in Settings)`);
ensureService(name).catch((err) => log(`Auto-start of ${name} failed: ${err?.message || err}`));
}
}
// --- On-demand Python service management ------------------------------------
function serviceRegistry() {
return {
meshtools: {
// reqsTag: a requirements.txt bump flips this service back to
// "not installed" until setup re-runs (incrementally) and re-tags it.
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT, reqsTag: MESHTOOLS_REQS_TAG,
label: 'Mesh Tools', venv: PY_VENV, port: PYTHON_PORT,
start: () => startPythonServer({
serviceDir: PYTHON_DIR, venvDir: PY_VENV, port: PYTHON_PORT,
logStream: openLogStream('python.log'), log,
@ -236,7 +183,7 @@ function stopService(name) {
function ensureService(name) {
const svc = SERVICES[name];
if (!svc) return Promise.reject(new Error(`Unknown service: ${name}`));
if (!isReady(svc.venv, svc.reqsTag)) {
if (!isReady(svc.venv)) {
return Promise.reject(new Error(`${svc.label} is not installed yet. Install it in Settings.`));
}
if (starting[name]) return starting[name];
@ -260,7 +207,7 @@ function serviceStatus() {
for (const [name, svc] of Object.entries(SERVICES)) {
out[name] = {
label: svc.label,
installed: isReady(svc.venv, svc.reqsTag),
installed: isReady(svc.venv),
running: !!handles[name],
starting: !!starting[name],
};
@ -291,7 +238,7 @@ async function doSetup(rigging, send) {
const uv = await ensureUv({ appRoot: APP_ROOT, onLine: (t) => send({ service: 'meshtools', kind: 'log', text: t }) });
if (!uv) throw new Error('Could not find or install uv (the Python toolchain manager).');
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
if (!isReady(PY_VENV)) {
await setupPythonServer({
uv, serviceDir: PYTHON_DIR, venvDir: PY_VENV,
onProgress: (e) => send({ service: 'meshtools', ...e }),
@ -314,7 +261,7 @@ async function doSetup(rigging, send) {
function registerSetupIpc() {
ipcMain.handle('setup:status', () => ({
desktop: true,
meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG),
meshtools: isReady(PY_VENV),
rigging: isReady(RIG_VENV),
}));
@ -325,7 +272,7 @@ function registerSetupIpc() {
// Provisioned only — services are started on demand (or from Settings),
// not here, so installing doesn't spin up a process the user isn't using.
log('Setup run complete.');
return { ok: true, status: { meshtools: isReady(PY_VENV, MESHTOOLS_REQS_TAG), rigging: isReady(RIG_VENV) } };
return { ok: true, status: { meshtools: isReady(PY_VENV), rigging: isReady(RIG_VENV) } };
} catch (err) {
log(`Setup run failed: ${err.message}`);
send({ kind: 'error', text: err.message });
@ -394,7 +341,7 @@ async function boot() {
// progress (isReady probes the venv, so a legacy venv whose system Python was
// removed is detected and rebuilt). Otherwise → fast path (splash).
let splash = null;
if (!isReady(PY_VENV, MESHTOOLS_REQS_TAG)) {
if (!isReady(PY_VENV)) {
await runFirstRunSetup();
} else {
splash = loadingWindow();
@ -419,10 +366,6 @@ async function boot() {
createWindow();
if (splash && !splash.isDestroyed()) splash.close();
if (setupWindow && !setupWindow.isDestroyed()) setupWindow.close();
// Fire the opt-in service auto-starts AFTER the window is up so they never
// delay launch (fire-and-forget — each service reports its own readiness).
autoStartServices();
}
let didShutdown = false;

View file

@ -10,10 +10,7 @@
// - Mesh Tools (python-server): always provisioned. CPU only.
// - Rigging (skintokens): opt-in. Heavy (torch + flash-attn + model) and needs
// an NVIDIA GPU; the setup reuses the service's own Python helpers
// (select_flash_attn.py / download_wheel.py / download.py). Windows and Linux
// only — flash-attn comes from a prebuilt wheel curated PER PLATFORM
// (flash_attention_windows.txt / flash_attention_linux.txt) because building
// it from source takes ~an hour either way. macOS has no CUDA and is refused.
// (select_flash_attn.py / download_wheel.py / download.py).
//
// Everything is async and streams output to an onProgress callback; nothing
// blocks the Electron main-process event loop.
@ -24,16 +21,9 @@ const os = require('node:os');
const { spawn, spawnSync } = require('node:child_process');
const IS_WIN = process.platform === 'win32';
const IS_MAC = process.platform === 'darwin';
const PYVER = '3.13';
const UV_EXE = IS_WIN ? 'uv.exe' : 'uv';
// Bump whenever python-server/requirements.txt changes so EXISTING installs
// re-run the (incremental) mesh-tools setup and pick up the new deps — the
// marker alone only proves that SOME requirements set was installed once.
// History: 2 = added bpy (GLB->FBX engine export, v1.5.0).
const MESHTOOLS_REQS_TAG = 'meshtools-reqs-2';
function venvPython(venvDir) {
return IS_WIN
? path.join(venvDir, 'Scripts', 'python.exe')
@ -62,19 +52,8 @@ function venvUsable(venvDir) {
}
}
// `requiredTag` (optional) additionally requires the marker to start with that
// tag — pass MESHTOOLS_REQS_TAG for the mesh-tools venv so a requirements bump
// re-triggers its setup. Rigging keeps the tag-less check (its marker must not
// be invalidated by mesh-tools changes: re-setup means multi-GB torch/model
// downloads).
function isReady(venvDir, requiredTag) {
if (!fs.existsSync(depsMarker(venvDir)) || !venvUsable(venvDir)) return false;
if (!requiredTag) return true;
try {
return fs.readFileSync(depsMarker(venvDir), 'utf8').startsWith(requiredTag);
} catch {
return false;
}
function isReady(venvDir) {
return fs.existsSync(depsMarker(venvDir)) && venvUsable(venvDir);
}
// Create the venv with uv, rebuilding from scratch if the existing one is broken
@ -186,7 +165,7 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
run: (log) => runStream(uv, ['pip', 'install', '--python', vp, '-r', 'requirements.txt'], { cwd: serviceDir, env, onLine: log }).then((r) => r.code),
},
], onProgress);
fs.writeFileSync(depsMarker(venvDir), `${MESHTOOLS_REQS_TAG} ${new Date().toISOString()}`);
fs.writeFileSync(depsMarker(venvDir), new Date().toISOString());
onProgress({ kind: 'done' });
}
@ -196,11 +175,6 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
// downloaded there; rig_server.py chdirs to this same dir at launch (via
// RIGTOOLS_DATA_DIR) so its relative weight lookups resolve here.
async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) {
// Rigging needs an NVIDIA GPU. Say so up front rather than failing several GB
// into a torch install that has no macOS CUDA build to find.
if (IS_MAC) {
throw new Error('Rigging (Auto Rig) needs an NVIDIA GPU (CUDA), which macOS does not provide. The rest of the app works normally.');
}
const vp = venvPython(venvDir);
const env = process.env;
const modelDir = dataDir || serviceDir;
@ -223,9 +197,6 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
], (e) => onProgress(scaled(e, 0, 0.4)));
// Select the flash-attn wheel + matching torch for this machine's CUDA.
// select_flash_attn.py picks the table for THIS platform (win_amd64 wheels from
// flash_attention_windows.txt, linux_x86_64 from flash_attention_linux.txt) —
// a wheel from the wrong table is rejected outright by uv at install time.
onProgress({ kind: 'phase', phase: 'Selecting CUDA build', pct: 0.4 });
const sel = await runStream(vp, ['select_flash_attn.py'], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
let wheel = null, torchArgs = null;
@ -234,39 +205,29 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim();
}
// No match -> no rigging. Bail BEFORE the torch download: flash-attn is a hard
// requirement (src/model/tokenrig.py imports it unguarded, so the service cannot
// even load without it), and building it from source takes ~an hour on every
// platform. Pulling multi-GB of torch on the way to a certain failure is waste.
if (!wheel || !torchArgs) {
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA (see details). Rigging is unavailable on this machine.');
}
// Install torch with the curated per-wheel command, ABI-matched to the wheel.
// Install torch (curated per-wheel command, or a sane default).
onProgress({ kind: 'phase', phase: 'Installing PyTorch', pct: 0.45 });
const torchInstall = torchArgs
? torchArgs.split(/\s+/)
: ['torch==2.7.0', 'torchvision==0.22.0', 'torchaudio==2.7.0', '--index-url', 'https://download.pytorch.org/whl/cu128'];
{
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchArgs.split(/\s+/)], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchInstall], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error(`PyTorch install failed (exit ${r.code}).`);
}
// flash-attn — download the prebuilt wheel first (Hugging Face Xet URLs 403 for
// pip and need the HF client; GitHub release assets are plain URLs), install it,
// then PROVE it loads: a wheel built against a different torch ABI installs
// cleanly and only dies at `import flash_attn` with `undefined symbol: _ZN3c10…`.
// Catching that here beats surfacing it after the multi-GB checkpoint download.
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.6 });
{
// flash-attn — download the prebuilt wheel via the HF client, then install it.
if (wheel) {
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.65 });
const dl = await runStream(vp, ['download_wheel.py', wheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
const localWheel = dl.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
if (dl.code !== 0 || !localWheel) throw new Error('flash-attn download failed. Rigging cannot start without it.');
const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.');
}
onProgress({ kind: 'phase', phase: 'Verifying flash-attn', pct: 0.72 });
{
const probe = 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)';
const r = await runStream(vp, ['-c', probe], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn installed but will not import — most likely a torch ABI mismatch with the selected wheel (see details). Rigging cannot start.');
if (dl.code === 0 && localWheel) {
const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.');
} else {
throw new Error('flash-attn download failed. Rigging cannot start without it.');
}
} else {
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA. Rigging is unavailable.');
}
// Model checkpoints (large; downloaded into the WRITABLE data dir).
@ -354,7 +315,6 @@ function startService({ name, serviceDir, venvDir, script, env, logStream, log }
module.exports = {
PYVER,
MESHTOOLS_REQS_TAG,
venvPython,
isReady,
ensureUv,

View file

@ -71,7 +71,7 @@
<div class="svc__head">
<span class="dot"></span>
<span class="svc__name">Mesh Tools</span>
<span class="svc__tag">required · Auto UV / Retopo / FBX export (~1 GB)</span>
<span class="svc__tag">required · Auto UV / Retopo</span>
</div>
<div class="svc__phase">Waiting to start…</div>
<div class="bar"><i></i></div>
@ -83,7 +83,7 @@
<span class="svc__name">Rigging (Auto Rig)</span>
<span class="svc__tag">optional · NVIDIA GPU, large download</span>
</div>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB with a recent driver — CUDA 12.8+; downloads several GB)</label>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB; downloads several GB)</label>
<div class="svc__phase" style="display:none"></div>
<div class="bar" style="display:none"><i></i></div>
</div>
@ -109,13 +109,6 @@
const logEl = $('#log');
const errEl = $('#err');
// Rigging needs CUDA, so it exists on Windows and Linux only. Hide the option on
// macOS rather than offering an install that cannot succeed. (An unchecked box
// reads as false in runInstall, so nothing else needs to know.)
if ((window.genStudioDesktop && window.genStudioDesktop.platform) === 'darwin') {
$('#svc-rigging').style.display = 'none';
}
function setRow(service, { state, phase, pct }) {
const row = rows[service];
if (!row) return;

View file

@ -52,13 +52,6 @@
box-shadow: 0 0 22px rgba(124,92,255,0.55);
display: flex; align-items: center; justify-content: center;
font-size: 22px;
overflow: hidden;
}
/* App icon fills the orb; if the file is missing the emoji underneath shows. */
.orb img {
position: absolute; inset: 0; width: 100%; height: 100%;
object-fit: cover; border-radius: 50%;
-webkit-user-drag: none;
}
.title {
font-size: 26px; font-weight: 700; letter-spacing: .3px;
@ -75,7 +68,7 @@
<div class="glow"></div>
<div class="mark">
<div class="ring"></div>
<div class="orb">🌌<img src="../public/favicon.png" alt="" onerror="this.remove()" /></div>
<div class="orb">🌌</div>
</div>
<div class="title">3D Gen Studio</div>
<div class="status">Starting local services<span class="dots"></span></div>

View file

@ -1,204 +0,0 @@
// Loopback HTTP client for the MCP layer.
//
// Every MCP tool talks to the running 3D Gen Studio backend through its own
// REST API (the exact contract the React frontend uses) instead of importing
// storage.js directly. This keeps SQLite behind a single process and reuses
// the existing route handlers unchanged, so the MCP layer stays a thin shell.
import { Buffer } from 'node:buffer';
export function createApiClient(baseUrl) {
const base = String(baseUrl || 'http://127.0.0.1:3001').replace(/\/+$/, '');
async function parseJsonResponse(res, fallbackMessage) {
if (res.status === 204) return { ok: true };
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.error || `${fallbackMessage} (HTTP ${res.status})`);
}
return data;
}
async function apiJson(method, apiPath, { body, query } = {}) {
const url = new URL(`${base}/api${apiPath}`);
for (const [key, value] of Object.entries(query || {})) {
if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
}
const res = await fetch(url, {
method,
headers: body !== undefined ? { 'Content-Type': 'application/json' } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined
});
return parseJsonResponse(res, `${method} /api${apiPath} failed`);
}
async function apiForm(method, apiPath, formData) {
const res = await fetch(`${base}/api${apiPath}`, { method, body: formData });
return parseJsonResponse(res, `${method} /api${apiPath} failed`);
}
// Parse an SSE byte stream, invoking onData for each `data:` JSON payload.
// Heartbeat comments (`: keep-alive`) and malformed frames are skipped.
async function readSseStream(stream, onData) {
const reader = stream.getReader();
const decoder = new TextDecoder();
let buffer = '';
const handleEvent = raw => {
for (const line of raw.split('\n')) {
if (!line.startsWith('data:')) continue;
try {
onData(JSON.parse(line.slice(5).trim()));
} catch {
// Non-JSON data frame — ignore.
}
}
};
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) >= 0) {
handleEvent(buffer.slice(0, sep));
buffer = buffer.slice(sep + 2);
}
}
if (buffer.trim()) handleEvent(buffer);
}
// POST multipart to an endpoint that answers with an SSE stream (the mesh
// tool proxies). onProgress receives every `progress` event; resolves with
// the terminal `done` event; throws on an `error` event.
async function apiFormSse(apiPath, formData, onProgress) {
const res = await fetch(`${base}/api${apiPath}`, { method: 'POST', body: formData });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
const detail = data?.detail ? `: ${JSON.stringify(data.detail)}` : '';
throw new Error((data?.error || `POST /api${apiPath} failed (HTTP ${res.status})`) + detail);
}
let doneEvent = null;
let errorEvent = null;
await readSseStream(res.body, evt => {
if (evt?.type === 'progress') onProgress?.(evt);
else if (evt?.type === 'done') doneEvent = evt;
else if (evt?.type === 'error') errorEvent = evt;
});
if (errorEvent) throw new Error(errorEvent.detail || 'The mesh tool reported an error.');
if (!doneEvent) throw new Error('The mesh tool finished without returning a result.');
return doneEvent;
}
// Subscribe to a long-lived SSE endpoint. Events are delivered to onData
// until close() is called or the stream ends (onEnd fires on unexpected end).
function subscribeSse(apiPath, onData, { onEnd } = {}) {
const controller = new AbortController();
(async () => {
const res = await fetch(`${base}/api${apiPath}`, {
headers: { Accept: 'text/event-stream' },
signal: controller.signal
});
if (!res.ok) throw new Error(`SSE /api${apiPath} failed (HTTP ${res.status})`);
await readSseStream(res.body, onData);
throw new Error(`SSE /api${apiPath} ended unexpectedly`);
})().catch(err => {
if (!controller.signal.aborted) onEnd?.(err);
});
return { close: () => controller.abort() };
}
// Public URL for a stored asset file. Asset records carry both `filePath`
// ("data/assets/meshes/x.glb", storage-prefixed) and `filename`
// ("meshes/x.glb", relative to the served assets dir) — accept either.
function assetUrl(filePath) {
const relative = String(filePath || '').replace(/^\/+/, '').replace(/^data\/assets\//, '');
return `${base}/assets/${relative}`;
}
// Download a stored asset file as a Buffer.
async function fetchAssetBuffer(filePath) {
const res = await fetch(assetUrl(filePath));
if (!res.ok) throw new Error(`Failed to read asset file "${filePath}" (HTTP ${res.status})`);
return Buffer.from(await res.arrayBuffer());
}
return { base, apiJson, apiForm, apiFormSse, subscribeSse, assetUrl, fetchAssetBuffer };
}
// ---------------------------------------------------------------------------
// Tool plumbing shared by every tools/*.js module.
export function jsonResult(value) {
return { content: [{ type: 'text', text: JSON.stringify(value ?? null, null, 2) }] };
}
// Wrap a tool implementation: resolve to a JSON text result, surface thrown
// errors as MCP tool errors (isError) instead of protocol-level failures.
export function toolHandler(fn) {
return async (args, extra) => {
try {
return jsonResult(await fn(args ?? {}, extra));
} catch (err) {
return { isError: true, content: [{ type: 'text', text: String(err?.message || err) }] };
}
};
}
// Progress reporter bound to the caller's progressToken (no-op when the client
// didn't request progress). progress/total follow MCP semantics.
export function createProgressReporter(extra) {
const token = extra?._meta?.progressToken;
if (token === undefined || token === null) {
return async () => {};
}
return async (progress, total, message) => {
try {
await extra.sendNotification({
method: 'notifications/progress',
params: {
progressToken: token,
progress,
...(total !== undefined && total !== null ? { total } : {}),
...(message ? { message } : {})
}
});
} catch {
// Client disconnected or transport closed — progress is best-effort.
}
};
}
// Locate an asset anywhere in a project's asset tree (top-level assets plus
// nested edits/versions/children). Throws with a hint when the id is unknown.
export async function findProjectAsset(api, projectId, assetId) {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
const flat = [];
const visit = asset => {
if (!asset) return;
flat.push(asset);
for (const key of ['edits', 'versions', 'children']) {
if (Array.isArray(asset[key])) asset[key].forEach(visit);
}
};
(Array.isArray(assets) ? assets : []).forEach(visit);
const asset = flat.find(a => Number(a?.id) === Number(assetId));
if (!asset) throw new Error(`Asset ${assetId} not found in project ${projectId} (use list_assets to find valid ids).`);
if (!asset.filename && !asset.filePath) throw new Error(`Asset ${assetId} has no stored file.`);
return asset;
}
// Attach a public URL to an asset record (and its nested edits/versions when
// present) so MCP clients can download files without base64 round-trips.
export function withAssetUrls(api, asset) {
if (!asset || typeof asset !== 'object') return asset;
const out = { ...asset };
const file = out.filename || out.filePath;
if (file) out.url = api.assetUrl(file);
if (out.thumbnail) out.thumbnailUrl = api.assetUrl(out.thumbnail);
for (const key of ['edits', 'versions', 'children']) {
if (Array.isArray(out[key])) out[key] = out[key].map(item => withAssetUrls(api, item));
}
return out;
}

View file

@ -1,75 +0,0 @@
// Streamable-HTTP mount for the MCP server (stateless mode).
//
// Each POST /mcp request gets a fresh McpServer + transport — all real state
// lives in the app's database, so no session bookkeeping is needed, and
// progress notifications still stream on the POST response's SSE leg.
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { buildMcpServer } from './index.js';
const LOOPBACK_ADDRESSES = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
export function mountMcp(app, { baseUrl, getSettings, notifyMutation }) {
const handler = async (req, res) => {
try {
const settings = await getSettings().catch(() => null);
const mcpSettings = settings?.mcp || {};
if (mcpSettings.enabled === false) {
return res.status(404).json({ error: 'MCP server is disabled in Settings' });
}
const token = String(mcpSettings.token || '');
if (token) {
if (req.headers.authorization !== `Bearer ${token}`) {
return res.status(401).json({
jsonrpc: '2.0',
error: { code: -32001, message: 'Unauthorized: invalid or missing bearer token' },
id: null
});
}
} else if (!LOOPBACK_ADDRESSES.has(req.socket.remoteAddress)) {
// Without a token, only local clients may connect (the server binds
// all interfaces). Set settings.mcp.token to allow remote access.
return res.status(403).json({
jsonrpc: '2.0',
error: { code: -32002, message: 'Forbidden: remote access requires a bearer token (settings.mcp.token)' },
id: null
});
}
if (req.method !== 'POST') {
// Stateless mode: no server-initiated GET stream, no DELETE sessions.
res.setHeader('Allow', 'POST');
return res.status(405).json({
jsonrpc: '2.0',
error: { code: -32000, message: 'Method not allowed (stateless MCP endpoint — use POST)' },
id: null
});
}
const server = buildMcpServer({ baseUrl, notifyMutation });
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on('close', () => {
transport.close();
server.close();
});
await server.connect(transport);
// The app's global express.json() already parsed the body — pass it in.
await transport.handleRequest(req, res, req.body);
} catch (err) {
console.error('MCP request failed:', err);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: { code: -32603, message: 'Internal server error' },
id: null
});
}
}
};
app.post('/mcp', handler);
app.get('/mcp', handler);
app.delete('/mcp', handler);
}

View file

@ -1,70 +0,0 @@
// MCP server for 3D Gen Studio.
//
// Exposes the app's headless capabilities (projects, kanban cards, node graph,
// ComfyUI workflows, AI actions, mesh tools, assets) as MCP tools so any MCP
// client — Claude Desktop/Code, ChatGPT, local LLM stacks — can automate the
// app. Tools call the running backend over loopback HTTP (see client.js).
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createApiClient } from './client.js';
import { registerProjectTools } from './tools/projects.js';
import { registerCardTools } from './tools/cards.js';
import { registerGraphTools } from './tools/graph.js';
import { registerWorkflowTools } from './tools/workflows.js';
import { registerActionTools } from './tools/actions.js';
import { registerMeshToolTools } from './tools/meshTools.js';
import { registerAssetTools } from './tools/assets.js';
import { registerSettingsTools } from './tools/settings.js';
function readAppVersion() {
try {
const packagePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
return JSON.parse(fs.readFileSync(packagePath, 'utf8'))?.version || '0.0.0';
} catch {
return '0.0.0';
}
}
const APP_VERSION = readAppVersion();
const SERVER_INSTRUCTIONS = `3D Gen Studio automation server.
Typical flows:
- New pipeline: create_project (preset "graph") -> create_node / connect_nodes to lay out the pipeline -> run_workflow or generate_image / generate_mesh to produce assets.
- IMPORTANT (graph projects): always pass nodeId to run_workflow / generate_image / edit_image / generate_mesh so the results are DISPLAYED on that node. Without nodeId the assets are saved but no node shows them. The first result becomes the node's image/mesh; extra results become new nodes stacked below it.
- IMPORTANT ordering: connect_nodes to wire a node's input asset(s) BEFORE you run_workflow / edit_image / generate_mesh on it. The run reads the node's connected input at execution time — it feeds the workflow/API and decides whether the result is saved as an edit of the connected image / a version of the connected mesh. Running first and connecting afterwards is wrong: the run sees no input, so it uses none and saves a stray new root asset, and the late connection does not re-run or re-parent it. If you got the order wrong, delete the stray result, connect the inputs, then run again.
- ComfyUI: list_workflows for saved workflows and their parameters; import_workflow to add new ones (inspect_workflow first to discover inputs/outputs). run_workflow blocks with progress until the assets are ready. ComfyUI itself must be running (URL in get_settings).
- ComfyUI image/mesh (file) parameters are filled AUTOMATICALLY from the target node's wired inputs (matched by type) — so for a node whose inputs are connected, do NOT pass inputs for file parameters (no need to guess their ids); just connect_nodes then run_workflow with nodeId. Only set a file-parameter input to override a wired input or when nothing is connected. Set inputs only for non-file parameters (string/number/boolean) you want to change.
- When you DO pass an image/mesh (file) parameter in inputs (e.g. in a kanban project with no wiring), the value is just the asset's numeric id — nothing else. The SAME plain id works for a root asset, an edit, or a version (a background-removed image is an edit → pass that edit's own id, found in the children/edits tree from list_assets). Do NOT pass a file path/filename or a {assetId, editId} object; a bare id is correct.
- Parent linkage is AUTOMATIC — do NOT manage parentAssetId yourself. run_workflow saves its output under the source it was derived from (the image/mesh input matching the output type, wired or passed in inputs): an image output becomes an edit of that image, a mesh output a version of that mesh. edit_image already saves an edit of its imageSource, and run_mesh_tool saves a version of its assetId. So a re-texture (image+mesh in, mesh out) versions the input mesh, and a background-removal (image in, image out) edits the input image, with no parentAssetId needed. Only pass parentAssetId to override the inferred parent.
- Mesh processing: run_mesh_tool (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx) works on mesh assets; results save as asset versions.
- Seeing results: use view_asset to LOOK at a generated image (returns the actual image; for meshes it returns the thumbnail when available). Use download_asset to save any asset file to a local folder. Assets also carry direct download URLs in every response.
Note: interactive Mesh Editor sculpting/painting and Image Editor pixel edits are browser-only and not exposed here. If the app UI is open in a browser, it may need a refresh to show changes made through these tools.`;
// Build a fully-registered MCP server instance.
// baseUrl: origin of the running backend (defaults to loopback :3001).
// notifyMutation(projectId): optional hook fired after any mutation so the
// host process can push a refresh signal to open browser UIs.
export function buildMcpServer({ baseUrl, notifyMutation } = {}) {
const api = createApiClient(baseUrl);
const server = new McpServer(
{ name: '3d-gen-studio', version: APP_VERSION },
{ instructions: SERVER_INSTRUCTIONS }
);
const ctx = { api, notifyMutation: typeof notifyMutation === 'function' ? notifyMutation : () => {} };
registerProjectTools(server, ctx);
registerCardTools(server, ctx);
registerGraphTools(server, ctx);
registerWorkflowTools(server, ctx);
registerActionTools(server, ctx);
registerMeshToolTools(server, ctx);
registerAssetTools(server, ctx);
registerSettingsTools(server, ctx);
return server;
}

View file

@ -1,145 +0,0 @@
// Attach generated assets to a graph node, mirroring what GraphPage does after
// a run completes (applyNodeResult + spawnAdditionalResultNodes): the first
// result becomes the node's asset (that's what the node card displays); every
// additional result becomes a new node stacked below, wired to the same
// incoming reference edges so it can be used the same way.
const VERTICAL_STEP = 580; // collapsed node card height (~480px) + gap
const NODE_TYPE_BY_ASSET_TYPE = { image: 'Image', mesh: 'Mesh' };
// Decide where a generated result should land. Graph nodes are filled via
// `nodeId` (→ attachResultsToNode → the node's own asset); kanban cards via
// `cardId`. Clients sometimes pass a graph node id as `cardId`, which the kanban
// path can't attach to a node (and worse, silently creates an orphaned card), so
// promote such an id to a node target here. Returns the resolved target; a node
// target never also carries a kanban cardId.
//
// Safe because graph nodes and kanban cards are unique rows in one `Cards` table:
// an id that matches a graph node IS that node, not a card.
export async function resolveNodeTarget(api, projectId, { nodeId, cardId } = {}) {
if (nodeId !== undefined && nodeId !== null && nodeId !== '') {
return { nodeId: Number(nodeId), cardId: undefined };
}
if (cardId !== undefined && cardId !== null && cardId !== '' && projectId) {
const numeric = Number(cardId);
if (Number.isInteger(numeric)) {
const nodes = await api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []);
const isGraphNode = (Array.isArray(nodes) ? nodes : []).some(node => Number(node?.id) === numeric);
if (isGraphNode) {
return { nodeId: numeric, cardId: undefined };
}
}
}
return { nodeId: undefined, cardId };
}
// List the assets feeding a node's inputs: for each incoming edge whose source
// node holds an asset, the asset id + type (ordered by input connector so the
// result is deterministic). Lets a workflow run fill its image/mesh parameters
// from what the node is wired to — mirroring the GraphPage, which binds each
// file parameter to the connected input of the matching type — and pick the
// parent asset (image edit / mesh version) by matching the output type.
export async function resolveNodeInputAssets(api, projectId, nodeId) {
if (!nodeId || projectId === undefined || projectId === null) {
return [];
}
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []),
api.apiJson('GET', '/graph/connections', { query: { projectId } }).catch(() => [])
]);
const nodeList = Array.isArray(nodes) ? nodes : [];
const incomingEdges = (Array.isArray(connections) ? connections : [])
.filter(connection => Number(connection?.targetNodeId) === Number(nodeId))
.sort((a, b) => String(a?.inputId || '').localeCompare(String(b?.inputId || '')));
const inputs = [];
for (const edge of incomingEdges) {
const sourceNode = nodeList.find(node => Number(node?.id) === Number(edge.sourceNodeId));
const assetId = sourceNode?.assetId ?? sourceNode?.asset?.id ?? null;
if (assetId) {
inputs.push({
assetId: Number(assetId),
type: String(sourceNode?.asset?.type || '').toLowerCase() || null,
connectorId: edge.inputId || null
});
}
}
return inputs;
}
export async function attachResultsToNode(api, { projectId, nodeId, assets, metadata = {} }) {
const usable = (Array.isArray(assets) ? assets : [assets]).filter(asset =>
asset?.id && NODE_TYPE_BY_ASSET_TYPE[String(asset.type || '').toLowerCase()]
);
if (!nodeId || usable.length === 0) {
return { attached: false };
}
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }),
api.apiJson('GET', '/graph/connections', { query: { projectId } })
]);
const targetNode = (Array.isArray(nodes) ? nodes : []).find(node => Number(node?.id) === Number(nodeId));
if (!targetNode) {
throw new Error(`nodeId ${nodeId} not found in project ${projectId} — the generated assets are saved, use get_graph to find valid node ids.`);
}
const [firstAsset, ...extraAssets] = usable;
const updatedNode = await api.apiJson('PUT', `/graph/nodes/${nodeId}`, {
body: {
projectId,
assetId: firstAsset.id,
name: firstAsset.name || targetNode.name,
status: null,
progress: null,
metadata
}
});
// Additional results: new nodes below the target, re-wired to the target's
// incoming edges (same handles) so they carry the same references.
const incomingEdges = (Array.isArray(connections) ? connections : [])
.filter(connection => Number(connection?.targetNodeId) === Number(nodeId));
const baseX = Number(targetNode.xPos) || 0;
const baseY = Number(targetNode.yPos) || 0;
const additionalNodes = [];
for (let index = 0; index < extraAssets.length; index += 1) {
const asset = extraAssets[index];
const nodeTypeName = NODE_TYPE_BY_ASSET_TYPE[String(asset.type).toLowerCase()];
const createdNode = await api.apiJson('POST', '/graph/nodes', {
body: {
projectId,
nodeTypeName,
name: asset.name || nodeTypeName,
xPos: baseX,
yPos: baseY + ((index + 1) * VERTICAL_STEP),
assetId: asset.id,
metadata: { createdFromNodeId: Number(nodeId) }
}
});
additionalNodes.push(createdNode);
for (const edge of incomingEdges) {
await api.apiJson('POST', '/graph/connections', {
body: {
projectId,
sourceNodeId: edge.sourceNodeId,
targetNodeId: createdNode.id,
inputId: edge.inputId || 'input-0',
outputId: edge.outputId || 'output-0'
}
}).catch(() => null); // an unwirable edge shouldn't lose the result node
}
}
return {
attached: true,
node: updatedNode,
additionalNodeIds: additionalNodes.map(node => node.id)
};
}

View file

@ -1,24 +0,0 @@
#!/usr/bin/env node
// stdio entry point for MCP clients that spawn a process (e.g. Claude Desktop
// local servers). It is a thin bridge: tools still call the RUNNING 3D Gen
// Studio backend over loopback HTTP — this process never opens the database.
//
// Usage: node mcp/stdio.js (app must be running, default :3001)
// GENSTUDIO_URL=http://localhost:3001 node mcp/stdio.js
import process from 'node:process';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { buildMcpServer } from './index.js';
const baseUrl = (process.env.GENSTUDIO_URL || `http://127.0.0.1:${process.env.PORT || 3001}`).replace(/\/+$/, '');
try {
const res = await fetch(`${baseUrl}/api/projects`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.error(`3D Gen Studio is not reachable at ${baseUrl} (${err?.message || err}).`);
console.error('Start the app first (npm run dev, or launch the desktop app), then retry.');
process.exit(1);
}
const server = buildMcpServer({ baseUrl });
await server.connect(new StdioServerTransport());

View file

@ -1,439 +0,0 @@
import { z } from 'zod';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode, resolveNodeTarget } from '../nodeResults.js';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// Map the submit response of POST /api/meshes/generate to the matching
// provider poll endpoint and its request body.
function buildMeshPollRequest(submit, base) {
const provider = String(submit?.provider || '').toLowerCase();
if (provider.includes('tencent')) {
return {
path: '/meshes/generate/tencent/result',
body: { ...base, jobId: submit.jobId, region: submit.region }
};
}
if (provider.includes('tripo')) {
return { path: '/meshes/generate/tripo/result', body: { ...base, taskId: submit.taskId } };
}
if (provider.includes('hitem')) {
return { path: '/meshes/generate/hitem/result', body: { ...base, taskId: submit.taskId, jobId: submit.jobId } };
}
return null;
}
// Fixed mesh-generation provider ids the backend dispatches on
// (see src/utils/kanbanHelpers.js). Each typed tool below hardwires one, so a
// client only supplies parameters — no need to know the id.
const TENCENT_MESH_API_ID = 'tencent_meshgeneration';
const TRIPO_MESH_API_ID = 'tripo_meshgeneration';
const HITEM_MESH_API_ID = 'hitem_meshgeneration';
// Typed provider option shapes. These mirror the request-body keys and defaults
// that server.js reads for each provider (normalize{Tencent,Tripo,Hitem}
// MeshGenerationInput) 1:1, so a client sees every knob with its enum/range and
// default instead of an opaque options blob. Keep in sync with server.js and
// src/utils/kanbanHelpers.js.
const TENCENT_MESH_OPTIONS = {
region: z.enum(['ap-singapore', 'eu-frankfurt', 'na-siliconvalley']).describe('Tencent Cloud region — REQUIRED (no default).'),
modelVersion: z.enum(['3.0', '3.1']).default('3.0').describe('Hunyuan3D model version. LowPoly generation requires 3.0.'),
generationType: z.enum(['Normal', 'LowPoly', 'Geometry']).default('Normal').describe('Generation mode. LowPoly requires modelVersion 3.0.'),
polygonType: z.enum(['triangle', 'quadrilaterial']).default('triangle').describe('Polygon type — only applied when generationType is LowPoly.'),
faceCount: z.number().int().min(3000).max(1500000).default(500000).describe('Target face count (3000–1,500,000).'),
enablePBR: z.boolean().default(false).describe('Generate a PBR-ready mesh.')
};
const TRIPO_MESH_OPTIONS = {
modelVersion: z.enum(['v2.0-20240919', 'v2.5-20250123', 'v3.0-20250812', 'v3.1-20260211', 'Turbo-v1.0-20250506', 'P1-20260311']).default('v2.5-20250123').describe('Tripo model version. The P1 model ignores enableImageAutofix/textureAlignment/orientation/quad/smartLowPoly/generateParts/geometryQuality.'),
modelSeed: z.number().int().optional().describe('Geometry RNG seed (optional; omit for random).'),
enableImageAutofix: z.boolean().default(false).describe('Fix the input image before generation (ignored by P1).'),
faceLimit: z.number().int().min(1000).optional().describe('Max face count (>=1000; optional).'),
texture: z.boolean().default(true).describe('Generate texture maps. Incompatible with generateParts=true.'),
pbr: z.boolean().default(true).describe('Export a PBR model. Incompatible with generateParts=true.'),
textureSeed: z.number().int().optional().describe('Texture RNG seed (optional).'),
textureAlignment: z.enum(['original_image', 'geometry']).default('original_image').describe('Texture alignment (ignored by P1).'),
textureQuality: z.enum(['standard', 'detailed']).default('standard').describe('Texture quality.'),
autoSize: z.boolean().default(false).describe('Auto-fit scale to real-world size.'),
orientation: z.enum(['default', 'align_image']).default('default').describe('Output orientation (ignored by P1).'),
quad: z.boolean().default(false).describe('Generate a quad mesh (ignored by P1). Incompatible with generateParts=true.'),
smartLowPoly: z.boolean().default(false).describe('Optimize for low poly (ignored by P1).'),
generateParts: z.boolean().default(false).describe('Split into semantic parts (ignored by P1). Incompatible with texture/pbr/quad=true.'),
exportUv: z.boolean().default(true).describe('Include UVs in the output.'),
geometryQuality: z.enum(['standard', 'detailed']).default('standard').describe('Geometry quality — only applied for v3.0/v3.1 models.')
};
const HITEM_MESH_OPTIONS = {
hitemModel: z.enum(['hitem3dv1.5', 'hitem3dv2.0', 'hitem3dv2.1']).default('hitem3dv2.1').describe('Hitem3D model version.'),
hitemResolution: z.enum(['512', '1024', '1536', '1536pro', '1536fast']).optional().describe('Resolution. Valid per model: v1.5/v2.0 = 512/1024/1536/1536pro; v2.1 = 1536fast/1536pro. Invalid/omitted falls back to the model default.'),
hitemRequestType: z.union([z.literal(1), z.literal(3)]).default(3).describe('1 = mesh only, 3 = textured mesh.'),
hitemFace: z.number().int().min(100000).max(2000000).default(300000).describe('Target face count (100,000–2,000,000).'),
hitemPbr: z.boolean().default(false).describe('Generate a PBR-ready mesh.')
};
// Poll a provider's mesh-result endpoint until the job completes, errors, or the
// timeout elapses — streaming MCP progress and attaching results to a graph node
// on completion. The mesh is only persisted server-side once a poll sees the job
// complete, so this loop IS what finishes an async job. Returns the completed
// result, throws on provider error, or returns {status:'running'} on timeout.
async function pollMeshResult(api, notifyMutation, {
pollRequest, providerLabel, projectId, nodeId, selectedApi, timeoutSeconds, pollIntervalSeconds, pollFirst = false
}, reportProgress) {
const deadline = Date.now() + timeoutSeconds * 1000;
let lastStatus = null;
let first = true;
while (Date.now() < deadline) {
if (!(first && pollFirst)) await sleep(pollIntervalSeconds * 1000);
first = false;
lastStatus = await api.apiJson('POST', pollRequest.path, { body: pollRequest.body });
if (lastStatus?.status === 'completed') {
await reportProgress(100, 100, 'Mesh generation completed');
let nodeAttachment = null;
if (nodeId && Array.isArray(lastStatus.assets) && lastStatus.assets.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
assets: lastStatus.assets.map(asset => ({ ...asset, type: asset?.type || 'mesh' })),
metadata: { lastAction: 'mesh-generation', selectedApi }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...lastStatus, nodeAttachment } : lastStatus;
}
if (lastStatus?.status === 'error') {
throw new Error(lastStatus.error || 'Mesh generation failed');
}
const percent = Number(lastStatus?.progressPercent ?? lastStatus?.progress);
await reportProgress(
Number.isFinite(percent) ? percent : 50,
100,
`${providerLabel} status: ${lastStatus?.jobStatus || lastStatus?.taskStatus || lastStatus?.status || 'processing'}`
);
}
return { status: 'running', lastStatus };
}
// Core submit-and-poll runner shared by generate_mesh and the typed
// generate_mesh_{tencent,tripo,hitem} tools: submit the provider job, poll to
// completion (streaming MCP progress), attach results to a graph node when
// asked, and return the saved assets (or job info on timeout).
async function runMeshGeneration(api, notifyMutation, args, extra) {
const {
projectId, selectedApi, name, prompt, imageSource, nodeId, cardId, parentAssetId,
options = {}, timeoutSeconds = 1200, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
// Route a graph-node target to the node; never send a node id as a kanban
// cardId. targetNodeId gets the final mesh attached (via pollMeshResult).
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
const submit = await api.apiJson('POST', '/meshes/generate', {
body: {
projectId, selectedApi, name,
...(prompt ? { prompt } : {}),
...(imageSource !== undefined ? { imageSource } : {}),
...(kanbanCardId !== undefined && kanbanCardId !== null ? { cardId: kanbanCardId } : {}),
...(parentAssetId !== undefined ? { parentAssetId } : {}),
...options
}
});
notifyMutation(projectId);
const pollRequest = buildMeshPollRequest(submit, {
projectId,
name,
prompt: prompt || '',
cardId: submit?.cardId ?? kanbanCardId ?? null,
selectedApi,
parentAssetId: parentAssetId ?? null
});
// Custom APIs respond synchronously — nothing to poll.
if (!pollRequest) return submit;
await reportProgress(0, 100, `${submit.provider} job submitted (${submit.jobId || submit.taskId})`);
const outcome = await pollMeshResult(api, notifyMutation, {
pollRequest,
providerLabel: submit.provider,
projectId,
nodeId: targetNodeId,
selectedApi,
timeoutSeconds,
pollIntervalSeconds
}, reportProgress);
if (outcome.status === 'running') {
// Timed out with the job still on the provider. The mesh is NOT saved until a
// result poll sees completion, so hand back the job ids for get_mesh_result.
// Surface the resolved node target so a follow-up get_mesh_result can pass
// nodeId and still land the mesh on the intended node.
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. The provider keeps working, but the mesh is only saved once a result poll sees it finish — call get_mesh_result with the ids below to retrieve it when ready${targetNodeId ? ' (pass nodeId to attach it to the graph node)' : ''}. Do NOT re-run generation (that starts a new job).`,
provider: submit.provider,
selectedApi,
projectId,
name,
...(targetNodeId ? { nodeId: targetNodeId } : {}),
...(submit.jobId ? { jobId: submit.jobId } : {}),
...(submit.taskId ? { taskId: submit.taskId } : {}),
...(submit.region ? { region: submit.region } : {}),
...(submit.cardId ? { cardId: submit.cardId } : {}),
lastStatus: outcome.lastStatus
};
}
return outcome;
}
export function registerActionTools(server, { api, notifyMutation }) {
server.registerTool('generate_image', {
title: 'Generate image',
description: 'Generate an image with an external AI provider and save it as a project asset. selectedApi identifies the provider/model configured in Settings (e.g. Google/OpenAI image APIs or a custom_* API) — check get_settings for what is configured. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node).',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Provider/model id from Settings (e.g. "google_gemini", "openai_gpt_image", or a custom_* id)'),
prompt: z.string().min(1),
name: z.string().min(1).describe('Name for the generated asset/card'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing kanban card to attach the result to')
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
// A graph node id may arrive as nodeId or (mistakenly) as cardId — route it
// to the node and keep only a real kanban cardId in the request body.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
if (targetNodeId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets: [{ ...result, type: result?.type || 'image' }],
metadata: { lastAction: 'image-api' }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...result, nodeAttachment } : result;
}));
server.registerTool('edit_image', {
title: 'Edit image (AI)',
description: 'Edit an existing project image with an external AI provider (prompt-based edit). The result is saved as an edit of the source asset. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). For ComfyUI-based edits use run_workflow instead.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
imageSource: z.union([z.number().int(), z.string()]).describe('Source image: asset id or stored filePath'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to'),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
const savedEdits = Array.isArray(result?.savedEdits) ? result.savedEdits : [];
if (targetNodeId && savedEdits.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets: savedEdits.map(edit => ({ id: edit.id, name: edit.name || body.name, type: 'image' })),
metadata: { lastAction: 'image-edit-api' }
});
}
notifyMutation(projectId);
return nodeAttachment ? { ...result, nodeAttachment } : result;
}));
server.registerTool('generate_mesh', {
title: 'Generate 3D mesh',
description: 'Generate a 3D mesh from an image and/or prompt using Tencent Hunyuan, Tripo AI, or Hitem3D (selectedApi from Settings). Submits the job and polls the provider until the mesh is ready (streams MCP progress), then returns the saved mesh assets. In graph projects pass nodeId so the mesh is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). Takes minutes — on timeout returns the job info so it can be re-polled by calling this tool\'s sibling get-result flow or checking list_assets later.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Mesh provider id from Settings (Tencent / Tripo / Hitem3D / custom_*)'),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (Tencent/Tripo support text-to-3D)'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (required for Hitem3D)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
options: z.record(z.string(), z.any()).default({}).describe('Provider options, e.g. Tencent: region, modelVersion, enablePBR, faceCount, generationType, polygonType; Tripo: modelVersion, texture, pbr, quad, faceLimit, …. Prefer the dedicated generate_mesh_tencent / generate_mesh_tripo / generate_mesh_hitem tools, which document and validate every option.'),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, args, extra)));
server.registerTool('generate_mesh_tencent', {
title: 'Generate 3D mesh (Tencent Hunyuan3D)',
description: 'Generate a 3D mesh with Tencent Cloud Hunyuan3D and save it as a project asset. Provide EITHER prompt (text-to-3D) OR imageSource (image-to-3D), not both. Every Tencent parameter is exposed under `options` with its enum/range and default; region is required. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires Tencent Cloud credentials configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TENCENT_MESH_OPTIONS).describe('Tencent Hunyuan3D parameters (region is required).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: TENCENT_MESH_API_ID }, extra)));
server.registerTool('generate_mesh_tripo', {
title: 'Generate 3D mesh (Tripo AI)',
description: 'Generate a 3D mesh with Tripo AI and save it as a project asset. Provide EITHER prompt (text-to-3D) OR imageSource (image-to-3D), not both. Every Tripo parameter is exposed under `options` with its enum/range and default. Note: the P1 model ignores several options, and generateParts is incompatible with texture/pbr/quad. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires a Tripo AI API key configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TRIPO_MESH_OPTIONS).default({}).describe('Tripo AI parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: TRIPO_MESH_API_ID }, extra)));
server.registerTool('generate_mesh_hitem', {
title: 'Generate 3D mesh (Hitem3D)',
description: 'Generate a 3D mesh with Hitem3D from an image and save it as a project asset. imageSource is REQUIRED (Hitem3D is image-to-3D only). Every Hitem3D parameter is exposed under `options` with its enum/range and default. Submits and polls until ready (streams progress), returning the saved mesh assets (or job info on timeout). Requires Hitem3D access/secret keys configured in Settings.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1),
imageSource: z.union([z.number().int(), z.string()]).describe('Source image: asset id or stored filePath — REQUIRED.'),
options: z.object(HITEM_MESH_OPTIONS).default({}).describe('Hitem3D parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler((args, extra) => runMeshGeneration(api, notifyMutation, { ...args, selectedApi: HITEM_MESH_API_ID }, extra)));
server.registerTool('get_mesh_result', {
title: 'Get mesh generation result',
description: 'Retrieve and finish an async mesh-generation job (Tencent / Tripo / Hitem3D) — use this when the original generate_mesh* call returned {status:"running"} after timing out. The generated mesh is NOT saved to the project until a result poll sees the job complete, so this tool is required to recover a timed-out job (list_assets will not show it before then). It polls the provider until the mesh is ready, saves it, and returns the assets. Pass the ids from the timeout payload: Tripo/Hitem3D use taskId; Tencent uses jobId + region. It is safe to call repeatedly.',
inputSchema: {
projectId: z.number().int(),
name: z.string().min(1).describe('The same name the job was submitted with (used to save the asset)'),
provider: z.enum(['tencent', 'tripo', 'hitem']).describe('Provider the job was submitted to'),
taskId: z.string().optional().describe('Tripo AI / Hitem3D job id (from the timeout payload)'),
jobId: z.string().optional().describe('Tencent Cloud job id (from the timeout payload)'),
region: z.enum(['ap-singapore', 'eu-frankfurt', 'na-siliconvalley']).optional().describe('Tencent Cloud region the job was submitted in (required for Tencent)'),
selectedApi: z.string().optional().describe('Provider id override (defaults to the standard id for the provider)'),
prompt: z.string().optional().describe('Original prompt (stored in asset metadata; optional)'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Kanban card the job is attached to (from the timeout payload)'),
parentAssetId: z.number().int().optional().describe('Save the result as a version of this asset'),
nodeId: z.number().int().optional().describe('Graph node to attach the result to (graph projects)'),
timeoutSeconds: z.number().int().min(5).max(3600).default(600),
pollIntervalSeconds: z.number().int().min(3).max(120).default(10)
}
}, toolHandler(async (args, extra) => {
const {
projectId, name, provider, taskId, jobId, region, selectedApi, prompt,
cardId, parentAssetId, nodeId, timeoutSeconds = 600, pollIntervalSeconds = 10
} = args;
const reportProgress = createProgressReporter(extra);
const providerIds = { tencent: TENCENT_MESH_API_ID, tripo: TRIPO_MESH_API_ID, hitem: HITEM_MESH_API_ID };
const providerLabels = { tencent: 'Tencent Cloud', tripo: 'Tripo AI', hitem: 'Hitem3D' };
const effectiveSelectedApi = selectedApi || providerIds[provider];
const providerLabel = providerLabels[provider];
if (provider === 'tencent' && (!jobId || !region)) {
throw new Error('Tencent result lookup requires both jobId and region (from the timeout payload).');
}
if ((provider === 'tripo' || provider === 'hitem') && !taskId) {
throw new Error(`${providerLabel} result lookup requires taskId (from the timeout payload).`);
}
// buildMeshPollRequest keys off the provider label substring and the ids.
const pollRequest = buildMeshPollRequest(
{ provider: providerLabel, jobId, taskId, region },
{ projectId, name, prompt: prompt || '', cardId: cardId ?? null, selectedApi: effectiveSelectedApi, parentAssetId: parentAssetId ?? null }
);
if (!pollRequest) throw new Error(`Unknown mesh provider: ${provider}`);
const outcome = await pollMeshResult(api, notifyMutation, {
pollRequest,
providerLabel,
projectId,
nodeId,
selectedApi: effectiveSelectedApi,
timeoutSeconds,
pollIntervalSeconds,
pollFirst: true
}, reportProgress);
if (outcome.status === 'running') {
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. Call get_mesh_result again with the same ids to keep waiting.`,
provider: providerLabel,
projectId,
name,
...(jobId ? { jobId } : {}),
...(taskId ? { taskId } : {}),
...(region ? { region } : {}),
lastStatus: outcome.lastStatus
};
}
return outcome;
}));
server.registerTool('edit_mesh', {
title: 'Edit mesh (AI)',
description: 'Edit an existing project mesh through a configured custom mesh-edit API (selectedApi must be a custom_* id from Settings).',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]).describe('Source mesh: asset id or stored filePath'),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/edit', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
server.registerTool('texture_mesh', {
title: 'Texture mesh (AI)',
description: 'Texture an existing project mesh through a configured custom texturing API (selectedApi must be a custom_* id from Settings). For ComfyUI-based texturing use run_workflow.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/texture', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
server.registerTool('rig_mesh_api', {
title: 'Rig mesh (external API)',
description: 'Rig an existing project mesh through a configured custom rigging API (selectedApi must be a custom_* id from Settings). For the built-in local Auto Rig service use run_mesh_tool with operation "auto_rig".',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
prompt: z.string().min(1),
name: z.string().min(1),
meshSource: z.union([z.number().int(), z.string()]),
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, ...body }) => {
const result = await api.apiJson('POST', '/meshes/rigging', { body: { projectId, ...body } });
notifyMutation(projectId);
return result;
}));
}

View file

@ -1,240 +0,0 @@
import { z } from 'zod';
import { Buffer } from 'node:buffer';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, withAssetUrls, findProjectAsset } from '../client.js';
const MIME_BY_EXT = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.glb': 'model/gltf-binary',
'.gltf': 'model/gltf+json',
'.fbx': 'application/octet-stream',
'.obj': 'text/plain',
'.json': 'application/json'
};
// MCP image blocks Claude can actually see. Cap the raw size so the base64
// payload stays under typical model/image limits (~5 MB base64).
const VIEWABLE_IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
const MAX_VIEW_BYTES = 3.5 * 1024 * 1024;
function imageMimeOf(filePath) {
return MIME_BY_EXT[path.extname(String(filePath || '')).toLowerCase()] || null;
}
// Resolve what file a view/download request points at: an image asset's own
// file, or — for meshes — its thumbnail when viewing.
function resolveViewTarget(asset) {
const file = asset.filename || asset.filePath;
const mime = imageMimeOf(file);
if (mime && VIEWABLE_IMAGE_MIME.has(mime)) {
return { file, mime, note: null };
}
if (asset.thumbnail) {
const thumbMime = imageMimeOf(asset.thumbnail) || 'image/png';
return {
file: asset.thumbnail,
mime: thumbMime,
note: `This is the thumbnail preview of "${asset.name}" (${String(asset.type || 'asset')}), not the file itself. Use download_asset for the full file.`
};
}
return null;
}
export function registerAssetTools(server, { api, notifyMutation }) {
server.registerTool('list_assets', {
title: 'List project assets',
description: 'List a project\'s assets (images, meshes, workflows) with their version/edit trees and direct download URLs.',
inputSchema: {
projectId: z.number().int(),
includeChildren: z.boolean().optional().describe('Also return every project-linked edit/version as a top-level entry, not only nested under its root.')
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, includeChildren }) => {
const assets = await api.apiJson('GET', '/assets', {
query: { projectId, ...(includeChildren ? { includeChildren: 'true' } : {}) }
});
return (Array.isArray(assets) ? assets : []).map(asset => withAssetUrls(api, asset));
}));
server.registerTool('list_library_assets', {
title: 'List asset library',
description: 'List the global (project-independent) asset library: images, meshes, brushes, and saved workflows.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const assets = await api.apiJson('GET', '/assets/library');
if (Array.isArray(assets)) return assets.map(asset => withAssetUrls(api, asset));
if (assets && typeof assets === 'object') {
return Object.fromEntries(Object.entries(assets).map(([key, value]) => [
key,
Array.isArray(value) ? value.map(asset => withAssetUrls(api, asset)) : value
]));
}
return assets;
}));
server.registerTool('upload_asset', {
title: 'Upload asset',
description: 'Upload a local file (image or mesh) into a project as a new asset. The file is read from an absolute path on this machine.',
inputSchema: {
projectId: z.number().int(),
filePath: z.string().min(1).describe('Absolute local path of the file to upload'),
name: z.string().optional().describe('Asset name (defaults to the file name)'),
type: z.enum(['image', 'mesh']).optional().describe('Asset type (inferred from the file extension when omitted)'),
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, filePath, name, type, metadata }) => {
const buffer = await fs.readFile(filePath);
const fileName = path.basename(filePath);
const mime = MIME_BY_EXT[path.extname(fileName).toLowerCase()] || 'application/octet-stream';
const form = new FormData();
form.append('file', new Blob([buffer], { type: mime }), fileName);
form.append('projectId', String(projectId));
if (type) form.append('type', type);
if (name) form.append('name', name);
form.append('metadata', JSON.stringify(metadata || {}));
const asset = await api.apiForm('POST', '/assets/upload', form);
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
server.registerTool('link_asset', {
title: 'Link existing asset',
description: 'Attach an existing asset to a project. Pass assetId to link an asset that is already in the database — this works for a root asset AND for an image edit or mesh version (use the child id from list_assets). Pass filename instead to link a stored file from the asset library.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().optional().describe('Asset id to link — root, image edit or mesh version. Preferred over filename.'),
filename: z.string().min(1).optional().describe('Stored asset filename (from list_library_assets). Used when assetId is not given.'),
type: z.enum(['image', 'mesh']).default('image'),
name: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional(),
cascadeChildren: z.boolean().optional().describe('With assetId: also link every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, assetId, filename, type, name, metadata, cascadeChildren }) => {
if (assetId === undefined && !filename) {
throw new Error('Pass either assetId or filename.');
}
const asset = assetId !== undefined
? await api.apiJson('POST', `/projects/${projectId}/assets`, {
body: { assetId, ...(cascadeChildren ? { cascadeChildren: true } : {}) }
})
: await api.apiJson('POST', '/assets/link', {
body: { projectId, filename, type, ...(name ? { name } : {}), ...(metadata ? { metadata } : {}) }
});
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
server.registerTool('unlink_asset', {
title: 'Unlink asset from project',
description: 'Remove an asset from a project without deleting the file or the library record. Also removes it from any card/node it sits on in that project.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Asset id — root, image edit or mesh version'),
cascadeChildren: z.boolean().default(true).describe('Also unlink every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, assetId, cascadeChildren }) => {
const query = cascadeChildren === false ? { cascadeChildren: 'false' } : {};
const result = await api.apiJson('DELETE', `/projects/${projectId}/assets/${assetId}`, { query });
notifyMutation(projectId);
return result;
}));
server.registerTool('view_asset', {
title: 'View asset (image)',
description: 'SEE a project asset: returns the actual image so it can be visually inspected. For image assets returns the image itself; for meshes returns the thumbnail preview when one exists. Use this after generating images to check the results. For raw file access use download_asset.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Asset id (from list_assets or a generation result)')
},
annotations: { readOnlyHint: true }
}, async ({ projectId, assetId } = {}) => {
try {
const asset = await findProjectAsset(api, projectId, assetId);
const target = resolveViewTarget(asset);
if (!target) {
return {
isError: true,
content: [{
type: 'text',
text: `Asset ${assetId} ("${asset.name}", type ${asset.type}) has no viewable image or thumbnail. Use download_asset to save the file locally instead.`
}]
};
}
const buffer = await api.fetchAssetBuffer(target.file);
if (buffer.length > MAX_VIEW_BYTES) {
return {
isError: true,
content: [{
type: 'text',
text: `Asset file is too large to view inline (${(buffer.length / 1024 / 1024).toFixed(1)} MB). Use download_asset to save it locally, or open its URL: ${api.assetUrl(target.file)}`
}]
};
}
const info = {
id: asset.id,
name: asset.name,
type: asset.type,
width: asset.width || undefined,
height: asset.height || undefined,
url: api.assetUrl(asset.filename || asset.filePath)
};
return {
content: [
{ type: 'image', data: buffer.toString('base64'), mimeType: target.mime },
{ type: 'text', text: (target.note ? `${target.note}\n` : '') + JSON.stringify(info) }
]
};
} catch (err) {
return { isError: true, content: [{ type: 'text', text: String(err?.message || err) }] };
}
});
server.registerTool('download_asset', {
title: 'Download asset to disk',
description: 'Save a project asset\'s file (image, mesh, or workflow) into an absolute folder on the machine running 3D Gen Studio, so it can be opened or inspected from the filesystem.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int(),
folder: z.string().min(1).describe('Absolute output folder'),
fileName: z.string().optional().describe('Output file name (defaults to the asset\'s stored file name)')
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, assetId, folder, fileName }) => {
const asset = await findProjectAsset(api, projectId, assetId);
const assetFile = asset.filename || asset.filePath;
const buffer = await api.fetchAssetBuffer(assetFile);
// Reuse the server's export endpoint — it writes arbitrary files under an
// absolute folder with basename sanitization.
const form = new FormData();
form.append('folder', folder);
form.append('files', new Blob([buffer]), fileName || path.basename(String(assetFile)) || `asset-${assetId}`);
const written = await api.apiForm('POST', '/export/mesh', form);
return { ...written, sizeBytes: buffer.length, asset: { id: asset.id, name: asset.name, type: asset.type } };
}));
server.registerTool('delete_asset', {
title: 'Delete asset',
description: 'PERMANENTLY delete an asset from a project. Set confirm=true to proceed.',
inputSchema: {
assetId: z.number().int(),
confirm: z.boolean().describe('Must be true — confirms the permanent deletion')
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ assetId, confirm }) => {
if (confirm !== true) throw new Error('Refusing to delete: pass confirm=true to permanently delete this asset.');
await api.apiJson('DELETE', `/assets/${assetId}`);
notifyMutation(null);
return { deleted: true, assetId };
}));
}

View file

@ -1,125 +0,0 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
// Kanban columns are fixed (seeded in storage.js). Accept names, map to ids.
const KANBAN_COLUMNS = {
'images': 1,
'image edit': 2,
'mesh gen': 3,
'mesh edit': 4,
'texturing': 5,
'rigging': 6
};
function resolveColumnId(column) {
if (typeof column === 'number') return column;
const id = KANBAN_COLUMNS[String(column || '').trim().toLowerCase()];
if (!id) {
throw new Error(`Unknown kanban column "${column}". Valid columns: Images, Image Edit, Mesh Gen, Mesh Edit, Texturing, Rigging.`);
}
return id;
}
export function registerCardTools(server, { api, notifyMutation }) {
server.registerTool('list_cards', {
title: 'List cards',
description: 'List every card of a project. Kanban cards carry kanbanColumnId (1=Images, 2=Image Edit, 3=Mesh Gen, 4=Mesh Edit, 5=Texturing, 6=Rigging) and position; graph nodes appear here too with a non-null nodeTypeId (use get_graph for the graph view).',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => api.apiJson('GET', '/cards', { query: { projectId } })));
server.registerTool('move_card', {
title: 'Move kanban card',
description: 'Move a kanban card to a column ("Images", "Image Edit", "Mesh Gen", "Mesh Edit", "Texturing", "Rigging") at the given position (0-based).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int().describe('Card id (from list_cards)'),
column: z.string().describe('Target column name'),
position: z.number().int().min(0).describe('0-based position inside the column')
}
}, toolHandler(async ({ projectId, cardId, column, position }) => {
const result = await api.apiJson('PUT', '/cards/move', {
body: { projectId, cardId, kanbanColumnId: resolveColumnId(column), position }
});
notifyMutation(projectId);
return result;
}));
server.registerTool('delete_card', {
title: 'Delete card',
description: 'PERMANENTLY delete a card from a project (its linked assets remain).',
inputSchema: { projectId: z.number().int(), cardId: z.number().int() },
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, cardId }) => {
await api.apiJson('DELETE', `/cards/${cardId}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, cardId };
}));
server.registerTool('list_card_attributes', {
title: 'List card attributes',
description: 'List custom attributes attached to a project\'s cards, plus the available attribute types (1=Text, 2=Number).',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const [attributes, types] = await Promise.all([
api.apiJson('GET', '/card-attributes', { query: { projectId } }),
api.apiJson('GET', '/card-attributes/types')
]);
return { attributes, types };
}));
server.registerTool('create_card_attribute', {
title: 'Create card attribute',
description: 'Add a custom attribute to a card. attributeTypeId: 1=Text, 2=Number.',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
attributeTypeId: z.number().int().describe('1=Text, 2=Number'),
value: z.string().default('').describe('Attribute value (string; numbers as text)')
}
}, toolHandler(async ({ projectId, cardId, attributeTypeId, value }) => {
const attribute = await api.apiJson('POST', '/card-attributes', {
body: { projectId, cardId, attributeTypeId, attributeValue: value }
});
notifyMutation(projectId);
return attribute;
}));
server.registerTool('update_card_attribute', {
title: 'Update card attribute',
description: 'Update a card attribute (identified by cardId + position from list_card_attributes).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
position: z.number().int(),
attributeTypeId: z.number().int().optional(),
value: z.string().optional()
}
}, toolHandler(async ({ projectId, cardId, position, attributeTypeId, value }) => {
const attribute = await api.apiJson('PUT', `/card-attributes/${cardId}/${position}`, {
body: {
projectId,
...(attributeTypeId !== undefined ? { attributeTypeId } : {}),
...(value !== undefined ? { attributeValue: value } : {})
}
});
notifyMutation(projectId);
return attribute;
}));
server.registerTool('delete_card_attribute', {
title: 'Delete card attribute',
description: 'Delete a card attribute (identified by cardId + position).',
inputSchema: {
projectId: z.number().int(),
cardId: z.number().int(),
position: z.number().int()
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, cardId, position }) => {
await api.apiJson('DELETE', `/card-attributes/${cardId}/${position}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, cardId, position };
}));
}

View file

@ -1,140 +0,0 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
// Node types seeded in storage.js (NODE_TYPES). The friendly enum maps to the
// exact nodeTypeName the backend expects.
const NODE_KINDS = {
image: 'Image',
mesh: 'Mesh',
number: 'Number',
text: 'Text',
boolean: 'Boolean',
image_compare: 'Image Compare'
};
export function registerGraphTools(server, { api, notifyMutation }) {
server.registerTool('get_graph', {
title: 'Get graph',
description: 'Get a graph project\'s full node graph: nodes (with xPos/yPos, nodeTypeName, linked assetId, status, metadata) and connections (sourceNodeId/targetNodeId with React Flow handle ids like "output-0"/"input-0").',
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }),
api.apiJson('GET', '/graph/connections', { query: { projectId } })
]);
return { nodes, connections };
}));
server.registerTool('create_node', {
title: 'Create graph node',
description: 'Add a node to a graph project. Kinds: image (holds/generates images and runs ComfyUI/API actions), mesh (mesh generation/editing), number/text/boolean (value nodes feeding workflow parameters), image_compare. Value nodes store their value in metadata as {"outputType":"number|text|boolean","outputValue":<value>}.',
inputSchema: {
projectId: z.number().int(),
kind: z.enum(['image', 'mesh', 'number', 'text', 'boolean', 'image_compare']),
name: z.string().optional().describe('Node display name'),
x: z.number().default(0).describe('Canvas X position'),
y: z.number().default(0).describe('Canvas Y position'),
assetId: z.number().int().optional().describe('Existing asset to attach to the node'),
metadata: z.record(z.string(), z.any()).optional().describe('Node metadata JSON (e.g. outputType/outputValue for value nodes)')
}
}, toolHandler(async ({ projectId, kind, name, x, y, assetId, metadata }) => {
const node = await api.apiJson('POST', '/graph/nodes', {
body: {
projectId,
nodeTypeName: NODE_KINDS[kind],
name: name || NODE_KINDS[kind],
xPos: x,
yPos: y,
...(assetId !== undefined ? { assetId } : {}),
...(metadata !== undefined ? { metadata } : {})
}
});
notifyMutation(projectId);
return node;
}));
server.registerTool('update_node', {
title: 'Update graph node',
description: 'Update a graph node\'s name, linked asset, status, progress, or metadata.',
inputSchema: {
projectId: z.number().int(),
nodeId: z.number().int(),
name: z.string().optional(),
assetId: z.number().int().nullable().optional(),
status: z.string().optional(),
progress: z.number().optional(),
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, nodeId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
if (Object.keys(body).length === 0) throw new Error('Provide at least one field to update.');
const node = await api.apiJson('PUT', `/graph/nodes/${nodeId}`, { body: { projectId, ...body } });
notifyMutation(projectId);
return node;
}));
server.registerTool('move_node', {
title: 'Move graph node',
description: 'Move a graph node to a new canvas position.',
inputSchema: {
projectId: z.number().int(),
nodeId: z.number().int(),
x: z.number(),
y: z.number()
}
}, toolHandler(async ({ projectId, nodeId, x, y }) => {
const node = await api.apiJson('PUT', `/graph/nodes/${nodeId}/position`, {
body: { projectId, xPos: x, yPos: y }
});
notifyMutation(projectId);
return node;
}));
server.registerTool('delete_node', {
title: 'Delete graph node',
description: 'PERMANENTLY delete a graph node (its connections are removed with it; linked assets remain).',
inputSchema: { projectId: z.number().int(), nodeId: z.number().int() },
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, nodeId }) => {
await api.apiJson('DELETE', `/graph/nodes/${nodeId}`, { query: { projectId } });
notifyMutation(projectId);
return { deleted: true, nodeId };
}));
server.registerTool('connect_nodes', {
title: 'Connect graph nodes',
description: 'Create an edge from a source node\'s output handle to a target node\'s input handle. Handles default to "output-0"/"input-0"; connector types must be compatible (an image output feeds an image input, a number output feeds a number parameter, etc.).',
inputSchema: {
projectId: z.number().int(),
sourceNodeId: z.number().int(),
targetNodeId: z.number().int(),
outputId: z.string().default('output-0').describe('Source handle id'),
inputId: z.string().default('input-0').describe('Target handle id')
}
}, toolHandler(async ({ projectId, sourceNodeId, targetNodeId, outputId, inputId }) => {
const connection = await api.apiJson('POST', '/graph/connections', {
body: { projectId, sourceNodeId, targetNodeId, outputId, inputId }
});
notifyMutation(projectId);
return connection;
}));
server.registerTool('disconnect_nodes', {
title: 'Disconnect graph nodes',
description: 'Remove an edge between two graph nodes (all four identifiers must match the existing connection).',
inputSchema: {
projectId: z.number().int(),
sourceNodeId: z.number().int(),
targetNodeId: z.number().int(),
outputId: z.string().default('output-0'),
inputId: z.string().default('input-0')
}
}, toolHandler(async ({ projectId, sourceNodeId, targetNodeId, outputId, inputId }) => {
await api.apiJson('DELETE', '/graph/connections', {
query: { projectId, sourceNodeId, targetNodeId, outputId, inputId }
});
notifyMutation(projectId);
return { deleted: true };
}));
}

View file

@ -1,201 +0,0 @@
import { z } from 'zod';
import { Buffer } from 'node:buffer';
import path from 'node:path';
import { toolHandler, createProgressReporter, withAssetUrls, findProjectAsset } from '../client.js';
// Local mesh services behind the Node proxy. auto_uv/auto_retopo/repair/
// convert_fbx run on the Python mesh-tools service (:8200), auto_rig on the
// rigging service (:8300), optimize on the bundled gltfpack binary.
const OPERATIONS = {
auto_uv: { path: '/meshes/auto-uv', sse: true },
auto_retopo: { path: '/meshes/auto-retopo', sse: true },
repair: { path: '/meshes/repair', sse: true },
convert_fbx: { path: '/meshes/convert', sse: true, format: 'fbx' },
auto_rig: { path: '/meshes/rig', sse: true },
optimize: { path: '/meshes/optimize', sse: false }
};
// Typed option shapes for the parameter-heavy tools. These mirror the Python
// service's Pydantic models 1:1 (python-server/app/schemas.py) — same keys,
// ranges, and defaults — so an MCP client sees every knob with its bounds and
// default instead of an opaque options blob. Keep them in sync with schemas.py
// and the panel defaults in src/pages/MeshEditorPage.jsx.
const AUTO_UV_OPTIONS = {
// segmentation
max_cone_deg: z.number().min(1).max(180).default(50).describe('Normal-cone cap (deg). Higher = fewer, more distorted charts.'),
sharp_weight: z.number().min(0).max(1).default(0.35).describe('How strongly sharp edges attract seams.'),
min_faces: z.number().int().min(1).max(100000).default(20).describe('Charts smaller than this are dissolved into neighbours.'),
min_area_frac: z.number().min(0).max(1).default(0.004).describe('Min chart area as a fraction of total surface area.'),
fold_cap_deg: z.number().min(1).max(180).default(88).describe('Dihedral fold cap that forces a seam.'),
// refinement (LSCM-validated chart merge)
refine: z.boolean().default(true).describe('Run the LSCM-validated chart-merge pass (off = faster, more charts).'),
refine_target_faces: z.number().int().min(1).max(100000).default(80).describe('Charts below this face count are merge candidates.'),
refine_ad_thresh: z.number().min(1).max(10).default(1.32).describe('Max angle-distortion ratio a merge may introduce.'),
// parameterization
method: z.enum(['auto', 'lscm', 'arap', 'planar']).default('auto').describe('Per-chart flattening method.'),
arap_iters: z.number().int().min(0).max(100).default(4).describe('As-rigid-as-possible iterations (0 = LSCM/planar only).'),
// packing
resolution: z.number().int().min(64).max(8192).default(1024).describe('Atlas resolution used to size padding (px). Typical values: 256/512/1024/2048/4096/8192.'),
padding_texels: z.number().int().min(0).max(64).default(4).describe('Inter-island padding in texels.'),
// topology repair
weld: z.boolean().default(true).describe('Proximity-weld coincident verts before unwrapping (stitches shattered shells).'),
weld_tol_frac: z.number().min(0).max(1).default(0.1).describe('Weld tolerance as a fraction of median edge length.')
};
const AUTO_RETOPO_OPTIONS = {
// target
target_faces: z.number().int().min(50).max(5_000_000).default(6000).describe('Approximate face budget of the output.'),
quads: z.boolean().default(false).describe('Convert the final mesh to quad-dominant (reported in metrics; GLB stays triangulated).'),
// base generation (watertight shell)
watertight: z.boolean().default(true).describe('Build a unified voxel shell (robust to messy input) vs. remesh the surface directly (keeps open boundaries).'),
shell_resolution: z.number().int().min(16).max(1024).default(256).describe('Voxel grid cells along the longest bbox axis (watertight only).'),
shell_close_iter: z.number().int().min(0).max(20).default(1).describe('Morphological closing iterations to bridge cracks (watertight only).'),
shell_smooth: z.number().min(0).max(5).default(1.4).describe('Gaussian sigma (voxels) on the SDF; kills voxel ripple, lower = crisper (watertight only).'),
shell_taubin: z.number().int().min(0).max(100).default(10).describe('Taubin polish steps on the dense shell, 0 disables (watertight only).'),
shell_samples_per_pitch: z.number().min(1).max(8).default(2).describe('Surface sampling density; >=2 guarantees gap-free voxel coverage (watertight only).'),
max_memory_gb: z.number().min(0).max(128).default(4).describe('Auto-lower shell resolution to fit this budget, 0 disables (watertight only).'),
// clean topology (field-adaptive isotropic remeshing)
adaptive: z.boolean().default(true).describe('Curvature-adaptive density (more faces where the surface bends).'),
remesh_iters: z.number().int().min(1).max(100).default(10).describe('Isotropic remesh iterations.'),
feature_deg: z.number().min(0).max(180).default(30).describe('Crease angle preserved as a feature.'),
calibrate_passes: z.number().int().min(0).max(10).default(1).describe('Rough edge-length correction passes.'),
// hard-surface / detail preservation
preserve_features: z.boolean().default(false).describe('Hard-surface mode: keep sharp creases crisp, skip smoothing/projection.'),
feature_angle: z.number().min(0).max(180).default(25).describe('Crease angle (deg) treated as a hard edge when preserve_features is on.'),
// silhouette projection
project: z.boolean().default(true).describe('Project the remesh back onto the original surface.'),
project_iters: z.number().int().min(0).max(100).default(10).describe('Projection iterations.'),
project_clamp: z.number().min(0).max(10).default(1.5).describe('Max per-vertex move as a multiple of local edge length.'),
relax_strength: z.number().min(0).max(1).default(0.4).describe('Tangential relaxation factor per iteration.'),
// compute backend (shell stage only)
device: z.enum(['auto', 'cpu', 'cuda']).default('auto').describe("Shell-stage compute backend: 'auto' uses an NVIDIA GPU (CuPy) when available and falls back to CPU; 'cpu' forces CPU; 'cuda' forces GPU (errors if unavailable). Other stages always run on CPU."),
// misc
seed: z.number().int().min(0).default(0).describe('RNG seed for reproducibility.')
};
// Core runner shared by run_mesh_tool and the typed auto_uv_mesh/auto_retopo_mesh
// tools: load the asset, run the operation (SSE-streamed or synchronous), and
// save the result as a new version (or replace / write FBX to disk).
async function runMeshOperation(api, notifyMutation, args, extra) {
const { projectId, assetId, operation, options = {}, saveMode = 'version', name, targetFolder } = args;
const op = OPERATIONS[operation];
const reportProgress = createProgressReporter(extra);
const asset = await findProjectAsset(api, projectId, assetId);
await reportProgress(5, 100, `Loaded ${asset.name || 'mesh'} — running ${operation}`);
const assetFile = asset.filename || asset.filePath;
const meshBuffer = await api.fetchAssetBuffer(assetFile);
const form = new FormData();
const fileName = path.basename(String(assetFile)) || 'mesh.glb';
form.append('meshFile', new Blob([meshBuffer], { type: 'model/gltf-binary' }), fileName);
form.append('options', JSON.stringify(options));
let resultBuffer;
let stats;
let outFormat = 'glb';
if (op.sse) {
form.append('format', op.format || 'glb');
const done = await api.apiFormSse(op.path, form, evt => {
const frac = Number(evt?.frac);
reportProgress(
Number.isFinite(frac) ? Math.round(5 + frac * 85) : 50,
100,
evt?.message || evt?.stage || `Running ${operation}`
);
});
resultBuffer = Buffer.from(done.mesh_b64, 'base64');
stats = done.stats || null;
outFormat = done.format || op.format || 'glb';
} else {
const done = await api.apiForm('POST', op.path, form);
resultBuffer = Buffer.from(done.mesh_b64, 'base64');
stats = done.stats || null;
}
await reportProgress(92, 100, 'Saving result');
// FBX conversion is an export, not an editable asset — write it to disk.
if (operation === 'convert_fbx') {
if (!targetFolder) throw new Error('convert_fbx requires targetFolder (absolute folder to write the .fbx into).');
const exportForm = new FormData();
const fbxName = `${(name || asset.name || 'mesh').replace(/\.[^.]*$/, '')}.fbx`;
exportForm.append('folder', targetFolder);
exportForm.append('files', new Blob([resultBuffer]), fbxName);
const written = await api.apiForm('POST', '/export/mesh', exportForm);
await reportProgress(100, 100, 'FBX written');
return { operation, stats, ...written };
}
const saveForm = new FormData();
saveForm.append('assetId', String(asset.id));
saveForm.append('filePath', '');
saveForm.append('name', name || `${asset.name || 'Mesh'} (${operation.replace(/_/g, ' ')})`);
saveForm.append('saveMode', saveMode);
saveForm.append('meshFile', new Blob([resultBuffer], { type: 'model/gltf-binary' }), `mesh.${outFormat}`);
const savedAsset = await api.apiForm('POST', '/meshes/editor/save', saveForm);
notifyMutation(projectId);
await reportProgress(100, 100, 'Done');
return { operation, stats, savedAsset: withAssetUrls(api, savedAsset) };
}
export function registerMeshToolTools(server, { api, notifyMutation }) {
server.registerTool('run_mesh_tool', {
title: 'Run mesh tool',
description: 'Run a local mesh-processing tool on a project mesh asset and save the result. Operations: auto_uv (UV unwrap), auto_retopo (retopology), repair (fix non-manifold geometry), auto_rig (skeleton + skin weights via the rigging service), optimize (gltfpack simplification; options.simplify_ratio 0..1), convert_fbx (GLB→FBX via headless Blender; requires targetFolder, options.preset unity|unreal|generic). NOTE: auto_uv and auto_retopo have many parameters — prefer the dedicated auto_uv_mesh and auto_retopo_mesh tools, which document and validate every option; here their options ride along as a free-form object and unset keys fall back to service defaults. Requires the Python mesh-tools service (auto_uv/auto_retopo/repair/convert_fbx) or rigging service (auto_rig) to be running — in the desktop app start them from Settings. Results save as a new version of the asset by default.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
operation: z.enum(['auto_uv', 'auto_retopo', 'repair', 'auto_rig', 'optimize', 'convert_fbx']),
options: z.record(z.string(), z.any()).default({}).describe('Operation options (e.g. {simplify_ratio: 0.5} for optimize, {preset: "unity"} for convert_fbx). For auto_uv/auto_retopo see the dedicated tools for the full option list.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save the processed mesh as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result'),
targetFolder: z.string().optional().describe('convert_fbx only: absolute folder to write the .fbx file into')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, args, extra)));
server.registerTool('auto_uv_mesh', {
title: 'Auto UV unwrap',
description: 'UV-unwrap a project mesh asset with the Python mesh-tools service (:8200) and save the result as a new version. Every autouv.unwrap() parameter is exposed under `options` with its range and default — set the ones you need; omitted keys use the documented default. Streams progress. Requires the Python mesh-tools service running (start it from Settings in the desktop app).',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
options: z.object(AUTO_UV_OPTIONS).default({}).describe('Auto UV unwrap parameters. Any subset may be set; unset keys use their default.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, { ...args, operation: 'auto_uv' }, extra)));
server.registerTool('auto_retopo_mesh', {
title: 'Auto retopology',
description: 'Rebuild clean topology on a project mesh asset with the Python mesh-tools service (:8200) and save the result as a new version. Every autoretopo.RetopoConfig field is exposed under `options` with its range and default — set the ones you need; omitted keys use the documented default. The shell_* options apply only when watertight=true. Streams progress. Requires the Python mesh-tools service running (start it from Settings in the desktop app).',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Mesh asset id (from list_assets)'),
options: z.object(AUTO_RETOPO_OPTIONS).default({}).describe('Auto retopology parameters. Any subset may be set; unset keys use their default.'),
saveMode: z.enum(['version', 'replace']).default('version').describe('Save as a new version (default) or replace the asset file'),
name: z.string().optional().describe('Name for the saved result')
}
}, toolHandler((args, extra) => runMeshOperation(api, notifyMutation, { ...args, operation: 'auto_retopo' }, extra)));
server.registerTool('export_mesh', {
title: 'Export mesh file',
description: 'Copy a project mesh asset\'s file (GLB passthrough) into an absolute folder on this machine. For engine FBX exports (Unity/Unreal) use run_mesh_tool with operation "convert_fbx" instead.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int(),
folder: z.string().min(1).describe('Absolute output folder'),
fileName: z.string().optional().describe('Output file name (defaults to the asset\'s stored file name)')
}
}, toolHandler(async ({ projectId, assetId, folder, fileName }) => {
const asset = await findProjectAsset(api, projectId, assetId);
const assetFile = asset.filename || asset.filePath;
const buffer = await api.fetchAssetBuffer(assetFile);
const form = new FormData();
form.append('folder', folder);
form.append('files', new Blob([buffer]), fileName || path.basename(String(assetFile)) || 'mesh.glb');
return api.apiForm('POST', '/export/mesh', form);
}));
}

View file

@ -1,93 +0,0 @@
import { z } from 'zod';
import { toolHandler } from '../client.js';
export function registerProjectTools(server, { api, notifyMutation }) {
server.registerTool('list_projects', {
title: 'List projects',
description: 'List every 3D Gen Studio project (id, name, description, preset "graph" or kanban, creation date, status).',
annotations: { readOnlyHint: true }
}, toolHandler(async () => api.apiJson('GET', '/projects')));
server.registerTool('get_project', {
title: 'Get project',
description: 'Get one project by id, including its preset (graph vs kanban board) and saved graph viewport.',
inputSchema: { projectId: z.number().int().describe('Project id') },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => api.apiJson('GET', `/projects/${projectId}`)));
server.registerTool('create_project', {
title: 'Create project',
description: 'Create a new project. preset "graph" creates a node-graph project (Graph page); "kanban" creates a pipeline board with the fixed columns Images, Image Edit, Mesh Gen, Mesh Edit, Texturing, Rigging.',
inputSchema: {
name: z.string().min(1).describe('Project name'),
description: z.string().optional().describe('Optional project description'),
preset: z.enum(['graph', 'kanban']).default('graph').describe('Project type: node graph or kanban board')
}
}, toolHandler(async ({ name, description, preset }) => {
// The UI stores presets in title case ('Graph' / 'Kanban') and keys its
// preview images by that exact string — match it.
const project = await api.apiJson('POST', '/projects', {
body: { name, description: description || '', preset: preset === 'kanban' ? 'Kanban' : 'Graph' }
});
notifyMutation(project?.id);
return project;
}));
server.registerTool('update_project', {
title: 'Update project',
description: 'Update a project\'s name, description, or status.',
inputSchema: {
projectId: z.number().int(),
name: z.string().optional(),
description: z.string().optional(),
status: z.string().optional()
}
}, toolHandler(async ({ projectId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
if (Object.keys(body).length === 0) throw new Error('Provide at least one field to update (name, description, status).');
const project = await api.apiJson('PUT', `/projects/${projectId}`, { body });
notifyMutation(projectId);
return project;
}));
server.registerTool('delete_project', {
title: 'Delete project',
description: 'PERMANENTLY delete a project. Set confirm=true to proceed. With deleteAssets=true the project\'s asset files are removed from disk as well.',
inputSchema: {
projectId: z.number().int(),
confirm: z.boolean().describe('Must be true — confirms the permanent deletion'),
deleteAssets: z.boolean().default(false).describe('Also delete the project\'s asset files from disk')
},
annotations: { destructiveHint: true }
}, toolHandler(async ({ projectId, confirm, deleteAssets }) => {
if (confirm !== true) throw new Error('Refusing to delete: pass confirm=true to permanently delete this project.');
await api.apiJson('DELETE', `/projects/${projectId}`, { query: deleteAssets ? { deleteAssets: 'true' } : {} });
notifyMutation(projectId);
return { deleted: true, projectId };
}));
server.registerTool('export_project', {
title: 'Export project',
description: 'Export a project as a portable .3dgp bundle folder (manifest + all asset files) under the given absolute destination folder. Returns the created bundle path.',
inputSchema: {
projectId: z.number().int(),
folder: z.string().min(1).describe('Absolute destination folder on this machine (a subfolder named after the project is created inside it)'),
name: z.string().optional().describe('Optional bundle name override')
}
}, toolHandler(async ({ projectId, folder, name }) =>
api.apiJson('POST', `/projects/${projectId}/export`, { body: { folder, name: name || '' } })
));
server.registerTool('import_project', {
title: 'Import project',
description: 'Import a project from a previously exported bundle folder (must contain exactly one .3dgp manifest). Returns the created project.',
inputSchema: {
folder: z.string().min(1).describe('Absolute path of the exported bundle folder'),
name: z.string().optional().describe('Optional name for the imported project')
}
}, toolHandler(async ({ folder, name }) => {
const project = await api.apiJson('POST', '/projects/import', { body: { folder, name: name || '' } });
notifyMutation(project?.id);
return project;
}));
}

View file

@ -1,33 +0,0 @@
import { toolHandler } from '../client.js';
const SECRET_KEY_PATTERN = /(api[-_]?key|secret|token|password|credential|authorization)/i;
// Recursively replace secret-looking string values so API keys configured in
// Settings never leave the machine through an MCP client.
function redactSecrets(value) {
if (Array.isArray(value)) return value.map(redactSecrets);
if (value && typeof value === 'object') {
const out = {};
for (const [key, item] of Object.entries(value)) {
out[key] = SECRET_KEY_PATTERN.test(key) && typeof item === 'string' && item.length > 0
? '***redacted***'
: redactSecrets(item);
}
return out;
}
return value;
}
export function registerSettingsTools(server, { api }) {
server.registerTool('get_settings', {
title: 'Get settings (redacted)',
description: 'Read the app settings — which AI providers and custom APIs are configured (their ids for selectedApi), service URLs (ComfyUI, mesh tools, rigging), and preferences. All API keys and secrets are redacted.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => redactSecrets(await api.apiJson('GET', '/settings'))));
server.registerTool('get_system_stats', {
title: 'Get system stats',
description: 'Live CPU, RAM, and GPU usage of the machine running 3D Gen Studio.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => api.apiJson('GET', '/system/stats')));
}

View file

@ -1,305 +0,0 @@
import { z } from 'zod';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode, resolveNodeTarget, resolveNodeInputAssets } from '../nodeResults.js';
const FILE_PARAM_TYPES = ['image', 'mesh', 'video'];
// Strip the raw graph JSON from workflow records so list responses stay small.
function summarizeWorkflow(workflow) {
if (!workflow || typeof workflow !== 'object') return workflow;
const { workflowJson: _workflowJson, ...rest } = workflow;
return rest;
}
async function resolveWorkflowJson({ workflowJson, filePath }) {
if (workflowJson !== undefined && workflowJson !== null) {
return typeof workflowJson === 'string' ? JSON.parse(workflowJson) : workflowJson;
}
if (filePath) {
const raw = await fs.readFile(filePath, 'utf8');
const parsed = JSON.parse(raw);
// Accept both raw ComfyUI API graphs and .3dgw share bundles.
if (parsed?.type === '3dgenstudio-workflow' && parsed.workflowJson) return parsed;
return parsed;
}
throw new Error('Provide either workflowJson (the ComfyUI API-format graph) or filePath (a local .json/.3dgw file).');
}
export function registerWorkflowTools(server, { api, notifyMutation }) {
server.registerTool('list_workflows', {
title: 'List ComfyUI workflows',
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue, plus enums when the parameter only accepts a fixed list of values) and output nodes.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const workflows = await api.apiJson('GET', '/library/comfy-workflows');
return (Array.isArray(workflows) ? workflows : []).map(summarizeWorkflow);
}));
server.registerTool('inspect_workflow', {
title: 'Inspect ComfyUI workflow JSON',
description: 'Parse a ComfyUI workflow graph (API format) without saving it. Returns candidate inputs (every literal node input, id "{nodeId}.{inputKey}") and terminal output nodes — use these to choose parameters/outputs for import_workflow. Accepts inline JSON or a local file path (.json or .3dgw share bundle).',
inputSchema: {
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
filePath: z.string().optional().describe('Absolute path to a local workflow .json or .3dgw file')
},
annotations: { readOnlyHint: true }
}, toolHandler(async (args) => {
const resolved = await resolveWorkflowJson(args);
const graph = resolved?.type === '3dgenstudio-workflow' ? resolved.workflowJson : resolved;
const parsed = await api.apiJson('POST', '/library/comfy-workflows/inspect', { body: { workflowJson: graph } });
if (resolved?.type === '3dgenstudio-workflow') {
parsed.bundledConfiguration = { parameters: resolved.parameters || [], outputs: resolved.outputs || [] };
}
return parsed;
}));
server.registerTool('import_workflow', {
title: 'Import ComfyUI workflow',
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean, enums?: allowed values for a string/number parameter}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
inputSchema: {
name: z.string().min(1).describe('Workflow name in the library'),
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
filePath: z.string().optional().describe('Absolute path to a local workflow .json or .3dgw file'),
parameters: z.array(z.object({
id: z.string(),
name: z.string().optional(),
valueType: z.string().optional(),
enums: z.array(z.union([z.string(), z.number()])).optional()
.describe('Allowed values for a string/number parameter — the app renders it as a dropdown limited to this list. Ignored for other value types.')
})).optional().describe('Inputs to expose as parameters (ids from inspect_workflow)'),
outputs: z.array(z.object({
nodeId: z.string(),
name: z.string().optional(),
valueType: z.string().optional()
})).optional().describe('Output nodes to save results from (nodeIds from inspect_workflow)')
}
}, toolHandler(async ({ name, parameters, outputs, ...source }) => {
const resolved = await resolveWorkflowJson(source);
const isBundle = resolved?.type === '3dgenstudio-workflow';
const graph = isBundle ? resolved.workflowJson : resolved;
const effectiveParameters = parameters ?? (isBundle ? resolved.parameters : undefined) ?? [];
const effectiveOutputs = outputs ?? (isBundle ? resolved.outputs : undefined) ?? [];
const workflow = await api.apiJson('POST', '/library/comfy-workflows', {
body: { name, workflowJson: graph, parameters: effectiveParameters, outputs: effectiveOutputs }
});
notifyMutation(null);
return summarizeWorkflow(workflow);
}));
server.registerTool('update_workflow', {
title: 'Update ComfyUI workflow',
description: 'Update a saved workflow: rename it, change its parameter/output selection (including parameter default values), or replace the graph JSON.',
inputSchema: {
workflowId: z.number().int(),
name: z.string().optional(),
parameters: z.array(z.record(z.string(), z.any())).optional(),
outputs: z.array(z.record(z.string(), z.any())).optional(),
workflowJson: z.any().optional()
}
}, toolHandler(async ({ workflowId, ...updates }) => {
const body = Object.fromEntries(Object.entries(updates).filter(([, v]) => v !== undefined));
const workflow = await api.apiJson('PUT', `/library/comfy-workflows/${workflowId}`, { body });
notifyMutation(null);
return summarizeWorkflow(workflow);
}));
server.registerTool('run_workflow', {
title: 'Run ComfyUI workflow',
description: 'Execute a saved ComfyUI workflow and wait for the generated assets (streams MCP progress notifications). inputs maps parameter id -> value; for image/mesh parameters pass a project asset id (number) as the value, or use fileInputs to upload a local file. IMPORTANT for graph projects: pass nodeId (a graph node from get_graph/create_node) so the results are displayed on that node — the first result becomes the node\'s asset, additional results become new nodes stacked below it. nodeId is the ONLY way to fill a graph node; cardId is for kanban cards. (If you pass a graph node id as cardId it is auto-attached to that node, not turned into a card.) Wiring: the target node\'s connected input assets automatically fill the workflow\'s image/mesh parameters (matched by type), so you normally do NOT set inputs for file parameters — just connect_nodes to wire the source image/mesh, then run with nodeId. Only pass inputs for file parameters to override a wired input or when the node has no connection. Requires ComfyUI to be running (configured in Settings). On timeout returns {status:"running", promptId} — poll with get_run_status.',
inputSchema: {
workflowId: z.number().int().describe('Saved workflow id (from list_workflows)'),
projectId: z.number().int().optional().describe('Project to attach results to (required unless persistGeneratedAssets=false)'),
inputs: z.record(z.string(), z.any()).default({}).describe('Parameter id -> value. For an image/mesh parameter pass the asset\'s numeric id (from list_assets / a generation result) — this is ALL you need. The SAME plain id works for a root asset, an edit, or a version (e.g. a background-removed image is an edit — pass that edit\'s own id). Do NOT pass a file path/filename, and do NOT pass a {assetId, editId} object — a bare number is correct. Non-file parameters take their literal value (string/number/boolean).'),
fileInputs: z.record(z.string(), z.string()).optional().describe('Parameter id -> absolute local file path to upload for image/mesh/video parameters'),
nodeId: z.number().int().optional().describe('Graph node to attach the results to (graph projects) — the correct way to fill a node; without it the generated assets are saved but no node displays them'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing KANBAN card to attach the run to (kanban projects). For graph nodes use nodeId — a graph node id passed here is auto-routed to that node'),
name: z.string().optional().describe('Name for the generated asset(s)'),
parentAssetId: z.number().int().optional().describe('Save results under this asset: a mesh output becomes a version of it, an image output an edit of it (the parent must match the output type, else a new root asset is created). USUALLY LEAVE UNSET — it is inferred automatically from the source the output was derived from: the workflow file (image/mesh) input matching the output type, whether that input came from the target node\'s wiring or was passed in `inputs`. Set this only to override that inference (e.g. attach to a different asset).'),
persistProcessingCard: z.boolean().optional(),
persistGeneratedAssets: z.boolean().optional(),
timeoutSeconds: z.number().int().min(5).max(3600).default(600)
}
}, toolHandler(async (args, extra) => {
const {
workflowId, projectId, inputs = {}, fileInputs, nodeId, cardId, name,
parentAssetId, persistProcessingCard, persistGeneratedAssets, timeoutSeconds = 600
} = args;
const reportProgress = createProgressReporter(extra);
const promptId = randomUUID();
// Route a graph-node target to the node (via nodeId), even if the caller
// passed the node id as cardId. targetNodeId gets the result attached;
// kanbanCardId is only forwarded to the server when it's a real kanban card.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
// Mirror the GraphPage: use what the target node is wired to. Its connected
// input assets fill the workflow's image/mesh parameters (by matching type) so
// the caller doesn't have to hand-map parameter ids, and — when the caller
// didn't pin one — set the parent so the output is saved as an edit of a
// connected image / a version of a connected mesh (parent matches output type).
const nodeInputAssets = (targetNodeId && projectId)
? await resolveNodeInputAssets(api, projectId, targetNodeId)
: [];
// Fetch the workflow definition to know its file parameters and output type.
const workflowDef = (await api.apiJson('GET', '/library/comfy-workflows').catch(() => []))
.find?.(item => Number(item?.id) === Number(workflowId)) || null;
const fileParams = (workflowDef?.parameters || [])
.map(parameter => ({ id: parameter.id, type: String(parameter.valueType || '').toLowerCase() }))
.filter(parameter => FILE_PARAM_TYPES.includes(parameter.type));
// Auto-fill each unset image/mesh/video parameter from a connected input of
// the matching type (each connected asset used at most once). Explicit `inputs`
// and `fileInputs` always win over an auto-filled value.
const autoInputs = {};
if (nodeInputAssets.length > 0 && fileParams.length > 0) {
const available = nodeInputAssets.map(asset => ({ ...asset, used: false }));
for (const parameter of fileParams) {
const explicitlySet = (inputs[parameter.id] !== undefined && inputs[parameter.id] !== null)
|| (fileInputs && fileInputs[parameter.id]);
if (explicitlySet) continue;
const match = available.find(asset => !asset.used && asset.type === parameter.type);
if (match) {
autoInputs[parameter.id] = `asset:${match.assetId}`;
match.used = true;
}
}
}
// Unless the caller pinned a parent, let the server save the output under the
// source it was derived from: it matches each output to a resolved image/mesh
// input of the same type (from wiring or `inputs`) — an image output becomes an
// edit of its source image, a mesh output a version of its source mesh. This
// means a caller that reuses a source asset as an input doesn't have to remember
// parentAssetId (works for kanban too, where there is no node wiring). The server
// knows the true output type, so this is robust even when the workflow's declared
// output type is missing/wrong. Pass parentAssetId to override.
const autoParentFromInputs = (parentAssetId === undefined || parentAssetId === null);
// Subscribe to the single-job progress stream BEFORE submitting so the
// terminal event can't be missed (the endpoint also replays the latest
// snapshot on connect).
let resolveTerminal;
const terminalPromise = new Promise(resolve => { resolveTerminal = resolve; });
const subscription = api.subscribeSse(`/comfyui/workflows/progress/${promptId}`, payload => {
if (String(payload?.promptId || '') !== promptId) return;
if (payload?.status === 'error' || payload?.done) {
resolveTerminal(payload);
return;
}
const percent = Number(payload?.progressPercent);
reportProgress(
Number.isFinite(percent) ? percent : 0,
100,
[payload?.detail, payload?.currentNodeLabel].filter(Boolean).join(' — ') || 'Running ComfyUI workflow'
);
}, {
onEnd: err => resolveTerminal({ status: 'error', detail: `Progress stream ended unexpectedly: ${err?.message || err}` })
});
let timer = null;
try {
const form = new FormData();
if (projectId !== undefined && projectId !== null) form.append('projectId', String(projectId));
form.append('workflowId', String(workflowId));
form.append('promptId', promptId);
if (kanbanCardId !== undefined && kanbanCardId !== null) form.append('cardId', String(kanbanCardId));
if (name) form.append('name', name);
if (parentAssetId !== undefined && parentAssetId !== null) {
form.append('parentAssetId', String(parentAssetId));
} else if (autoParentFromInputs) {
form.append('autoParentFromInputs', 'true');
}
if (persistProcessingCard === false) form.append('persistProcessingCard', 'false');
if (persistGeneratedAssets === false) form.append('persistGeneratedAssets', 'false');
const inputValues = { ...autoInputs, ...inputs };
for (const [key, localPath] of Object.entries(fileInputs || {})) {
const fieldName = `comfyFile:${key}`;
const buffer = await fs.readFile(localPath);
form.append(fieldName, new Blob([buffer]), path.basename(localPath));
inputValues[key] = { __fileField: fieldName };
}
form.append('inputValues', JSON.stringify(inputValues));
await api.apiForm('POST', '/comfyui/workflows/run', form);
await reportProgress(0, 100, 'Workflow queued in ComfyUI');
const outcome = await Promise.race([
terminalPromise,
new Promise(resolve => { timer = setTimeout(() => resolve({ __timeout: true }), timeoutSeconds * 1000); })
]);
if (outcome.__timeout) {
return {
status: 'running',
promptId,
note: `Still running after ${timeoutSeconds}s. The workflow continues in the background — call get_run_status with this promptId to check on it; results are attached to the project when it finishes.`
};
}
if (outcome.status === 'error') {
throw new Error(outcome.detail || outcome.error || 'ComfyUI workflow failed');
}
await reportProgress(100, 100, 'Workflow completed');
const result = outcome.result;
const assets = Array.isArray(result) ? result : (result ? [result] : []);
// Graph projects: display the results on the target node (mirrors what
// the GraphPage does after a run — without this the assets exist but no
// node shows them).
let nodeAttachment = null;
if (targetNodeId && projectId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId: targetNodeId,
assets,
metadata: { lastAction: 'comfy-workflow', promptId }
});
notifyMutation(projectId);
}
return {
status: 'completed',
promptId,
assets,
...(nodeAttachment ? { nodeAttachment } : {})
};
} finally {
if (timer) clearTimeout(timer);
subscription.close();
}
}));
server.registerTool('get_run_status', {
title: 'Get workflow run status',
description: 'Check on a ComfyUI workflow run by promptId (returned by run_workflow). Returns the latest progress snapshot: status (processing/completed/error), progressPercent, detail, and the generated assets once done.',
inputSchema: {
promptId: z.string().min(1)
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ promptId }) => {
// The single-job stream replays the latest snapshot immediately on
// connect; grab it and close. No snapshot within 3s means the server no
// longer tracks this prompt (finished >60s ago, or never existed).
const snapshot = await new Promise(resolve => {
const timer = setTimeout(() => { subscription.close(); resolve(null); }, 3000);
const subscription = api.subscribeSse(`/comfyui/workflows/progress/${encodeURIComponent(promptId)}`, payload => {
clearTimeout(timer);
subscription.close();
resolve(payload);
}, { onEnd: () => { clearTimeout(timer); resolve(null); } });
});
if (!snapshot) {
return {
status: 'unknown',
promptId,
note: 'No progress snapshot for this promptId. The run either finished more than a minute ago (check the project\'s assets with list_assets) or was never started.'
};
}
return snapshot;
}));
}

2680
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "app",
"private": true,
"version": "2.1.2",
"version": "1.4.0",
"type": "module",
"main": "electron/main.cjs",
"description": "AI-powered 3D mesh production studio — image generation, mesh generation, UV unwrapping, and texturing pipelines.",
@ -18,7 +18,6 @@
"serve": "vite build && node server.js",
"lint": "eslint .",
"preview": "vite preview",
"mcp:stdio": "node mcp/stdio.js",
"electron:dev": "npm run build && electron .",
"dist": "npm run build && electron-builder",
"dist:win": "npm run build && electron-builder --win",
@ -27,8 +26,6 @@
"dist:dir": "npm run build && electron-builder --dir"
},
"dependencies": {
"@excalidraw/excalidraw": "^0.18.1",
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
"@types/three": "^0.183.1",
@ -53,8 +50,7 @@
"three": "^0.183.2",
"three-bvh-csg": "^0.0.18",
"three-mesh-bvh": "^0.9.9",
"ws": "^8.21.0",
"zod": "^4.4.3"
"ws": "^8.21.0"
},
"devDependencies": {
"@eslint/js": "^9.39.4",

View file

@ -39,14 +39,6 @@ ALLOWED_ORIGINS: list[str] = [
# Upload guard rails.
MAX_UPLOAD_BYTES: int = _env_int("MESHTOOLS_MAX_UPLOAD_BYTES", 512 * 1024 * 1024)
# GLB -> FBX conversion (headless Blender subprocess). Generous default: bpy
# import alone takes seconds and heavy scenes bake many animation takes.
CONVERT_TIMEOUT_S: int = _env_int("MESHTOOLS_CONVERT_TIMEOUT", 600)
# Thumbnail render (headless Blender subprocess). Shorter than convert: a single
# low-sample Cycles-CPU render of one frame after the bpy import (~seconds).
THUMBNAIL_TIMEOUT_S: int = _env_int("MESHTOOLS_THUMBNAIL_TIMEOUT", 180)
# Scratch space for temp files when a tool needs real paths on disk
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
WORK_DIR: Path = Path(

View file

@ -1,6 +1,6 @@
"""Mesh-processing endpoints: Auto UV, Auto Retopo, Repair and FBX Convert.
"""Mesh-processing endpoints: Auto UV and Auto Retopo.
Contract (shared by all routes):
Contract (shared by both routes):
Request : multipart/form-data
- meshFile : the mesh to process (GLB/OBJ/PLY/STL)
- options : JSON string of the operation options (optional)
@ -24,17 +24,14 @@ import queue
import threading
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import StreamingResponse
from pydantic import ValidationError
from ..config import MAX_UPLOAD_BYTES
from ..meshio import export_mesh, load_mesh, mesh_stats
from ..schemas import AutoRetopoOptions, AutoUvOptions, ConvertOptions, RepairOptions
from ..schemas import AutoRetopoOptions, AutoUvOptions, RepairOptions
from ..services.auto_retopo import run_auto_retopo
from ..services.auto_uv import run_auto_uv
from ..services.convert_fbx import run_convert_fbx
from ..services.mesh_thumbnail import render_mesh_thumbnail
from ..services.repair import run_repair
router = APIRouter(prefix="/meshes", tags=["meshes"])
@ -89,13 +86,11 @@ def _sse(obj: dict) -> str:
return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n"
def _stream_payload(run_callable, label: str) -> StreamingResponse:
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
"""Run `run_callable(emit)` in a worker thread and stream SSE progress events.
`run_callable(emit)` must return the terminal `done` payload dict and may
call emit(stage, frac, message) to report progress. Use this directly for
tools that build their own envelope (e.g. FBX conversion, which must never
round-trip through trimesh); use `_stream_tool` for trimesh-based tools.
`run_callable(emit)` must return (mesh, tool_stats, preview_png) and may call
emit(stage, frac, message) to report progress.
"""
events: "queue.Queue" = queue.Queue()
holder: dict = {}
@ -105,7 +100,8 @@ def _stream_payload(run_callable, label: str) -> StreamingResponse:
def worker():
try:
holder["payload"] = run_callable(emit)
mesh, tool_stats, preview = run_callable(emit)
holder["payload"] = _envelope(mesh, fmt, tool_stats, preview)
except Exception as exc: # noqa: BLE001 — surfaced to the client as an error event
holder["error"] = f"{label} failed: {exc}"
finally:
@ -136,17 +132,6 @@ def _stream_payload(run_callable, label: str) -> StreamingResponse:
return StreamingResponse(generate(), media_type="text/event-stream", headers=_SSE_HEADERS)
def _stream_tool(run_callable, fmt: str, label: str) -> StreamingResponse:
"""`_stream_payload` for trimesh-based tools: `run_callable(emit)` returns
(mesh, tool_stats, preview_png) and the envelope is built here.
"""
def run(emit):
mesh, tool_stats, preview = run_callable(emit)
return _envelope(mesh, fmt, tool_stats, preview)
return _stream_payload(run, label)
@router.post("/auto-uv")
async def auto_uv(
meshFile: UploadFile = File(...),
@ -181,56 +166,3 @@ async def repair(
data = await _read_upload(meshFile)
mesh = load_mesh(data, meshFile.filename or "mesh.glb")
return _stream_tool(lambda emit: run_repair(mesh, opts, progress=emit), format, "Repair")
@router.post("/convert")
async def convert(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("fbx"),
) -> StreamingResponse:
"""GLB -> FBX engine export (headless Blender subprocess).
Deliberately bypasses trimesh (`load_mesh`/`_envelope`): trimesh cannot
write FBX and flattens skinned meshes, and this endpoint's whole point is
preserving the skeleton + animation takes. The GLB bytes go to the worker
untouched.
"""
opts = _parse_options(options, ConvertOptions)
data = await _read_upload(meshFile)
if (format or "fbx").lstrip(".").lower() != "fbx":
raise HTTPException(status_code=400, detail="Only 'fbx' output is supported by /meshes/convert.")
def run(emit):
fbx_bytes, tool_stats = run_convert_fbx(data, opts, progress=emit)
return {
"format": "fbx",
"mesh_b64": base64.b64encode(fbx_bytes).decode("ascii"),
"stats": {
"vertex_count": tool_stats.get("vertices"),
"face_count": None,
"has_uv": bool(tool_stats.get("has_uv")),
"tool": tool_stats,
},
"preview_b64": None,
}
return _stream_payload(run, "Convert to FBX")
@router.post("/thumbnail")
async def thumbnail(meshFile: UploadFile = File(...)) -> dict:
"""Render a GLB to a 512x512 PNG thumbnail (headless Blender subprocess).
Single-artifact endpoint (no SSE): returns plain JSON with the PNG base64 in
`preview_b64`. Used by the Node backend to give server-side-generated meshes
(ComfyUI / external-API, driven over MCP) a thumbnail — those never get the
browser's WebGL render. The render runs in a threadpool so the bpy subprocess
does not block the event loop.
"""
data = await _read_upload(meshFile)
try:
png = await run_in_threadpool(render_mesh_thumbnail, data)
except Exception as exc: # noqa: BLE001 — surface as a clean HTTP error
raise HTTPException(status_code=500, detail=f"Thumbnail render failed: {exc}") from exc
return {"preview_b64": base64.b64encode(png).decode("ascii")}

View file

@ -132,28 +132,6 @@ class RepairOptions(BaseModel):
description="Weld coincident vertices by position before repairing (matches the editor's check).")
class ConvertOptions(BaseModel):
"""Options for the GLB -> FBX engine-export endpoint (headless Blender).
Presets tune the FBX for the target engine's import pipeline; see
app/tools/fbx_worker.py for the exact exporter settings each one maps to.
"""
preset: Literal["unity", "unreal", "generic"] = Field(
default="generic",
description="Target engine. 'unity'/'generic' write a meters file with "
"scale-1 transforms; 'unreal' bakes the scene to centimeters.")
unreal_scale_mode: Literal["bake", "units"] = Field(
default="bake",
description="Unreal only. 'bake' rescales mesh/armature/animation data "
"x100 to native centimeters; 'units' keeps meters and relies "
"on UE's 'Convert Scene Unit' import option.")
bake_fps: int = Field(default=30, ge=1, le=120,
description="Frame rate animation takes are baked at.")
anim_simplify: float = Field(default=1.0, ge=0.0, le=10.0,
description="Baked curve simplification (0 = lossless, larger = smaller files).")
class MeshStats(BaseModel):
"""Reported back to the caller (also surfaced via response headers)."""

View file

@ -1,116 +0,0 @@
"""GLB -> FBX conversion — subprocess driver for app/tools/fbx_worker.py.
The worker owns the actual Blender (bpy) work; this module only provisions a
job directory, spawns the worker with the venv's own interpreter, relays its
sentinel-prefixed progress lines, and returns the FBX bytes + stats.
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
once imported, and a Blender crash must not take the API down. Conversions are
serialized with a semaphore for the same reason (each subprocess peaks 1-2GB).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
from pathlib import Path
from uuid import uuid4
from ..config import CONVERT_TIMEOUT_S, WORK_DIR
from ..schemas import ConvertOptions
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/fbx_worker.py
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "fbx_worker.py"
_convert_lock = threading.Semaphore(1)
def run_convert_fbx(glb_bytes: bytes, opts: ConvertOptions, progress) -> tuple[bytes, dict]:
"""Convert a GLB to FBX. Returns (fbx_bytes, worker_stats); raises on failure.
`progress(stage, frac, message)` is called for each worker progress event.
"""
job_dir = WORK_DIR / f"convert-{uuid4().hex}"
job_dir.mkdir(parents=True)
try:
in_path = job_dir / "input.glb"
in_path.write_bytes(glb_bytes)
out_path = job_dir / "output.fbx"
opt_path = job_dir / "options.json"
opt_path.write_text(opts.model_dump_json(), encoding="utf-8")
with _convert_lock:
result = _run_worker(in_path, out_path, opt_path, progress)
if not result.get("ok"):
raise RuntimeError(result.get("error") or "FBX conversion failed.")
if not out_path.exists():
raise RuntimeError("FBX worker reported success but produced no output file.")
return out_path.read_bytes(), result.get("stats") or {}
finally:
shutil.rmtree(job_dir, ignore_errors=True)
def _run_worker(in_path: Path, out_path: Path, opt_path: Path, progress) -> dict:
proc = subprocess.Popen(
[
sys.executable,
str(_WORKER),
"--input", str(in_path),
"--output", str(out_path),
"--options", str(opt_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Watchdog instead of a read timeout: the stdout iteration below ends when
# the process dies, so killing it on expiry unblocks the loop too.
timed_out = threading.Event()
def _expire():
timed_out.set()
proc.kill()
watchdog = threading.Timer(CONVERT_TIMEOUT_S, _expire)
watchdog.daemon = True
watchdog.start()
result: dict | None = None
tail: list[str] = [] # last non-protocol lines, for error context
try:
for line in proc.stdout:
if not line.startswith(SENTINEL):
stripped = line.strip()
if stripped:
tail.append(stripped)
del tail[:-8]
continue
try:
event = json.loads(line[len(SENTINEL):])
except json.JSONDecodeError:
continue
if event.get("type") == "progress":
progress(event.get("stage", "convert"), event.get("frac", 0.0), event.get("message", ""))
elif event.get("type") == "result":
result = event
code = proc.wait()
finally:
watchdog.cancel()
if proc.poll() is None:
proc.kill()
if timed_out.is_set():
raise RuntimeError(f"FBX conversion timed out after {CONVERT_TIMEOUT_S}s.")
if result is None:
detail = f" Last output: {' | '.join(tail)}" if tail else ""
raise RuntimeError(f"FBX worker exited (code {code}) without a result.{detail}")
return result

View file

@ -1,108 +0,0 @@
"""GLB -> PNG thumbnail — subprocess driver for app/tools/thumbnail_worker.py.
The worker owns the actual Blender (bpy) render; this module only provisions a
job directory, spawns the worker with the venv's own interpreter, and returns
the PNG bytes.
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
once imported, and a Blender crash must not take the API down. Renders are
serialized with a semaphore for the same reason (each subprocess peaks ~1-2GB).
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import threading
from pathlib import Path
from uuid import uuid4
from ..config import THUMBNAIL_TIMEOUT_S, WORK_DIR
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/thumbnail_worker.py
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "thumbnail_worker.py"
_render_lock = threading.Semaphore(1)
def render_mesh_thumbnail(glb_bytes: bytes) -> bytes:
"""Render a GLB to a 512x512 PNG thumbnail. Returns the PNG bytes; raises on
failure."""
job_dir = WORK_DIR / f"thumb-{uuid4().hex}"
job_dir.mkdir(parents=True)
try:
in_path = job_dir / "input.glb"
in_path.write_bytes(glb_bytes)
out_path = job_dir / "output.png"
with _render_lock:
result = _run_worker(in_path, out_path)
if not result.get("ok"):
raise RuntimeError(result.get("error") or "Thumbnail render failed.")
if not out_path.exists():
raise RuntimeError("Thumbnail worker reported success but produced no output file.")
return out_path.read_bytes()
finally:
shutil.rmtree(job_dir, ignore_errors=True)
def _run_worker(in_path: Path, out_path: Path) -> dict:
proc = subprocess.Popen(
[
sys.executable,
str(_WORKER),
"--input", str(in_path),
"--output", str(out_path),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Watchdog instead of a read timeout: the stdout iteration below ends when
# the process dies, so killing it on expiry unblocks the loop too.
timed_out = threading.Event()
def _expire():
timed_out.set()
proc.kill()
watchdog = threading.Timer(THUMBNAIL_TIMEOUT_S, _expire)
watchdog.daemon = True
watchdog.start()
result: dict | None = None
tail: list[str] = [] # last non-protocol lines, for error context
try:
for line in proc.stdout:
if not line.startswith(SENTINEL):
stripped = line.strip()
if stripped:
tail.append(stripped)
del tail[:-8]
continue
try:
event = json.loads(line[len(SENTINEL):])
except json.JSONDecodeError:
continue
if event.get("type") == "result":
result = event
code = proc.wait()
finally:
watchdog.cancel()
if proc.poll() is None:
proc.kill()
if timed_out.is_set():
raise RuntimeError(f"Thumbnail render timed out after {THUMBNAIL_TIMEOUT_S}s.")
if result is None:
detail = f" Last output: {' | '.join(tail)}" if tail else ""
raise RuntimeError(f"Thumbnail worker exited (code {code}) without a result.{detail}")
return result

View file

@ -1,5 +0,0 @@
"""Standalone worker scripts run as subprocesses by app/services wrappers.
Nothing in here should be imported by the FastAPI process — workers may pull in
heavy/unsafe-in-process dependencies (bpy is not thread-safe and never unloads).
"""

View file

@ -1,318 +0,0 @@
"""GLB -> FBX conversion worker (headless Blender).
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/convert_fbx.py
(`python fbx_worker.py --input in.glb --output out.fbx --options opts.json`).
Never import this module from the service — bpy is not thread-safe, holds ~1GB
RSS once imported, and a crash inside Blender must not take the API down.
Presets tailor the FBX for the target engine:
- unity : file declared in meters with clean scale-1 transforms
(FBX_SCALE_UNITS -> Unity "File Scale" = 1).
- unreal : the scene is baked to centimeters (x100 on mesh/armature data and
every location F-curve) and written with FBX_SCALE_NONE, so UE
imports at the right size with unit bone scales — no reliance on
the "Convert Scene Unit" import option.
- generic : same neutral meters export as unity (most interoperable).
Every glTF animation arrives as an NLA track (that is how Blender's importer
stashes clips); the exporter turns each NLA strip into a separate FBX take, so
engines see one clip per animation.
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT
(bpy prints its own "Info:" noise, the parent ignores non-matching lines).
Exit codes: 0 ok, 2 conversion error, 3 validation failed, 4 bpy missing.
"""
from __future__ import annotations
import argparse
import json
import sys
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/convert_fbx.py
# Shared exporter settings. Axis conversion stays on the export matrix
# (use_space_transform) instead of being baked into vertices:
# bake_space_transform=True is unsafe with skinned meshes — it transforms mesh
# data but not armature/bone animation consistently. The compensating root
# rotation it avoids is absorbed by Unity/Unreal importers anyway.
COMMON_FBX = dict(
check_existing=False,
use_selection=False,
object_types={"ARMATURE", "MESH"},
use_mesh_modifiers=True,
mesh_smooth_type="FACE",
use_tspace=False, # tangent export fails on generated/disconnected UVs
add_leaf_bones=False, # leaf bones pollute Unity/UE skeletons
primary_bone_axis="Y",
secondary_bone_axis="X",
use_armature_deform_only=True,
armature_nodetype="NULL",
bake_anim=True,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True, # one take per clip (NLA-stashed by the importer)
bake_anim_use_all_actions=False, # True would cross-product junk takes
bake_anim_force_startend_keying=True,
bake_anim_step=1.0,
path_mode="COPY",
embed_textures=True,
axis_forward="-Z",
axis_up="Y",
use_space_transform=True,
bake_space_transform=False,
)
METER_SCALE_FBX = dict( # unity + generic
apply_unit_scale=True,
apply_scale_options="FBX_SCALE_UNITS",
global_scale=1.0,
)
CM_BAKED_FBX = dict( # unreal, after the x100 bake
apply_unit_scale=False,
apply_scale_options="FBX_SCALE_NONE",
global_scale=1.0,
)
def emit(obj: dict) -> None:
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
sys.stdout.flush()
def progress(stage: str, frac: float, message: str = "") -> None:
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def fail(error: str, code: int) -> None:
emit({"type": "result", "ok": False, "error": error})
sys.exit(code)
def normalize_nla(objects) -> list[str]:
"""Make the exporter's take collection deterministic.
The FBX exporter only bakes UNMUTED NLA strips, and depending on the
Blender version the glTF importer may leave the last clip as a dangling
active action instead of a stashed track. Unmute everything, stash any
dangling active action as its own track, and clear active actions so no
clip layers on top of the strip bakes. Returns the clip (strip) names.
"""
clip_names: list[str] = []
for obj in objects:
ad = obj.animation_data
if not ad:
continue
for track in ad.nla_tracks:
track.mute = False
clip_names.extend(strip.name for strip in track.strips)
action = ad.action
if action is not None:
in_nla = any(
strip.action == action
for track in ad.nla_tracks
for strip in track.strips
)
if not in_nla:
track = ad.nla_tracks.new()
track.name = action.name
track.strips.new(action.name, int(action.frame_range[0]), action)
clip_names.append(action.name)
ad.action = None
# A clip animating several objects appears once per object — dedupe, keep order.
return list(dict.fromkeys(clip_names))
def collect_stats(objects, clip_names) -> dict:
import bpy
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
seen_mesh_data = {m.data for m in meshes}
return {
"armature_count": len(armatures),
"bones": sum(len(a.data.bones) for a in armatures),
"meshes": len(meshes),
"vertices": sum(len(d.vertices) for d in seen_mesh_data),
"materials": len([m for m in bpy.data.materials if m.users]),
"has_uv": any(d.uv_layers for d in seen_mesh_data),
"clips": clip_names,
}
def bake_unreal_scale(objects, factor: float = 100.0) -> None:
"""Bake the scene from meters to centimeters at the DATA level.
Data-level transforms (Mesh.transform / Armature.transform) avoid the
operator selection/context dance that transform_apply needs headless, and
sidestep its child parent-inverse compensation (which would leave mesh data
small behind a scale-100 node — exactly the transform FBX must not carry).
Skinning stays consistent because in Blender the armature rest pose IS the
bind pose: scaling mesh and rest bones by the same factor preserves it.
"""
import bpy
from mathutils import Matrix
scale = Matrix.Scale(factor, 4)
seen_data = set()
for obj in objects:
if obj.type in {"MESH", "ARMATURE"} and obj.data not in seen_data:
seen_data.add(obj.data)
obj.data.transform(scale)
obj.location = [component * factor for component in obj.location]
parent_inverse = obj.matrix_parent_inverse.copy()
parent_inverse.translation *= factor
obj.matrix_parent_inverse = parent_inverse
# Object/data transforms do not touch animation: location F-curves (object
# and pose-bone hip/root-motion translation) are in now-x100 local units.
for action in bpy.data.actions:
for fcurve in _action_fcurves(action):
if fcurve.data_path == "location" or fcurve.data_path.endswith(".location"):
for key in fcurve.keyframe_points:
key.co.y *= factor
key.handle_left.y *= factor
key.handle_right.y *= factor
def _action_fcurves(action):
"""All F-curves of an action across bpy versions: Blender 5.x replaced the
flat Action.fcurves with slotted actions (layers > strips > channelbags)."""
fcurves = getattr(action, "fcurves", None)
if fcurves is not None:
return list(fcurves)
return [
fcurve
for layer in action.layers
for strip in layer.strips
if strip.type == "KEYFRAME"
for channelbag in strip.channelbags
for fcurve in channelbag.fcurves
]
def _remove_bone_widget_objects() -> None:
"""Delete bone display-widget objects (pose bones' custom shapes).
Belt and braces on top of bone_heuristic='TEMPERANCE': should any import
path still attach widget meshes to pose bones, they must never reach the
FBX (they are viewport dressing, not scene content).
"""
import bpy
widgets = set()
for obj in bpy.context.scene.objects:
if obj.type != "ARMATURE":
continue
for pose_bone in obj.pose.bones:
if pose_bone.custom_shape is not None:
widgets.add(pose_bone.custom_shape)
pose_bone.custom_shape = None
for widget in widgets:
bpy.data.objects.remove(widget, do_unlink=True)
def validate_reimport(path: str, in_stats: dict, clip_names: list[str]) -> dict:
"""Re-import the exported FBX into a fresh scene and assert nothing was lost."""
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.fbx(filepath=path, ignore_leaf_bones=True)
objects = list(bpy.context.scene.objects)
armatures = [o for o in objects if o.type == "ARMATURE"]
meshes = [o for o in objects if o.type == "MESH"]
actions = list(bpy.data.actions) # FBX importer: one action per take
if in_stats["armature_count"] and not armatures:
raise ValidationError("exported FBX contains no armature")
if clip_names and len(actions) < len(clip_names):
raise ValidationError(
f"expected {len(clip_names)} animation take(s), re-import found {len(actions)}"
)
if in_stats["meshes"] and not meshes:
raise ValidationError("exported FBX contains no mesh")
return {
"armatures": len(armatures),
"meshes": len(meshes),
"actions": sorted(action.name for action in actions),
}
class ValidationError(RuntimeError):
pass
def convert(input_path: str, output_path: str, opts: dict) -> dict:
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
# Set fps BEFORE import: the glTF importer converts clip times to frames
# with the scene fps, and the exporter bakes one key per frame.
scene.render.fps = int(opts.get("bake_fps", 30))
scene.render.fps_base = 1.0
progress("import", 0.1, "Importing GLB…")
# bone_heuristic: the default 'BLENDER' creates an "Icosphere" mesh object
# as the bones' display widget — a real scene object the FBX exporter would
# happily ship to the engine. 'TEMPERANCE' only orients bones, no widgets.
bpy.ops.import_scene.gltf(filepath=input_path, bone_heuristic="TEMPERANCE")
_remove_bone_widget_objects()
objects = list(scene.objects)
clip_names = normalize_nla(objects)
stats = collect_stats(objects, clip_names)
progress(
"import", 0.3,
f"Imported {stats['armature_count']} armature(s) ({stats['bones']} bones), "
f"{stats['meshes']} mesh(es), {len(clip_names)} clip(s)",
)
preset = opts.get("preset", "generic")
kwargs = dict(COMMON_FBX)
kwargs["bake_anim_simplify_factor"] = float(opts.get("anim_simplify", 1.0))
if preset == "unreal" and opts.get("unreal_scale_mode", "bake") == "bake":
progress("transform", 0.45, "Baking centimeter scale for Unreal…")
bake_unreal_scale(objects)
kwargs.update(CM_BAKED_FBX)
else:
kwargs.update(METER_SCALE_FBX)
progress("export", 0.55, f"Baking {len(clip_names)} animation take(s) to FBX…")
bpy.ops.export_scene.fbx(filepath=output_path, **kwargs)
progress("validate", 0.8, "Re-importing FBX to validate…")
stats["validation"] = validate_reimport(output_path, stats, clip_names)
stats["preset"] = preset
return stats
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Source .glb path")
parser.add_argument("--output", required=True, help="Destination .fbx path")
parser.add_argument("--options", required=True, help="Path to an options JSON file")
args = parser.parse_args()
with open(args.options, encoding="utf-8") as handle:
opts = json.load(handle)
try:
import bpy # noqa: F401 — probe only; used inside convert()
except ImportError as exc:
fail(f"bpy is not installed in this environment: {exc}", 4)
try:
stats = convert(args.input, args.output, opts)
except ValidationError as exc:
fail(f"Validation failed: {exc}", 3)
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
import traceback
traceback.print_exc()
fail(f"{type(exc).__name__}: {exc}", 2)
else:
emit({"type": "result", "ok": True, "stats": stats})
if __name__ == "__main__":
main()

View file

@ -1,185 +0,0 @@
"""GLB -> PNG thumbnail worker (headless Blender).
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/mesh_thumbnail.py
(`python thumbnail_worker.py --input in.glb --output out.png`). Never import this
module from the service — bpy is not thread-safe, holds ~1GB RSS once imported,
and a crash inside Blender must not take the API down.
Why a server-side render at all: mesh thumbnails are normally rendered in the
browser (src/utils/meshThumbnail.js, WebGL). Meshes created without a browser
(ComfyUI workflows / external-API generation driven over MCP) never get one, so
the app shows an empty image. This renders one headlessly instead.
Engine choice: Cycles on the CPU. Cycles needs no GL/display context, so it
renders reliably headless on every platform (EEVEE/Workbench depend on an
OpenGL context that is often absent on servers). Low samples keep a 512px frame
to ~1-3s. The framing/lighting mirrors the client renderer so thumbnails look
consistent: dark background, a 3/4 camera, key + fill + rim lights.
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT (bpy
prints its own "Info:" noise, the parent ignores non-matching lines).
Exit codes: 0 ok, 2 render error, 4 bpy missing.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/mesh_thumbnail.py
RESOLUTION = 512
SAMPLES = 24
CAMERA_FOV_DEG = 35.0
# Camera direction (Blender is Z-up; the glTF importer puts model front toward
# -Y). A 3/4 view from front-right-above, matching the client's angle.
CAMERA_DIR = (0.9, -1.0, 0.7)
# Neutral world colour used only for soft ambient fill (never shown — the film
# is transparent). Blender colour inputs are linear.
AMBIENT_COLOR = (0.09, 0.095, 0.11)
def emit(obj: dict) -> None:
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
sys.stdout.flush()
def progress(stage: str, frac: float, message: str = "") -> None:
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
def fail(error: str, code: int) -> None:
emit({"type": "result", "ok": False, "error": error})
sys.exit(code)
def _scene_bounds(objects):
"""World-space (min, max) corners over every mesh object's bounding box."""
from mathutils import Vector
lo = Vector((math.inf, math.inf, math.inf))
hi = Vector((-math.inf, -math.inf, -math.inf))
found = False
for obj in objects:
if obj.type != "MESH":
continue
found = True
for corner in obj.bound_box:
world = obj.matrix_world @ Vector(corner)
lo = Vector((min(lo.x, world.x), min(lo.y, world.y), min(lo.z, world.z)))
hi = Vector((max(hi.x, world.x), max(hi.y, world.y), max(hi.z, world.z)))
if not found:
return None
return lo, hi
def _add_sun(name, direction, energy):
import bpy
from mathutils import Vector
data = bpy.data.lights.new(name=name, type="SUN")
data.energy = energy
obj = bpy.data.objects.new(name=name, object_data=data)
bpy.context.scene.collection.objects.link(obj)
# A sun's rays travel along its local -Z; aim that at `direction`.
obj.rotation_euler = Vector(direction).normalized().to_track_quat("-Z", "Y").to_euler()
return obj
def render(input_path: str, output_path: str) -> None:
import bpy
from mathutils import Vector
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
progress("import", 0.2, "Importing GLB…")
# TEMPERANCE: the default bone heuristic spawns an Icosphere widget mesh for
# rigged meshes that would pollute the framing; TEMPERANCE only orients bones.
bpy.ops.import_scene.gltf(filepath=input_path, bone_heuristic="TEMPERANCE")
objects = list(scene.objects)
bounds = _scene_bounds(objects)
if bounds is None:
raise RuntimeError("The GLB contains no mesh geometry to render.")
lo, hi = bounds
center = (lo + hi) * 0.5
size = hi - lo
max_dim = max(size.x, size.y, size.z, 1e-4)
progress("camera", 0.4, "Framing camera…")
cam_data = bpy.data.cameras.new("thumb_cam")
cam_data.angle = math.radians(CAMERA_FOV_DEG)
cam_obj = bpy.data.objects.new("thumb_cam", cam_data)
scene.collection.objects.link(cam_obj)
scene.camera = cam_obj
direction = Vector(CAMERA_DIR).normalized()
distance = max_dim * 2.2
cam_obj.location = center + direction * distance
# Camera looks down its local -Z with +Y up.
cam_obj.rotation_euler = (-direction).to_track_quat("-Z", "Y").to_euler()
# Lights: a soft ambient world plus key/fill/rim suns (mirrors the client's
# ambient + key + rim setup).
world = bpy.data.worlds.new("thumb_world")
scene.world = world
world.use_nodes = True
bg = world.node_tree.nodes.get("Background")
if bg is not None:
bg.inputs[0].default_value = (*AMBIENT_COLOR, 1.0)
bg.inputs[1].default_value = 1.1 # ambient strength
_add_sun("key", (-0.5, 0.8, -1.0), 4.0)
_add_sun("fill", (0.9, 0.4, -0.6), 1.6)
_add_sun("rim", (0.4, -0.9, 0.5), 2.2)
progress("render", 0.6, "Rendering thumbnail…")
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = SAMPLES
scene.cycles.use_denoising = True
scene.render.resolution_x = RESOLUTION
scene.render.resolution_y = RESOLUTION
scene.render.resolution_percentage = 100
# Transparent background (RGBA): the model composites cleanly over the app's
# dark cards, and it avoids the version-specific Blender compositor API. The
# world stays bright for ambient fill but is not shown.
scene.render.film_transparent = True
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.filepath = output_path
# Match the client's plain-sRGB output: Blender's default AgX/Filmic view
# transform lifts darks and shifts colours. "Standard" keeps colours
# as-authored so thumbnails look like the in-app WebGL renders.
try:
scene.view_settings.view_transform = "Standard"
except TypeError: # build may name it differently — non-fatal
pass
bpy.ops.render.render(write_still=True)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Source .glb path")
parser.add_argument("--output", required=True, help="Destination .png path")
args = parser.parse_args()
try:
import bpy # noqa: F401 — probe only; used inside render()
except ImportError as exc:
fail(f"bpy is not installed in this environment: {exc}", 4)
try:
render(args.input, args.output)
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
import traceback
traceback.print_exc()
fail(f"{type(exc).__name__}: {exc}", 2)
else:
emit({"type": "result", "ok": True})
if __name__ == "__main__":
main()

View file

@ -16,12 +16,6 @@ pymeshlab>=2023.12 # isotropic remesh / decimation / quad conversion
matplotlib>=3.8 # only needed for the CLI's UV-layout / compare PNGs
rtree
# Engine export (GLB -> FBX via headless Blender). cp313 wheel (~340MB download,
# ~1GB installed); each bpy release supports exactly one Python version — keep in
# sync with .python-version (3.13). Imported ONLY by app/tools/fbx_worker.py,
# which runs as a subprocess (never import bpy in the FastAPI process).
bpy>=5.0,<6
# --- Optional GPU acceleration (Auto Retopo) ---------------------------------
# GPU packages live in requirements-nvidia.txt and are NOT installed from this
# file. run.bat auto-detects an NVIDIA GPU on first setup and installs them

737
server.js

File diff suppressed because it is too large Load diff

View file

@ -1,37 +0,0 @@
{
"1": {
"inputs": {
"model_name": "Qwen3-VL-4B-Instruct",
"quantization": "None (FP16)",
"attention_mode": "auto",
"use_torch_compile": false,
"device": "auto",
"prompt_text": "",
"enhancement_style": "📝 Enhance",
"custom_system_prompt": "",
"max_tokens": 1024,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.1,
"keep_model_loaded": false,
"seed": 12345
},
"class_type": "AILab_QwenVL_PromptEnhancer",
"_meta": {
"title": "QwenVL Prompt Enhancer"
}
},
"2": {
"inputs": {
"output": "",
"source": [
"1",
0
]
},
"class_type": "Display Any (rgthree)",
"_meta": {
"title": "Display Any (rgthree)"
}
}
}

View file

@ -181,8 +181,7 @@
"Inputs": [
{ "Node": "112", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "116", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "116", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "114", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "116", "Input": "steps", "Name": "Steps", "Type": "Number" }
],
"Outputs": [
{ "Node": "90", "Name": "Save Image", "Type": "Image" }
@ -295,8 +294,7 @@
"Inputs": [
{ "Node": "34:27", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "34:3", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "34:3", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "34:13", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "34:3", "Input": "steps", "Name": "Steps", "Type": "Number" }
],
"Outputs": [
{ "Node": "43", "Name": "Save Image", "Type": "Image" }
@ -329,8 +327,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "7", "Input": "noise_seed", "Name": "Seed", "Type": "Number" },
{ "Node": "8:17", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "8:18", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "63", "Name": "Save Image", "Type": "Image" }
@ -392,8 +389,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "7", "Input": "noise_seed", "Name": "Seed", "Type": "Number" },
{ "Node": "8:17", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "8:18", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "63", "Name": "Save Image", "Type": "Image" }
@ -477,8 +473,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "2", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "2", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "31", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "10", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "31", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "22", "Name": "Save Image", "Type": "Image" }
@ -503,8 +498,7 @@
{ "Node": "23", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "3", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "3", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "46", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "43", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "46", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "47", "Name": "Save Image", "Type": "Image" }
@ -559,7 +553,7 @@
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "232", "Name": "Save Mesh", "Type": "Mesh" }
@ -572,7 +566,7 @@
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" },
{ "Node": "261", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" }
],
"Outputs": [
@ -585,7 +579,7 @@
"Inputs": [
{ "Node": "1", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
{ "Node": "3", "Input": "target_face_num", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "3", "Input": "method", "Name": "Method", "Type": "String", "Enums":["Cumesh","Meshlib"] }
{ "Node": "3", "Input": "method", "Name": "Method (Cumesh or Meshlib)", "Type": "String" }
],
"Outputs": [
{ "Node": "5", "Name": "Save Mesh", "Type": "Mesh" }
@ -598,7 +592,7 @@
{ "Node": "1", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "8", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
{ "Node": "3", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" },
{ "Node": "3", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "3", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "12", "Name": "Output Mesh", "Type": "Mesh" }
@ -625,7 +619,7 @@
{ "Node": "2", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "28", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "4", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "4", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "4", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "7", "Name": "Save Mesh", "Type": "Mesh" }
@ -689,19 +683,6 @@
"Outputs": [
{ "Node": "10", "Name": "Save Mesh", "Type": "Mesh" }
]
},
{
"Name": "Prompt Enhancer",
"File": "setup/Prompt Enhancer.json",
"Inputs": [
{ "Node": "1", "Input": "prompt_text", "Name": "Source Prompt", "Type": "String" },
{ "Node": "1", "Input": "max_tokens", "Name": "Max Tokens", "Type": "Number" },
{ "Node": "1", "Input": "keep_model_loaded", "Name": "Keep Model Loaded", "Type": "Boolean" },
{ "Node": "1", "Input": "seed", "Name": "Seed", "Type": "Number" }
],
"Outputs": [
{ "Node": "2", "Name": "Enhanced Prompt", "Type": "String" }
]
}
]
}

View file

@ -8,7 +8,6 @@ import ProjectWorkspacePage from './pages/ProjectWorkspacePage'
import AssetsPage from './pages/AssetsPage'
import MeshEditorPage from './pages/MeshEditorPage'
import ImageEditorPage from './pages/ImageEditorPage'
import BoardPage from './pages/BoardPage'
import WikiPage from './pages/WikiPage'
function AppRoutes() {
@ -20,7 +19,6 @@ function AppRoutes() {
<Route path="/assets" element={<AssetsPage />} />
<Route path="/mesh-editor" element={<MeshEditorPage />} />
<Route path="/image-editor" element={<ImageEditorPage />} />
<Route path="/board" element={<BoardPage />} />
<Route path="/wiki" element={<WikiPage />} />
<Route path="/wiki/:pageId" element={<WikiPage />} />
<Route path="/library" element={<Navigate to="/assets" replace />} />

View file

@ -222,11 +222,8 @@
display: block;
}
/* Mesh thumbnails are square renders (often transparent-backed); the preview
box is 16:10, so `cover` would crop a tall subject and look zoomed in.
`contain` shows the whole render, centered over the card background. */
.asset-selector-preview--mesh .asset-selector-image {
object-fit: contain;
object-fit: cover;
}
.asset-selector-mesh-placeholder {

View file

@ -15,8 +15,6 @@ function getAssetPreviewUrl(filename) {
}
const ASSETS_PER_PAGE = 20;
// Meshes show 3 per row, so 21 (7 full rows) paginates more cleanly than 20.
const MESHES_PER_PAGE = 21;
export default function AssetSelectorModal({ assetType, onSelect, onClose, showEdits = false }) {
const { getLibraryAssets, projects } = useProjects();
@ -139,12 +137,11 @@ export default function AssetSelectorModal({ assetType, onSelect, onClose, showE
setCurrentPage(1);
}, [normalizedSearch, projectFilter]);
const assetsPerPage = validType === 'mesh' ? MESHES_PER_PAGE : ASSETS_PER_PAGE;
const totalPages = Math.max(1, Math.ceil(filteredAssets.length / assetsPerPage));
const pageStart = (currentPage - 1) * assetsPerPage;
const paginatedAssets = filteredAssets.slice(pageStart, pageStart + assetsPerPage);
const totalPages = Math.max(1, Math.ceil(filteredAssets.length / ASSETS_PER_PAGE));
const pageStart = (currentPage - 1) * ASSETS_PER_PAGE;
const paginatedAssets = filteredAssets.slice(pageStart, pageStart + ASSETS_PER_PAGE);
const pageRangeStart = filteredAssets.length === 0 ? 0 : pageStart + 1;
const pageRangeEnd = Math.min(pageStart + assetsPerPage, filteredAssets.length);
const pageRangeEnd = Math.min(pageStart + ASSETS_PER_PAGE, filteredAssets.length);
useEffect(() => {
if (currentPage > totalPages) {
@ -297,7 +294,7 @@ export default function AssetSelectorModal({ assetType, onSelect, onClose, showE
})}
</div>
{filteredAssets.length > assetsPerPage && (
{filteredAssets.length > ASSETS_PER_PAGE && (
<div className="asset-selector-pagination">
<div className="asset-selector-pagination-summary">
Showing {pageRangeStart}-{pageRangeEnd} of {filteredAssets.length}

View file

@ -145,32 +145,6 @@
color: var(--on-surface-variant);
}
.export-mesh__progress {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.export-mesh__progress-track {
height: 6px;
border-radius: 999px;
background: rgba(71, 72, 74, 0.28);
overflow: hidden;
}
.export-mesh__progress-bar {
height: 100%;
border-radius: 999px;
background: var(--primary);
transition: width 0.25s ease;
}
.export-mesh__progress-message {
font-size: 0.74rem;
line-height: 1.4;
color: var(--on-surface-variant);
}
.export-mesh__message {
padding: 0.65rem 0.8rem;
border-radius: var(--radius-md);

View file

@ -1,67 +1,27 @@
import { useEffect, useState } from 'react'
import { useState } from 'react'
import FolderBrowserDialog from './FolderBrowserDialog'
import {
EXPORT_FORMATS,
browseFolders,
exportObject3D,
isGlbUrl,
loadObject3DFromUrl,
sanitizeBaseName,
writeExportedFiles
} from '../utils/meshExport'
import { convertMesh, ensureDesktopService } from '../utils/meshTools'
import './ExportMeshDialog.css'
const LAST_OUTPUT_FOLDER_KEY = 'exportMeshDialog:lastOutputFolder'
// Reusable export popup. Provide either `getObject3D` (an async function that
// returns the in-memory THREE.Object3D to export) or `meshUrl` (a mesh URL the
// dialog loads itself). `defaultName` seeds the output file name.
//
// Engine presets (Blender/Unity/Unreal/FBX) are only offered in `meshUrl` mode:
// they exist to carry the rig + animation clips of saved assets, while
// `getObject3D` callers (the mesh editor) hand over rig-free geometry.
export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = 'mesh', onClose }) {
const [format, setFormat] = useState('glb')
const [fileName, setFileName] = useState(sanitizeBaseName(defaultName))
const [outputFolder, setOutputFolder] = useState('')
const [showFolderBrowser, setShowFolderBrowser] = useState(false)
const [exporting, setExporting] = useState(false)
const [progress, setProgress] = useState(null)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const formats = getObject3D ? EXPORT_FORMATS.filter(entry => entry.kind === 'local') : EXPORT_FORMATS
const selectedFormat = formats.find(entry => entry.value === format) || formats[0]
// Recall the last folder used, but drop it silently if it no longer exists.
useEffect(() => {
const saved = localStorage.getItem(LAST_OUTPUT_FOLDER_KEY)
if (!saved) return
browseFolders(saved)
.then(() => setOutputFolder(saved))
.catch(() => localStorage.removeItem(LAST_OUTPUT_FOLDER_KEY))
}, [])
// Source GLB for the preset paths. When the asset is already a .glb, use its
// original bytes (perfect fidelity — skin weights, clips and textures
// untouched); otherwise serialize through three.js, which now carries the
// loaded animations onto the exported GLB.
const getSourceGlbBlob = async base => {
if (!getObject3D && meshUrl && isGlbUrl(meshUrl)) {
const response = await fetch(meshUrl)
if (!response.ok) {
throw new Error('Could not fetch the source mesh.')
}
return await response.blob()
}
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
}
const files = await exportObject3D(object, { format: 'glb', baseName: base })
return files[0].blob
}
const selectedFormat = EXPORT_FORMATS.find(entry => entry.value === format) || EXPORT_FORMATS[0]
const handleExport = async () => {
const folder = outputFolder.trim()
@ -75,54 +35,21 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
setExporting(true)
setError('')
setSuccess('')
setProgress(null)
try {
let files
let convertNote = ''
if (selectedFormat.value === 'glb') {
// Byte-passthrough when the source is a .glb (rig/animations/textures
// untouched); three.js re-export otherwise.
setProgress({ frac: 0.2, message: 'Preparing GLB…' })
files = [{ filename: `${base}.glb`, blob: await getSourceGlbBlob(base) }]
} else if (selectedFormat.kind !== 'preset') {
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
}
files = await exportObject3D(object, { format: selectedFormat.value, baseName: base })
} else {
setProgress({ frac: 0.05, message: 'Preparing source GLB…' })
const glbBlob = await getSourceGlbBlob(base)
setProgress({ frac: 0.1, message: 'Starting the Mesh Tools service…' })
await ensureDesktopService('meshtools')
const { blob, stats } = await convertMesh(glbBlob, {
options: { preset: selectedFormat.preset },
fileName: `${base}.glb`,
onProgress: evt => setProgress({
frac: 0.1 + 0.85 * (evt.frac ?? 0),
message: evt.message || 'Converting to FBX…'
})
})
files = [{ filename: `${base}.fbx`, blob }]
const tool = stats?.tool
if (tool) {
const clipCount = Array.isArray(tool.clips) ? tool.clips.length : 0
convertNote = ` — ${tool.bones || 0} bones, ${clipCount} animation clip${clipCount === 1 ? '' : 's'}`
}
const object = getObject3D ? await getObject3D() : await loadObject3DFromUrl(meshUrl)
if (!object) {
throw new Error('No mesh is available to export.')
}
setProgress({ frac: 0.97, message: 'Writing files…' })
const files = await exportObject3D(object, { format, baseName: base })
const result = await writeExportedFiles(folder, files)
localStorage.setItem(LAST_OUTPUT_FOLDER_KEY, folder)
const writtenNames = (result?.written || files.map(file => file.filename)).join(', ')
setSuccess(`Exported ${files.length} file${files.length === 1 ? '' : 's'}: ${writtenNames}${convertNote}`)
setSuccess(`Exported ${files.length} file${files.length === 1 ? '' : 's'}: ${writtenNames}`)
} catch (err) {
setError(err.message || 'Failed to export the mesh.')
} finally {
setExporting(false)
setProgress(null)
}
}
@ -150,7 +77,7 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
value={format}
onChange={event => { setFormat(event.target.value); setSuccess('') }}
>
{formats.map(entry => (
{EXPORT_FORMATS.map(entry => (
<option key={entry.value} value={entry.value}>{entry.label}</option>
))}
</select>
@ -190,20 +117,11 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
</div>
</label>
{selectedFormat.hint && (
<p className="export-mesh__hint">{selectedFormat.hint}</p>
)}
{progress && (
<div className="export-mesh__progress" role="status">
<div className="export-mesh__progress-track">
<div
className="export-mesh__progress-bar"
style={{ width: `${Math.round(Math.min(1, Math.max(0, progress.frac)) * 100)}%` }}
/>
</div>
<span className="export-mesh__progress-message">{progress.message}</span>
</div>
{selectedFormat.multiFile && (
<p className="export-mesh__hint">
OBJ saves geometry, materials and textures as separate files named after the mesh
(e.g. {sanitizeBaseName(fileName)}.obj, {sanitizeBaseName(fileName)}.mtl, {sanitizeBaseName(fileName)}_albedo.png).
</p>
)}
{error && <div className="export-mesh__message export-mesh__message--error">{error}</div>}

View file

@ -55,7 +55,7 @@ function getNotificationIcon(tone) {
return 'info'
}
export default function Header({ showSearch = false, showCreateNew = false, onSettingsClick, title = '', centerTitle = false, searchValue = '', onSearchChange, searchPlaceholder = 'Search Assets', projectId = null }) {
export default function Header({ showSearch = false, showCreateNew = false, onSettingsClick, title = '', centerTitle = false, searchValue = '', onSearchChange, searchPlaceholder = 'Search Assets' }) {
const location = useLocation()
const navigate = useNavigate()
const { notifications, clearNotifications, removeNotification } = useNotifications()
@ -182,20 +182,6 @@ export default function Header({ showSearch = false, showCreateNew = false, onSe
)
)}
{projectId && (
isActive('/board') ? (
<Link to={`/projects/${projectId}`} className="header__search-btn" title="Back to workspace">
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>arrow_back</span>
<span className="header__search-text">Workspace</span>
</Link>
) : (
<Link to={`/board?projectId=${projectId}`} className="header__search-btn" title="Open brainstorming boards">
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>dashboard</span>
<span className="header__search-text">Boards</span>
</Link>
)
)}
<div className="header__actions">
<button
className={`header__icon-btn ${hasUnreadNotifications ? 'header__icon-btn--update' : ''}`}

View file

@ -8,7 +8,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
const [showGrid, setShowGrid] = useState(true)
const [showShadows, setShowShadows] = useState(false)
const [showAlbedo, setShowAlbedo] = useState(false)
const [showWireframe, setShowWireframe] = useState(false)
const [showLightSlider, setShowLightSlider] = useState(false)
const [lightIntensity, setLightIntensity] = useState(2.2)
const [showExport, setShowExport] = useState(false)
@ -47,15 +46,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
>
A
</button>
<button
type="button"
className={`mesh-preview-dialog__tool ${showWireframe ? 'mesh-preview-dialog__tool--active' : ''}`}
onClick={() => setShowWireframe(current => !current)}
aria-pressed={showWireframe}
title="Toggle wireframe"
>
W
</button>
<button
type="button"
className={`mesh-preview-dialog__tool ${showGrid ? 'mesh-preview-dialog__tool--active' : ''}`}
@ -103,7 +93,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
showGrid={showGrid}
showShadows={showShadows}
showAlbedo={showAlbedo}
showWireframe={showWireframe}
lightIntensity={lightIntensity}
fitMode="center"
/>

View file

@ -1,6 +1,5 @@
import { useState, useEffect } from 'react'
import { useSettings } from '../context/SettingsContext.shared'
import { API_BASE } from '../config'
import './SettingsModal.css'
const CUSTOM_API_TYPE_OPTIONS = [
@ -8,8 +7,7 @@ const CUSTOM_API_TYPE_OPTIONS = [
{ value: 'image-edit', label: 'Image Edit' },
{ value: 'mesh-generation', label: 'Mesh Generation' },
{ value: 'mesh-edit', label: 'Mesh Edit' },
{ value: 'mesh-texturing', label: 'Mesh Texturing' },
{ value: 'mesh-rigging', label: 'Mesh Rigging' }
{ value: 'mesh-texturing', label: 'Mesh Texturing' }
]
function getCustomApiTypeLabel(type) {
@ -88,23 +86,6 @@ function ServiceControl({ name }) {
)
}
// Desktop-only: opt a service into starting automatically when the app launches
// (the main process reads this setting on boot). Renders nothing outside the
// desktop app, where services are launched externally.
function AutoStartToggle({ checked, onChange, warning }) {
const isDesktop = typeof window !== 'undefined' && !!window.genStudioServices?.isDesktop
if (!isDesktop) return null
return (
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5em', marginTop: '10px', cursor: 'pointer' }}>
<input type="checkbox" checked={!!checked} onChange={e => onChange(e.target.checked)} />
<span className="settings-helper-text" style={{ margin: 0 }}>
Start automatically when the app launches
{warning ? ' (keeps ~14 GB of GPU memory in use the whole session)' : ''}
</span>
</label>
)
}
// Desktop-only: install the (opt-in) rigging service after first run — for users
// who upgraded, skipped it on the setup screen, or later added a GPU. Drives the
// same uv provisioning as the first-run window via the genStudioSetup bridge and
@ -183,48 +164,6 @@ function RiggingInstaller() {
)
}
// Desktop-only-friendly folder browse button: calls the backend's native folder
// picker (Windows) and reports the chosen path back to the caller.
function BrowseFolderButton({ description, initialPath, onPick }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const handleClick = async () => {
setError(''); setBusy(true)
try {
const res = await fetch(`${API_BASE}/setup/pick-folder`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description, initialPath })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Folder picker failed')
if (data.path) onPick(data.path)
} catch (err) {
setError(err.message || String(err))
} finally {
setBusy(false)
}
}
return (
<>
<button
type="button"
className="kanban-sidebar__new-asset"
style={{ margin: 0, padding: '0.5rem 0.9rem', whiteSpace: 'nowrap' }}
onClick={handleClick}
disabled={busy}
title={description}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px', verticalAlign: 'middle' }}>folder_open</span>
{busy ? '…' : 'Browse'}
</button>
{error && <p className="settings-helper-text" style={{ color: '#f87171' }}>{error}</p>}
</>
)
}
export default function SettingsModal({ onClose }) {
const { settings, updateSettings, addCustomApi } = useSettings()
const [localSettings, setLocalSettings] = useState(settings)
@ -579,65 +518,21 @@ export default function SettingsModal({ onClose }) {
<div className="settings-input-group">
<label className="settings-label">Path</label>
<div style={{ display: 'flex', gap: '0.5em', alignItems: 'flex-start' }}>
<input
className="settings-input"
style={{ flex: 1 }}
placeholder="C:\\ComfyUI"
value={localSettings?.apis?.comfyui?.path || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
path: e.target.value
}
<input
className="settings-input"
placeholder="C:\\ComfyUI"
value={localSettings?.apis?.comfyui?.path || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
path: e.target.value
}
}))}
/>
<BrowseFolderButton
description="Select your ComfyUI folder"
initialPath={localSettings?.apis?.comfyui?.path || ''}
onPick={picked => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, comfyui: { ...prev?.apis?.comfyui, path: picked } }
}))}
/>
</div>
</div>
<div className="settings-input-group">
<label className="settings-label">Models Path <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span></label>
<div style={{ display: 'flex', gap: '0.5em', alignItems: 'flex-start' }}>
<input
className="settings-input"
style={{ flex: 1 }}
placeholder="Defaults to {ComfyUI path}\models"
value={localSettings?.apis?.comfyui?.modelsPath || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
modelsPath: e.target.value
}
}
}))}
/>
<BrowseFolderButton
description="Select your ComfyUI models folder"
initialPath={localSettings?.apis?.comfyui?.modelsPath || localSettings?.apis?.comfyui?.path || ''}
onPick={picked => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, comfyui: { ...prev?.apis?.comfyui, modelsPath: picked } }
}))}
/>
</div>
<p className="settings-helper-text">
Set this only if your models live somewhere other than <code>{'{ComfyUI path}'}\models</code> (e.g. shared across multiple ComfyUI installs).
</p>
}
}))}
/>
</div>
<div className="settings-grid settings-grid--triple">
@ -744,13 +639,6 @@ export default function SettingsModal({ onClose }) {
stop it here. Outside the desktop app, start it from python-server/run.
</p>
<ServiceControl name="meshtools" />
<AutoStartToggle
checked={localSettings?.apis?.meshtools?.autoStart}
onChange={v => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, meshtools: { ...prev?.apis?.meshtools, autoStart: v } }
}))}
/>
</div>
<h3 className="settings-section-title font-label">Rigging (Python) Connection</h3>
@ -809,14 +697,6 @@ export default function SettingsModal({ onClose }) {
</p>
<RiggingInstaller />
<ServiceControl name="rigging" />
<AutoStartToggle
warning
checked={localSettings?.apis?.rigtools?.autoStart}
onChange={v => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, rigtools: { ...prev?.apis?.rigtools, autoStart: v } }
}))}
/>
</div>
</section>
)}

View file

@ -74,11 +74,9 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const [loadError, setLoadError] = useState('')
const [comfyPath, setComfyPath] = useState('')
const [modelsPath, setModelsPath] = useState('')
const [pathBusy, setPathBusy] = useState(false)
const [pathError, setPathError] = useState('')
const [browseBusy, setBrowseBusy] = useState(false)
const [browseModelsBusy, setBrowseModelsBusy] = useState(false)
const [selectionByName, setSelectionByName] = useState({})
const [existingFileKeys, setExistingFileKeys] = useState(new Set())
@ -119,10 +117,6 @@ export default function SetupWizardModal({ onComplete, onClose }) {
setComfyPath(settings?.apis?.comfyui?.path || '')
}, [settings?.apis?.comfyui?.path])
useEffect(() => {
setModelsPath(settings?.apis?.comfyui?.modelsPath || '')
}, [settings?.apis?.comfyui?.modelsPath])
useEffect(() => () => {
eventSourceRef.current?.close()
}, [])
@ -137,10 +131,9 @@ export default function SetupWizardModal({ onComplete, onClose }) {
return buildFileList(config, allSelections, paths)
}, [config])
const refreshFileExistence = useCallback(async (pathOverride, modelsPathOverride) => {
const refreshFileExistence = useCallback(async (pathOverride) => {
if (!config) return
const effectivePath = pathOverride ?? comfyPath
const effectiveModelsPath = modelsPathOverride ?? modelsPath
if (!effectivePath) return
setCheckingFiles(true)
@ -148,7 +141,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const res = await fetch(`${API_BASE}/setup/check-files`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comfyPath: effectivePath, modelsPath: effectiveModelsPath, files: allCandidateFiles })
body: JSON.stringify({ comfyPath: effectivePath, files: allCandidateFiles })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to check files')
@ -163,7 +156,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
} finally {
setCheckingFiles(false)
}
}, [allCandidateFiles, comfyPath, modelsPath, config])
}, [allCandidateFiles, comfyPath, config])
const selections = useMemo(
() => Object.entries(selectionByName).map(([diffusionName, modelQuality]) => ({ diffusionName, modelQuality })),
@ -262,35 +255,15 @@ export default function SetupWizardModal({ onComplete, onClose }) {
}
}
const handleBrowseModelsFolder = async () => {
setPathError('')
setBrowseModelsBusy(true)
try {
const res = await fetch(`${API_BASE}/setup/pick-folder`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: 'Select your ComfyUI models folder', initialPath: modelsPath || comfyPath })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Folder picker failed')
if (data.path) setModelsPath(data.path)
} catch (err) {
setPathError(err.message || String(err))
} finally {
setBrowseModelsBusy(false)
}
}
const handleValidatePath = async () => {
setPathError('')
setPathBusy(true)
try {
const trimmed = comfyPath.trim()
const trimmedModelsPath = modelsPath.trim()
const res = await fetch(`${API_BASE}/setup/check-comfy-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: trimmed, modelsPath: trimmedModelsPath })
body: JSON.stringify({ path: trimmed })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Invalid ComfyUI path')
@ -299,11 +272,11 @@ export default function SetupWizardModal({ onComplete, onClose }) {
...settings,
apis: {
...(settings?.apis || {}),
comfyui: { ...(settings?.apis?.comfyui || {}), path: trimmed, modelsPath: trimmedModelsPath }
comfyui: { ...(settings?.apis?.comfyui || {}), path: trimmed }
}
})
await refreshFileExistence(trimmed, trimmedModelsPath)
await refreshFileExistence(trimmed)
setStepId('models')
} catch (err) {
setPathError(err.message || String(err))
@ -325,7 +298,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const res = await fetch(`${API_BASE}/setup/download`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comfyPath, modelsPath, files: filesToDownload })
body: JSON.stringify({ comfyPath, files: filesToDownload })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to start downloads')
@ -467,36 +440,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
</button>
</div>
<p className="setup-wizard__hint">
{modelsPath.trim()
? 'Missing model-type subfolders will be created inside your models folder below.'
: <>The folder must contain a <code>models</code> subfolder. Missing model-type subfolders will be created.</>}
</p>
<label className="projects-page__label font-label" htmlFor="setup-models-path" style={{ marginTop: '1em' }}>
Models Folder <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span>
</label>
<div className="setup-wizard__path-row">
<input
id="setup-models-path"
type="text"
className="projects-page__input setup-wizard__path-input"
placeholder="Defaults to {ComfyUI folder}\models"
value={modelsPath}
onChange={(e) => setModelsPath(e.target.value)}
/>
<button
type="button"
className="setup-wizard__browse-btn"
onClick={handleBrowseModelsFolder}
disabled={browseModelsBusy}
title="Browse for models folder"
>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>folder_open</span>
{browseModelsBusy ? '…' : 'Browse'}
</button>
</div>
<p className="setup-wizard__hint">
Set this only if your models live somewhere other than <code>{'{ComfyUI folder}'}\models</code> (e.g. shared across multiple ComfyUI installs).
The folder must contain a <code>models</code> subfolder. Missing model-type subfolders will be created.
</p>
{pathError && <div className="setup-wizard__error">{pathError}</div>}

View file

@ -184,36 +184,6 @@ function applyDisplayMaterial(object, showNormals, showShadows, showAlbedo) {
})
}
function applyWireframeOverlay(object, showWireframe) {
if (!showWireframe || !object) {
return
}
const meshes = []
object.traverse(child => {
if (child.isMesh && child.geometry) {
meshes.push(child)
}
})
meshes.forEach(mesh => {
const overlay = new THREE.Mesh(
mesh.geometry,
new THREE.MeshBasicMaterial({
color: '#ffffff',
wireframe: true,
transparent: true,
opacity: 0.36,
depthWrite: false
})
)
overlay.castShadow = false
overlay.receiveShadow = false
overlay.userData.isWireframeOverlay = true
mesh.add(overlay)
})
}
async function loadModelFromUrl(url, fitMode = 'ground') {
const extension = getExtensionFromUrl(url)
@ -279,7 +249,6 @@ export default function Viewer({
showGrid = true,
showShadows = true,
showAlbedo = false,
showWireframe = false,
lightIntensity = 2.2,
fitMode = 'ground'
}) {
@ -325,9 +294,8 @@ export default function Viewer({
const modelClone = modelState.object.clone(true)
applyDisplayMaterial(modelClone, showNormals, showShadows, showAlbedo)
applyWireframeOverlay(modelClone, showWireframe)
return modelClone
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo, showWireframe])
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo])
const cameraTarget = modelState?.modelUrl === modelUrl ? modelState.target : new THREE.Vector3(0, 0.75, 0)
const cameraPosition = modelState?.modelUrl === modelUrl ? modelState.cameraPosition : new THREE.Vector3(3, 3, 5)

View file

@ -1,465 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useProjects } from '../../context/ProjectContext'
import { useSettings } from '../../context/SettingsContext.shared'
import { useNotifications } from '../../context/NotificationContext'
import { useWorkflowJobs } from '../../context/WorkflowJobsContext'
import {
IMAGE_API_LIST,
normalizeCustomApiType,
filterImageGenerationWorkflows,
filterImageEditWorkflows,
getWorkflowParameterValueType,
isFileWorkflowValueType,
getWorkflowFileInputAccept,
createComfyExecutionId
} from '../../utils/graphHelpers'
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import AssetSelectorModal from '../AssetSelectorModal'
// An image/file input value chosen from the Assets library (vs an uploaded File).
function isAssetReferenceValue(value) {
return value && typeof value === 'object' && !(value instanceof File) && typeof value.source === 'string'
}
function describeFileValue(value, valueType) {
if (value instanceof File) return value.name
if (isAssetReferenceValue(value)) return value.name || 'Selected asset'
return `Choose ${valueType} file`
}
// Merge image-generation + image-edit workflows, de-duplicated by id and
// sorted alphabetically by name.
function collectImageWorkflows(workflows = []) {
const seen = new Set()
const result = []
for (const wf of [...filterImageGenerationWorkflows(workflows), ...filterImageEditWorkflows(workflows)]) {
if (seen.has(wf.id)) continue
seen.add(wf.id)
result.push(wf)
}
return result.sort((a, b) =>
String(a.name || '').localeCompare(String(b.name || ''), undefined, { sensitivity: 'base' })
)
}
export default function BoardAiPanel({ projectId, projectName, boardId, onImageGenerated, getSelectedBoardImage }) {
const { getComfyWorkflows, runComfyWorkflow, generateImage, resolveAssetSourceReference } = useProjects()
const { settings } = useSettings()
const { addNotification } = useNotifications()
const { registerJob, completeJob } = useWorkflowJobs()
const [tab, setTab] = useState('comfy')
const [workflows, setWorkflows] = useState([])
const [selectedWorkflowId, setSelectedWorkflowId] = useState('')
const [comfyInputs, setComfyInputs] = useState({})
const [comfyName, setComfyName] = useState('')
const [selectedApi, setSelectedApi] = useState('')
const [apiPrompt, setApiPrompt] = useState('')
const [apiName, setApiName] = useState('')
const [running, setRunning] = useState(false)
const [status, setStatus] = useState(null)
const [assetPickerParam, setAssetPickerParam] = useState(null) // { paramId, valueType }
const fileInputsRef = useRef({})
const customApis = useMemo(() => settings?.apis?.custom || [], [settings])
const imageApis = useMemo(() => ([
...IMAGE_API_LIST,
...customApis
.filter(api => normalizeCustomApiType(api?.type) === 'image-generation')
.map(api => ({ id: `custom_${api.id}`, name: api.name }))
]), [customApis])
useEffect(() => {
let cancelled = false
getComfyWorkflows()
.then(list => { if (!cancelled) setWorkflows(collectImageWorkflows(list || [])) })
.catch(err => console.error('Failed to load ComfyUI workflows', err))
return () => { cancelled = true }
}, [getComfyWorkflows])
useEffect(() => {
if (imageApis.length && !selectedApi) setSelectedApi(imageApis[0].id)
}, [imageApis, selectedApi])
// Workflow ids are numeric but <select> values are strings — match loosely
// (same approach as GraphAssetNode) so the selected workflow resolves.
const selectedWorkflow = useMemo(
() => workflows.find(wf => String(wf.id) === String(selectedWorkflowId)) || null,
[workflows, selectedWorkflowId]
)
const handleSelectWorkflow = (id) => {
setSelectedWorkflowId(id)
const wf = workflows.find(w => String(w.id) === String(id))
setComfyInputs(wf ? getComfyDraftFromWorkflow(wf).inputs : {})
}
const setInputValue = (paramId, value) => {
setComfyInputs(prev => ({ ...prev, [paramId]: value }))
}
const flash = (message, tone = 'info') => setStatus({ message, tone })
// Resolve a chosen file to a source reference (edit: for edits so the output
// nests under the root ancestor; asset: for roots) and bind it to a parameter.
const bindSourceForParam = async (paramId, valueType, filePath, fallbackName) => {
const { sourceReference } = await resolveAssetSourceReference(
projectId,
valueType === 'mesh' ? 'mesh' : 'image',
filePath
)
setInputValue(paramId, { source: sourceReference, name: fallbackName || 'Selected asset' })
}
const handleUseSelectedImage = async (paramId, valueType) => {
const selected = getSelectedBoardImage?.()
if (!selected?.filename) {
flash('Select an image on the board first.', 'error')
return
}
try {
await bindSourceForParam(paramId, valueType, selected.filename, 'Selected board image')
} catch (err) {
console.error('Failed to use selected board image', err)
flash(err.message || 'Failed to use the selected image.', 'error')
}
}
const runComfy = async () => {
if (!selectedWorkflow) { flash('Select a workflow first.', 'error'); return }
// Validate required file/string params (numbers/booleans always have a value).
for (const parameter of selectedWorkflow.parameters || []) {
const valueType = getWorkflowParameterValueType(parameter)
const value = comfyInputs[parameter.id]
if (isFileWorkflowValueType(valueType) && !(value instanceof File) && !isAssetReferenceValue(value)) {
flash(`Select a ${valueType} for ${parameter.name}.`, 'error')
return
}
if (valueType === 'string' && parameter.required && !String(value ?? '').trim()) {
flash(`Enter a value for ${parameter.name}.`, 'error')
return
}
}
const promptId = createComfyExecutionId('comfy-prompt')
const clientId = createComfyExecutionId('comfy-client')
setRunning(true)
flash('Running ComfyUI workflow…')
registerJob({
id: promptId,
projectId,
projectName,
page: 'board',
targetId: boardId,
kind: 'image',
label: selectedWorkflow.name
})
try {
const assets = await runComfyWorkflow(projectId, {
workflowId: selectedWorkflow.id,
inputs: comfyInputs,
name: comfyName.trim() || undefined,
clientId,
promptId,
persistProcessingCard: false,
// Detached: image-generation outputs (no image input) become root project
// assets with no Kanban card. autoParentFromInputs: when an image input is
// an asset, the output is saved as an Edit of that source image instead.
detachedAsset: true,
autoParentFromInputs: true
})
const imageAssets = (Array.isArray(assets) ? assets : [assets]).filter(
a => a && (a.type ? a.type === 'image' : true)
)
for (const asset of imageAssets) {
await onImageGenerated(asset)
}
completeJob(promptId, { status: 'completed' })
flash(`Added ${imageAssets.length} image${imageAssets.length === 1 ? '' : 's'} to the board.`, 'success')
} catch (err) {
console.error('ComfyUI board generation failed', err)
completeJob(promptId, { status: 'error', error: err.message })
flash(err.message || 'ComfyUI workflow failed.', 'error')
addNotification({ title: 'Board generation failed', message: err.message || 'ComfyUI workflow failed', tone: 'error', source: selectedWorkflow.name, projectId })
} finally {
setRunning(false)
}
}
const runApi = async () => {
if (!selectedApi) { flash('Select an API.', 'error'); return }
if (!apiPrompt.trim()) { flash('Enter a prompt.', 'error'); return }
const name = apiName.trim()
if (!name) { flash('Enter a name for the image.', 'error'); return }
setRunning(true)
flash('Generating image…')
try {
const asset = await generateImage(projectId, { selectedApi, prompt: apiPrompt.trim(), name, detachedAsset: true })
await onImageGenerated(asset)
flash('Image added to the board.', 'success')
} catch (err) {
console.error('API board generation failed', err)
flash(err.message || 'Image generation failed.', 'error')
addNotification({ title: 'Board generation failed', message: err.message || 'Image generation failed', tone: 'error', source: imageApis.find(a => a.id === selectedApi)?.name || 'Image API', projectId })
} finally {
setRunning(false)
}
}
const renderParameterField = (parameter) => {
const valueType = getWorkflowParameterValueType(parameter)
const value = comfyInputs[parameter.id]
const label = parameter.label || parameter.name || parameter.id
if (isFileWorkflowValueType(valueType)) {
const hasValue = value instanceof File || isAssetReferenceValue(value)
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<button
type="button"
className={`board-ai-panel__file-btn ${hasValue ? 'board-ai-panel__file-btn--set' : ''}`}
onClick={() => fileInputsRef.current[parameter.id]?.click()}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>upload</span>
{describeFileValue(value, valueType)}
</button>
<div className="board-ai-panel__file-actions">
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => fileInputsRef.current[parameter.id]?.click()}
>
From computer
</button>
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => setAssetPickerParam({ paramId: parameter.id, valueType })}
>
From Assets
</button>
{valueType === 'image' && (
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => handleUseSelectedImage(parameter.id, valueType)}
title="Use the image currently selected on the board"
>
Selected image
</button>
)}
</div>
<input
ref={(el) => { fileInputsRef.current[parameter.id] = el }}
type="file"
accept={getWorkflowFileInputAccept(valueType)}
style={{ display: 'none' }}
onChange={(e) => setInputValue(parameter.id, e.target.files?.[0] || null)}
/>
</div>
)
}
if (valueType === 'boolean') {
return (
<label className="board-ai-panel__field" key={parameter.id} style={{ flexDirection: 'row', alignItems: 'center', gap: '0.5rem' }}>
<input
type="checkbox"
checked={Boolean(value)}
onChange={(e) => setInputValue(parameter.id, e.target.checked)}
/>
<span className="board-ai-panel__label" style={{ margin: 0 }}>{label}</span>
</label>
)
}
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<select
className="board-ai-panel__select"
value={value == null ? '' : String(value)}
onChange={(e) => setInputValue(parameter.id, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
)
}
if (valueType === 'number') {
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<input
className="board-ai-panel__input"
type="number"
value={value ?? ''}
onChange={(e) => setInputValue(parameter.id, e.target.value === '' ? '' : Number(e.target.value))}
/>
</div>
)
}
// string / json / anything else — multiline like the Graph Image node.
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<textarea
className="board-ai-panel__textarea"
value={typeof value === 'string' ? value : (value == null ? '' : JSON.stringify(value, null, 2))}
onChange={(e) => setInputValue(parameter.id, e.target.value)}
/>
</div>
)
}
return (
<aside className="board-ai-panel">
<div className="board-ai-panel__head">
<div className="board-ai-panel__title">Generate images</div>
<div className="board-ai-panel__subtitle">Saved to Assets and placed on the board</div>
</div>
<div className="board-ai-panel__body">
<div className="board-ai-panel__tabs">
<button
type="button"
className={`board-ai-panel__tab ${tab === 'comfy' ? 'board-ai-panel__tab--active' : ''}`}
onClick={() => setTab('comfy')}
>
ComfyUI
</button>
<button
type="button"
className={`board-ai-panel__tab ${tab === 'api' ? 'board-ai-panel__tab--active' : ''}`}
onClick={() => setTab('api')}
>
External API
</button>
</div>
{tab === 'comfy' ? (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Workflow</span>
<select
className="board-ai-panel__select"
value={selectedWorkflowId}
onChange={(e) => handleSelectWorkflow(e.target.value)}
>
<option value="">Select a workflow…</option>
{workflows.map(wf => (
<option key={wf.id} value={wf.id}>{wf.name}</option>
))}
</select>
{workflows.length === 0 && (
<span className="board-ai-panel__hint" style={{ marginTop: '0.3rem' }}>
No image workflows found. Import one from the Assets library.
</span>
)}
</div>
{selectedWorkflow && (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Image name (optional)</span>
<input
className="board-ai-panel__input"
value={comfyName}
onChange={(e) => setComfyName(e.target.value)}
placeholder={selectedWorkflow.name}
/>
</div>
{(selectedWorkflow.parameters || []).map(renderParameterField)}
</>
)}
<button className="board-ai-panel__run" onClick={runComfy} disabled={running || !selectedWorkflow}>
{running ? 'Working…' : 'Run workflow'}
</button>
</>
) : (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">API</span>
<select
className="board-ai-panel__select"
value={selectedApi}
onChange={(e) => setSelectedApi(e.target.value)}
>
{imageApis.map(api => (
<option key={api.id} value={api.id}>{api.name}</option>
))}
</select>
</div>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Image name</span>
<input
className="board-ai-panel__input"
value={apiName}
onChange={(e) => setApiName(e.target.value)}
placeholder="Concept sketch"
/>
</div>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Prompt</span>
<textarea
className="board-ai-panel__textarea"
value={apiPrompt}
onChange={(e) => setApiPrompt(e.target.value)}
placeholder="Describe the image to generate…"
/>
</div>
<button className="board-ai-panel__run" onClick={runApi} disabled={running}>
{running ? 'Working…' : 'Generate image'}
</button>
</>
)}
{status && (
<div className={`board-ai-panel__status ${status.tone === 'error' ? 'board-ai-panel__status--error' : ''}`}>
{status.message}
</div>
)}
</div>
{assetPickerParam && (
<AssetSelectorModal
assetType={assetPickerParam.valueType === 'mesh' ? 'mesh' : 'image'}
showEdits
onSelect={async (asset) => {
const picker = assetPickerParam
setAssetPickerParam(null)
if (!asset) return
try {
// Resolve to the right reference: edits nest under the root ancestor;
// roots reuse the project asset or attach a library file if needed.
await bindSourceForParam(
picker.paramId,
picker.valueType,
asset.filename || asset.filePath,
asset.name
)
} catch (err) {
console.error('Failed to use selected asset for board input', err)
flash(err.message || 'Failed to use the selected asset.', 'error')
}
}}
onClose={() => setAssetPickerParam(null)}
/>
)}
</aside>
)
}

View file

@ -1,158 +0,0 @@
import { useEffect, useRef, useState } from 'react'
export default function BoardSwitcher({
projectId,
boards = [],
currentBoard,
onBoardsChanged,
createBoard,
updateBoard,
deleteBoard,
onSelect
}) {
const [open, setOpen] = useState(false)
const [renamingId, setRenamingId] = useState(null)
const [renameValue, setRenameValue] = useState('')
const [busy, setBusy] = useState(false)
const rootRef = useRef(null)
useEffect(() => {
if (!open) return undefined
const onPointerDown = (event) => {
if (rootRef.current && !rootRef.current.contains(event.target)) {
setOpen(false)
setRenamingId(null)
}
}
document.addEventListener('mousedown', onPointerDown)
return () => document.removeEventListener('mousedown', onPointerDown)
}, [open])
const handleCreate = async () => {
if (busy) return
setBusy(true)
try {
const name = `Board ${boards.length + 1}`
const created = await createBoard(projectId, name)
onBoardsChanged()
setOpen(false)
onSelect(created.id)
} catch (err) {
console.error('Failed to create board', err)
} finally {
setBusy(false)
}
}
const startRename = (board) => {
setRenamingId(board.id)
setRenameValue(board.name)
}
const commitRename = async (board) => {
const name = renameValue.trim()
setRenamingId(null)
if (!name || name === board.name) return
try {
await updateBoard(board.id, { name })
onBoardsChanged()
} catch (err) {
console.error('Failed to rename board', err)
}
}
const handleDelete = async (board) => {
if (boards.length <= 1) {
window.alert('A project must keep at least one board.')
return
}
if (!window.confirm(`Delete board "${board.name}"? This cannot be undone.`)) return
try {
await deleteBoard(board.id)
const remaining = boards.filter(b => String(b.id) !== String(board.id))
onBoardsChanged()
if (String(board.id) === String(currentBoard?.id) && remaining[0]) {
onSelect(remaining[0].id)
}
} catch (err) {
console.error('Failed to delete board', err)
}
}
return (
<div className="board-switcher" ref={rootRef}>
<button
type="button"
className="board-switcher__current"
onClick={() => setOpen(o => !o)}
title="Switch board"
>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>dashboard</span>
<span className="board-switcher__name">{currentBoard?.name || 'Select board'}</span>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>expand_more</span>
</button>
<button type="button" className="board-switcher__btn" onClick={handleCreate} disabled={busy}>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add</span>
New
</button>
{open && (
<div className="board-switcher__menu" role="menu">
{boards.map(board => {
const isActive = String(board.id) === String(currentBoard?.id)
const isRenaming = renamingId === board.id
return (
<div
key={board.id}
className={`board-switcher__item ${isActive ? 'board-switcher__item--active' : ''}`}
onClick={() => {
if (isRenaming) return
setOpen(false)
onSelect(board.id)
}}
>
{isRenaming ? (
<input
className="board-switcher__input"
value={renameValue}
autoFocus
onClick={(e) => e.stopPropagation()}
onChange={(e) => setRenameValue(e.target.value)}
onBlur={() => commitRename(board)}
onKeyDown={(e) => {
if (e.key === 'Enter') commitRename(board)
if (e.key === 'Escape') setRenamingId(null)
}}
/>
) : (
<>
<span className="board-switcher__name">{board.name}</span>
<span className="board-switcher__item-actions">
<button
type="button"
className="board-switcher__icon-btn"
title="Rename board"
onClick={(e) => { e.stopPropagation(); startRename(board) }}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>edit</span>
</button>
<button
type="button"
className="board-switcher__icon-btn"
title="Delete board"
onClick={(e) => { e.stopPropagation(); handleDelete(board) }}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>delete</span>
</button>
</span>
</>
)}
</div>
)
})}
</div>
)}
</div>
)
}

View file

@ -13,7 +13,6 @@ import {
createComfyExecutionId
} from '../../utils/graphHelpers'
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import { buildAssetUrl } from '../../utils/meshTexturing'
import './ComfyTextGenModal.css'
@ -325,24 +324,6 @@ export default function ComfyTextGenModal({ open, onClose, onResult }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<div key={parameter.id} className="comfy-tg-field">
<label className="comfy-tg-label">{parameter.name} • {valueType.toUpperCase()}</label>
<select
className="comfy-tg-input"
value={value == null ? '' : String(value)}
onChange={event => handleInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
)
}
if (valueType === 'number') {
return (
<div key={parameter.id} className="comfy-tg-field">

View file

@ -42,7 +42,6 @@ import {
resolveImageSourceOption,
resolveSelectedInputSource
} from '../../utils/graphHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
import LastActionInfo from './LastActionInfo'
@ -179,21 +178,6 @@ const GraphAssetNode = memo(function GraphAssetNode({ data }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
if (enumOptions) {
return (
<select
className="params-card__select nodrag"
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
)
}
if (valueType === 'string' || parameter.type === 'json') {
return (
<div className="comfy-textfield-wrap nodrag">
@ -492,18 +476,21 @@ const GraphAssetNode = memo(function GraphAssetNode({ data }) {
From Assets
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageModeSelect?.(data.id, 'comfy')}>
ComfyUI Workflow
Generate · ComfyUI Workflow
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageModeSelect?.(data.id, 'api')}>
API
Generate · Remote API
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageEditModeSelect?.(data.id, 'edit-api')}>
Edit · API
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageEditModeSelect?.(data.id, 'edit-comfy')}>
Edit · ComfyUI Workflow
</button>
</>
)}
{isMeshGen ? (
<>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onMeshGenModeSelect?.(data.id, 'local')}>
Local Computer
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onMeshGenModeSelect?.(data.id, 'assets')}>
Assets
</button>

View file

@ -14,7 +14,6 @@ import {
isFileWorkflowValueType,
resolveSelectedInputSource
} from '../../utils/graphHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
import LastActionInfo from './LastActionInfo'
@ -78,21 +77,6 @@ const GraphValueNode = memo(function GraphValueNode({ data }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
if (enumOptions) {
return (
<select
className="params-card__select nodrag"
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
)
}
if (valueType === 'string' || parameter.type === 'json') {
return (
<div className="comfy-textfield-wrap nodrag">

View file

@ -1,29 +1,10 @@
// Renders a single non-image ComfyUI workflow parameter (boolean checkbox or
// text/number input). Shared by the AI control panels. Presentational.
import { getValueType } from '../../../utils/imageEditorCanvas'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../../utils/workflowEnums'
import ComfyTextButton from '../../comfy/ComfyTextButton'
export default function WorkflowParameterField({ parameter, value, onChange }) {
const valueType = getValueType(parameter)
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<label className="image-editor-label">
{parameter.name}
<select
className="image-editor-input"
value={value == null ? '' : String(value)}
onChange={event => onChange(parameter.id, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</label>
)
}
if (valueType === 'boolean') {
return (

View file

@ -11,7 +11,6 @@ import {
isTencentMeshGenerationApi,
isTripoMeshGenerationApi
} from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
// A single Kanban board card (image / image-edit / mesh-gen / mesh-edit / texturing).
// Presentational: all board state, derived selectors, and handlers are passed in
@ -52,7 +51,6 @@ export default function KanbanImageCard({
handleCardDragStart,
handleCardDragEnd,
openImageSourceMenu,
openMeshSourceMenu,
handleRemoveImageCard,
openMeshPreview,
handleRemoveImage,
@ -84,16 +82,12 @@ export default function KanbanImageCard({
const isMeshGenCard = card.kanbanColumnId === 3
const isMeshEditCard = card.kanbanColumnId === 4
const isTexturingCard = card.kanbanColumnId === 5
const isRiggingCard = card.kanbanColumnId === 6
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard || isRiggingCard
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard
const carouselItems = getCardPreviewItems(card, showAttributes)
const useAssetCarousel = carouselItems.length > 0
const previewAssets = useAssetCarousel
? card.assets
: isMeshWorkflowCard && (card.meshAssets?.length || 0) > 0
? card.meshAssets
// Images column: meshes attached via "Add more meshes" sit alongside the images.
: (card.allAssets?.length ? card.allAssets : card.assets)
const previewAssets = isMeshWorkflowCard && (card.meshAssets?.length || 0) > 0 && !useAssetCarousel
? card.meshAssets
: card.assets
const totalPages = useAssetCarousel
? Math.max(1, carouselItems.length)
: Math.max(1, Math.ceil(previewAssets.length / 4))
@ -107,8 +101,8 @@ export default function KanbanImageCard({
const availableActionApis = getApiOptionsForCard(card)
const availableActionWorkflows = getWorkflowsForCard(card)
const selectedActionWorkflow = availableActionWorkflows.find(workflow => workflow.id == imageEditDraft?.workflowId) || null
const apiSourceGroups = isMeshEditCard || isTexturingCard || isRiggingCard ? meshSourceGroups : imageSourceGroups
const apiSourceValueType = isMeshEditCard || isTexturingCard || isRiggingCard ? 'mesh' : 'image'
const apiSourceGroups = isMeshEditCard || isTexturingCard ? meshSourceGroups : imageSourceGroups
const apiSourceValueType = isMeshEditCard || isTexturingCard ? 'mesh' : 'image'
return (
<div
@ -119,28 +113,19 @@ export default function KanbanImageCard({
onDragEnd={handleCardDragEnd}
>
<div className="image-card__actions">
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openMeshSourceMenu(card.id)
}}
title="Add more meshes"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>deployed_code</span>
</button>
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openImageSourceMenu(card.id)
}}
title="Add more images"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add_photo_alternate</span>
</button>
{!showAttributes && (
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openImageSourceMenu(card.id)
}}
title="Add more images"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add_photo_alternate</span>
</button>
)}
<button
className="image-card__action-btn image-card__delete"
disabled={cardLocked}
@ -162,12 +147,9 @@ export default function KanbanImageCard({
? Math.min(imageEditPreviewIndexes[asset.id] || 0, Math.max(0, displayItems.length - 1))
: 0
const previewItem = showAttributes ? (displayItems[previewIndex] || displayItems[0]) : asset
// Meshes rendered outside the carousel carry their thumbnail on
// `thumbnail`; the carousel pre-resolves it into `previewFilename`.
const meshThumbnail = useAssetCarousel ? asset.previewFilename : (asset.type === 'mesh' ? asset.thumbnail : null)
const previewFilename = useAssetCarousel
? (asset.previewFilename || asset.filename)
: (showAttributes ? previewItem?.filename : (meshThumbnail || asset.filename))
: (showAttributes ? previewItem?.filename : asset.filename)
const previewName = useAssetCarousel
? asset.name
: (showAttributes ? previewItem?.name : asset.name)
@ -198,7 +180,7 @@ export default function KanbanImageCard({
} : undefined}
>
{previewType === 'mesh' && previewUrl ? (
meshThumbnail ? (
asset.previewFilename ? (
<img
src={previewUrl}
alt={previewName}
@ -230,13 +212,13 @@ export default function KanbanImageCard({
e.stopPropagation()
handleRemoveImage(asset.id)
}}
title={previewType === 'mesh' ? 'Remove mesh' : 'Remove image'}
title="Remove image"
>
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>close</span>
</button>
)}
{useAssetCarousel && previewType === 'mesh' && sourceAsset?.id && (
{previewType === 'mesh' && sourceAsset?.id && (
<button
className="image-card__thumb-remove image-card__thumb-remove--left"
disabled={cardLocked}
@ -446,7 +428,7 @@ export default function KanbanImageCard({
{imageEditDraft.mode === 'api' ? (
<>
<div className="params-card__field">
<label className="params-card__label font-label">{isMeshEditCard || isTexturingCard || isRiggingCard ? 'Mesh' : 'Image'}</label>
<label className="params-card__label font-label">{isMeshEditCard || isTexturingCard ? 'Mesh' : 'Image'}</label>
<select
className="image-card__attribute-select"
value={imageEditDraft.selectedAssetId}
@ -455,7 +437,7 @@ export default function KanbanImageCard({
{isMeshGenCard && (isTencentMeshGenerationApi(imageEditDraft.selectedApi) || isTripoMeshGenerationApi(imageEditDraft.selectedApi)) && (
<option value="">No image source (use prompt)</option>
)}
{apiSourceGroups.length === 0 && <option value="">{isMeshEditCard || isTexturingCard || isRiggingCard ? 'No meshes available' : 'No images available'}</option>}
{apiSourceGroups.length === 0 && <option value="">{isMeshEditCard || isTexturingCard ? 'No meshes available' : 'No images available'}</option>}
{apiSourceGroups.map(group => (
<optgroup key={group.asset.id} label={group.asset.name}>
{group.options.map(option => (
@ -604,12 +586,6 @@ export default function KanbanImageCard({
}
const sourceOptions = getAttributeOptionsForCard(card.id, valueType === 'number' ? 'Number' : 'Text')
// An attribute-bound value is shown read-only, so the dropdown
// reflects whichever value is actually in play.
const enumSelectValue = binding.source === 'custom'
? (binding.customValue == null ? '' : String(binding.customValue))
: String(resolvedValue ?? '')
const enumOptions = getWorkflowEnumOptions(parameter, enumSelectValue)
return (
<div key={parameter.id} className="params-card__field">
@ -623,18 +599,7 @@ export default function KanbanImageCard({
<option key={option.id} value={option.id}>{option.label}</option>
))}
</select>
{enumOptions ? (
<select
className="image-card__attribute-select"
value={enumSelectValue}
onChange={event => handleImageEditParameterValueChange(card, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
disabled={binding.source !== 'custom'}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'string' ? (
{valueType === 'string' ? (
<div className="comfy-textfield-wrap">
<textarea
className="gen-prompt-input image-card__param-textarea"
@ -673,8 +638,6 @@ export default function KanbanImageCard({
? 'No compatible ComfyUI workflow available for mesh edits.'
: isTexturingCard
? 'No compatible ComfyUI workflow available for mesh texturing.'
: isRiggingCard
? 'No compatible ComfyUI workflow available for mesh rigging.'
: 'No compatible ComfyUI workflow available for image edits.'}</span>
</div>
)}

View file

@ -1,5 +1,4 @@
import { getWorkflowValueType } from '../../utils/meshTexturing'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
// Projection-mode left panel (projection setup, AI workflow + image-input
@ -190,26 +189,11 @@ export default function ProjectionToolsPanel({
{projectionWorkflowParameters.map(parameter => {
const valueType = getWorkflowValueType(parameter)
const currentValue = projectionWorkflowInputs?.[parameter.id]
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
return (
<label key={parameter.id} className="mesh-editor-workflow-field">
<span>{parameter.name}</span>
{enumOptions ? (
<select
className="mesh-editor-panel__input"
value={currentValue == null ? '' : String(currentValue)}
onChange={event => setProjectionWorkflowInputs(current => ({
...current,
[parameter.id]: resolveWorkflowEnumValue(parameter, event.target.value)
}))}
disabled={!!texturingUnavailableReason || projecting || projectionRebuilding}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'boolean' ? (
{valueType === 'boolean' ? (
<button
type="button"
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}

View file

@ -1,5 +1,4 @@
import { getWorkflowValueType } from '../../utils/meshTexturing'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
// Texturing-mode left panel (brush/crop/feather, AI workflow + image-input
@ -163,23 +162,11 @@ export default function TexturingToolsPanel({
{textureWorkflowParameters.map(parameter => {
const valueType = getWorkflowValueType(parameter)
const currentValue = textureWorkflowInputs?.[parameter.id]
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
return (
<label key={parameter.id} className="mesh-editor-workflow-field">
<span>{parameter.name}</span>
{enumOptions ? (
<select
className="mesh-editor-panel__input"
value={currentValue == null ? '' : String(currentValue)}
onChange={event => handleTextureWorkflowInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
disabled={!!texturingUnavailableReason || !!pendingPatch}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'boolean' ? (
{valueType === 'boolean' ? (
<button
type="button"
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}

View file

@ -79,30 +79,6 @@ export function ProjectProvider({ children }) {
fetchProjects()
}, [fetchProjects])
// App-level event stream: the backend publishes `externalMutation` events
// when something outside this browser (e.g. an MCP client / AI agent)
// changes data. Refresh the project list and let open pages refetch via a
// window event so the UI doesn't sit on stale state until a manual reload.
useEffect(() => {
if (typeof EventSource === 'undefined') return undefined
const eventSource = new EventSource(`${API_BASE}/events`)
eventSource.onmessage = (event) => {
let payload
try {
payload = JSON.parse(event.data)
} catch {
return
}
if (payload?.type !== 'externalMutation') return
fetchProjects()
window.dispatchEvent(new CustomEvent('genstudio:external-mutation', { detail: payload }))
}
eventSource.onerror = () => {}
return () => eventSource.close()
}, [fetchProjects])
const createProject = async (projectData) => {
try {
const res = await fetch(`${API_BASE}/projects`, {
@ -167,22 +143,6 @@ export function ProjectProvider({ children }) {
return data
}
const runMeshRiggingApi = async (projectId, rigData) => {
const res = await fetch(`${API_BASE}/meshes/rigging`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ projectId, ...rigData })
})
const data = await res.json()
if (!res.ok) {
throw new Error(data?.error || 'Failed to run mesh rigging API')
}
return data
}
const runMeshEditApi = async (projectId, editData) => {
const res = await fetch(`${API_BASE}/meshes/edit`, {
method: 'POST',
@ -480,89 +440,12 @@ export function ProjectProvider({ children }) {
}
}
// Persist the Graph canvas viewport (pan + zoom) without triggering a full
// projects refetch — this fires on every pan/zoom end, so it must stay cheap.
const saveGraphViewport = async (id, viewport) => {
try {
await fetch(`${API_BASE}/projects/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ graphViewport: viewport })
})
} catch (err) {
console.error('Failed to save graph viewport:', err)
}
}
const deleteProject = async (id, { deleteAssets = false } = {}) => {
const query = deleteAssets ? '?deleteAssets=true' : ''
await fetch(`${API_BASE}/projects/${id}${query}`, { method: 'DELETE' })
await fetchProjects()
}
// ---- Brainstorming Boards ------------------------------------------------
const getProjectBoards = async (projectId) => {
const res = await fetch(`${API_BASE}/boards?projectId=${projectId}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to load boards')
return data
}
const getBoard = async (boardId) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to load board')
return data
}
const createBoard = async (projectId, name = 'Untitled Board') => {
const res = await fetch(`${API_BASE}/boards`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ projectId, name })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to create board')
return data
}
const updateBoard = async (boardId, patch) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch)
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to update board')
return data
}
// Save used by the board's debounced autosave. Never throws into the render
// path (mirrors saveGraphViewport); returns true on success so the UI can
// surface a save indicator.
const saveBoardState = async (boardId, state) => {
try {
const res = await fetch(`${API_BASE}/boards/${boardId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state })
})
return res.ok
} catch (err) {
console.error('Failed to save board state:', err)
return false
}
}
const deleteBoard = async (boardId) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`, { method: 'DELETE' })
if (!res.ok && res.status !== 204) {
const data = await res.json().catch(() => ({}))
throw new Error(data?.error || 'Failed to delete board')
}
}
const exportProject = async (id, { folder, name }) => {
const res = await fetch(`${API_BASE}/projects/${id}/export`, {
method: 'POST',
@ -590,9 +473,8 @@ export function ProjectProvider({ children }) {
return data
}
const getProjectAssets = async (projectId, { includeChildren = false } = {}) => {
const query = includeChildren ? '&includeChildren=true' : ''
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}${query}`)
const getProjectAssets = async (projectId) => {
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}`)
return await res.json()
}
@ -853,16 +735,6 @@ export function ProjectProvider({ children }) {
return await res.json();
}
// Resolve a file (served filename or stored path) to a workflow source
// reference (edit: for edits, asset: for roots) so board edits nest correctly.
const resolveAssetSourceReference = async (projectId, type, filePath) => {
const params = new URLSearchParams({ projectId: String(projectId), type: type || 'image', filePath })
const res = await fetch(`${API_BASE}/assets/resolve-source?${params.toString()}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to resolve asset source')
return data
}
const attachExistingAsset = async (projectId, assetData) => {
const res = await fetch(`${API_BASE}/assets/link`, {
method: 'POST',
@ -879,39 +751,6 @@ export function ProjectProvider({ children }) {
return data
}
// Attach any EXISTING asset — a root, an image edit or a mesh version — to a
// project. Membership lives in Assets_Projects, so this needs no card.
const linkAssetToProject = async (projectId, assetId, { cascadeChildren = false } = {}) => {
const res = await fetch(`${API_BASE}/projects/${projectId}/assets`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetId, cascadeChildren })
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(data?.error || 'Failed to link asset to project')
}
return data
}
const unlinkAssetFromProject = async (projectId, assetId, { cascadeChildren = true } = {}) => {
const query = cascadeChildren ? '' : '?cascadeChildren=false'
const res = await fetch(`${API_BASE}/projects/${projectId}/assets/${assetId}${query}`, {
method: 'DELETE'
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(data?.error || 'Failed to unlink asset from project')
}
return data
}
const deleteLibraryAsset = async ({ type, filename, force = false }) => {
const params = new URLSearchParams({ type, filename })
if (force) {
@ -937,9 +776,8 @@ export function ProjectProvider({ children }) {
return data
}
const deleteAsset = async (assetId, { projectId = null } = {}) => {
const query = projectId ? `?projectId=${projectId}` : ''
const res = await fetch(`${API_BASE}/assets/${assetId}${query}`, { method: 'DELETE' })
const deleteAsset = async (assetId) => {
const res = await fetch(`${API_BASE}/assets/${assetId}`, { method: 'DELETE' })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
@ -1113,14 +951,6 @@ export function ProjectProvider({ children }) {
if (workflowData.persistGeneratedAssets === false) {
formData.append('persistGeneratedAssets', 'false')
}
if (workflowData.detachedAsset === true) {
formData.append('detachedAsset', 'true')
}
// The app manages its own edit/version saving (e.g. image edits via
// /image-edits/comfy, mesh versions via an explicit parentAssetId), and its
// generate flows must create new root assets — so opt out of the server's
// input-based parent inference unless a caller explicitly asks for it.
formData.append('autoParentFromInputs', workflowData.autoParentFromInputs === true ? 'true' : 'false')
Object.entries(workflowData.inputs || {}).forEach(([key, value]) => {
if (typeof File !== 'undefined' && value instanceof File) {
@ -1323,17 +1153,10 @@ export function ProjectProvider({ children }) {
loading,
createProject,
updateProject,
saveGraphViewport,
getProject,
deleteProject,
exportProject,
importProject,
getProjectBoards,
getBoard,
createBoard,
updateBoard,
saveBoardState,
deleteBoard,
getProjectAssets,
getProjectCards,
getProjectNodes,
@ -1353,9 +1176,6 @@ export function ProjectProvider({ children }) {
getPaintDocument,
savePaintDocument,
attachExistingAsset,
linkAssetToProject,
unlinkAssetFromProject,
resolveAssetSourceReference,
deleteAsset,
moveKanbanCard,
deleteCard,
@ -1379,7 +1199,6 @@ export function ProjectProvider({ children }) {
queryHitemMeshGenerationResult,
runMeshEditApi,
runMeshTexturingApi,
runMeshRiggingApi,
runImageEditComfy,
generateImage,
getComfyWorkflows,

View file

@ -5,7 +5,7 @@ import { API_BASE } from '../config'
const DEFAULT_CUSTOM_API_TYPE = 'image-generation'
function normalizeCustomApiType(type) {
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing', 'mesh-rigging'].includes(type)
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing'].includes(type)
? type
: DEFAULT_CUSTOM_API_TYPE
}
@ -151,7 +151,6 @@ export function SettingsProvider({ children }) {
},
comfyui: {
path: '',
modelsPath: '',
url: 'http://127.0.0.1',
port: '8188'
},

View file

@ -519,23 +519,6 @@
color: var(--on-surface);
}
.library-textarea {
resize: vertical;
min-height: 4.5rem;
font-family: inherit;
line-height: 1.4;
}
/* Enum editor: label + textarea + hint sit tighter than a top-level form field. */
.library-selected-item .library-field {
gap: 0.35rem;
}
.library-hint {
font-size: 0.72rem;
color: var(--on-surface-variant);
}
.library-config-fields,
.library-config-actions,
.library-workflow-card__actions,
@ -707,14 +690,6 @@
object-fit: cover;
}
/* Mesh thumbnails are square renders (often with a transparent background); the
preview box is 16:10, so `cover` would crop a tall subject (head/feet) and
look zoomed in. `contain` shows the whole render, letterboxed over the card's
gradient background. */
.asset-card__preview--mesh-thumbnail .asset-card__image {
object-fit: contain;
}
.asset-card__mesh-icon {
font-size: 2.75rem;
color: var(--secondary);

View file

@ -8,17 +8,9 @@ import { useProjects } from '../context/ProjectContext'
import { createMeshThumbnailFile, isMeshFile } from '../utils/meshThumbnail'
import { parseAbrFile } from '../utils/brushAbr'
import { downloadShareableWorkflow, isShareableWorkflow } from '../utils/workflowShare'
import {
formatWorkflowEnumsInput,
isEnumWorkflowValueType,
parseWorkflowEnumsInput
} from '../utils/workflowEnums'
import './AssetsPage.css'
const ASSETS_PER_PAGE = 20
// The mesh grid is 3 columns wide, so 21 (7 full rows) paginates more cleanly
// than 20 (which leaves a ragged last row).
const MESHES_PER_PAGE = 21
const COMFY_VALUE_TYPES = [
{ value: 'string', label: 'String' },
{ value: 'number', label: 'Number' },
@ -79,8 +71,7 @@ function createSelectionMap(items, getLabel, isOutput = false, selected = false)
{
selected,
name: getLabel(item),
valueType: getDefaultValueType(item, isOutput),
enumsText: formatWorkflowEnumsInput(item?.enums)
valueType: getDefaultValueType(item, isOutput)
}
])
)
@ -98,8 +89,7 @@ function hydrateWorkflowSelection(workflow) {
{
selected: Boolean(selectedParameter),
name: selectedParameter?.name || input.name,
valueType: getDefaultValueType(selectedParameter || input),
enumsText: formatWorkflowEnumsInput(selectedParameter?.enums)
valueType: getDefaultValueType(selectedParameter || input)
}
]
})
@ -134,8 +124,7 @@ function selectWorkflowItem(setter, key, name, valueType) {
[key]: {
selected: true,
name: prev[key]?.name || name,
valueType: prev[key]?.valueType || valueType,
enumsText: prev[key]?.enumsText || ''
valueType: prev[key]?.valueType || valueType
}
}))
}
@ -462,15 +451,8 @@ export default function AssetsPage() {
// An asset can be linked to multiple projects, so resolve every project key it
// belongs to (falling back to the single projectId, then "Unassigned").
// Edits/versions carry their own project links, and an asset shown here is a
// root — so a root also counts as belonging to every project one of its
// children was attached to, otherwise attaching an edit would show nothing.
const getAssetProjectKeys = useCallback((asset) => {
const ids = [
...(Array.isArray(asset?.projectIds) ? asset.projectIds : []),
...(Array.isArray(asset?.children) ? asset.children : [])
.flatMap(child => (Array.isArray(child?.projectIds) ? child.projectIds : []))
]
const ids = Array.isArray(asset?.projectIds) ? asset.projectIds : []
const keys = [...new Set(
ids.filter(id => id !== null && id !== undefined).map(id => String(id))
)]
@ -535,12 +517,11 @@ export default function AssetsPage() {
}
const groupedAssets = buildGroupedAssets()
const assetsPerPage = activeSection === 'meshes' ? MESHES_PER_PAGE : ASSETS_PER_PAGE
const totalPages = Math.max(1, Math.ceil(activeAssets.length / assetsPerPage))
const pageStart = (currentPage - 1) * assetsPerPage
const paginatedAssets = activeAssets.slice(pageStart, pageStart + assetsPerPage)
const totalPages = Math.max(1, Math.ceil(activeAssets.length / ASSETS_PER_PAGE))
const pageStart = (currentPage - 1) * ASSETS_PER_PAGE
const paginatedAssets = activeAssets.slice(pageStart, pageStart + ASSETS_PER_PAGE)
const pageRangeStart = activeAssets.length === 0 ? 0 : pageStart + 1
const pageRangeEnd = Math.min(pageStart + assetsPerPage, activeAssets.length)
const pageRangeEnd = Math.min(pageStart + ASSETS_PER_PAGE, activeAssets.length)
useEffect(() => {
if (currentPage > totalPages) {
@ -1112,17 +1093,11 @@ export default function AssetsPage() {
const buildWorkflowPayload = () => {
const parameters = (inspectedWorkflow?.inputs || [])
.filter(input => selectedInputs[input.id]?.selected)
.map(input => {
const valueType = selectedInputs[input.id]?.valueType || getDefaultValueType(input)
return {
id: input.id,
name: selectedInputs[input.id]?.name || input.name,
valueType,
// Always sent so emptying the field clears a previously saved list.
enums: parseWorkflowEnumsInput(selectedInputs[input.id]?.enumsText, valueType)
}
})
.map(input => ({
id: input.id,
name: selectedInputs[input.id]?.name || input.name,
valueType: selectedInputs[input.id]?.valueType || getDefaultValueType(input)
}))
const outputs = (inspectedWorkflow?.outputs || [])
.filter(output => selectedOutputs[output.nodeId]?.selected)
@ -1685,30 +1660,6 @@ export default function AssetsPage() {
))}
</select>
</div>
{/* JSON inputs resolve to the String value type but are parsed as
JSON at run time, so they never get an allowed-value list. */}
{input.type !== 'json' && isEnumWorkflowValueType(selectedInputs[input.id]?.valueType || getDefaultValueType(input)) && (
<div className="library-field">
<label className="library-label">Allowed Values (optional)</label>
<textarea
className="library-input library-textarea"
rows={3}
value={selectedInputs[input.id]?.enumsText || ''}
onChange={event => setSelectedInputs(prev => ({
...prev,
[input.id]: {
...prev[input.id],
enumsText: event.target.value
}
}))}
placeholder={'1024\n1536'}
/>
<span className="library-hint">
One value per line. Leave empty for a free-form field; two or more values turn it into a dropdown everywhere the workflow is used.
</span>
</div>
)}
</div>
))}
</div>

View file

@ -1,357 +0,0 @@
.board-page {
display: flex;
flex-direction: column;
height: 100vh;
background: var(--background);
color: var(--on-surface);
overflow: hidden;
}
.board-page__bar {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 1rem;
border-bottom: 1px solid var(--outline-variant);
background: var(--surface-container-low);
flex: 0 0 auto;
}
.board-page__save {
font-size: 0.78rem;
font-family: var(--font-label);
color: var(--on-surface-variant);
margin-left: 0.25rem;
}
.board-page__save--saving { color: var(--primary-dim); }
.board-page__save--saved { color: var(--on-surface-variant); }
.board-page__save--error { color: var(--error); }
.board-page__body {
flex: 1 1 auto;
display: flex;
min-height: 0;
}
.board-page__canvas {
position: relative;
flex: 1 1 auto;
min-width: 0;
height: 100%;
}
/* Excalidraw needs an explicitly sized host. */
.board-page__canvas .excalidraw {
height: 100%;
width: 100%;
}
.board-page__loading,
.board-page__empty,
.board-page__error {
display: grid;
place-items: center;
height: 100%;
color: var(--on-surface-variant);
font-family: var(--font-body);
}
.board-page__error {
height: auto;
padding: 0.5rem 1rem;
color: var(--on-error-container);
background: var(--error-container);
place-items: start;
}
/* ── Board switcher ──────────────────────────────────────── */
.board-switcher {
display: flex;
align-items: center;
gap: 0.5rem;
position: relative;
}
.board-switcher__current {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.35rem 0.7rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container);
color: var(--on-surface);
font-family: var(--font-label);
font-size: 0.9rem;
cursor: pointer;
max-width: 260px;
}
.board-switcher__current:hover {
border-color: var(--outline);
}
.board-switcher__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.board-switcher__menu {
position: absolute;
top: calc(100% + 4px);
left: 0;
z-index: 40;
min-width: 240px;
max-height: 340px;
overflow-y: auto;
padding: 0.35rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container-high);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
}
.board-switcher__item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.4rem 0.5rem;
border-radius: var(--radius-sm);
cursor: pointer;
color: var(--on-surface);
font-size: 0.88rem;
}
.board-switcher__item:hover {
background: var(--surface-container-highest);
}
.board-switcher__item--active {
background: var(--surface-variant);
}
.board-switcher__item-actions {
display: flex;
gap: 0.15rem;
opacity: 0;
}
.board-switcher__item:hover .board-switcher__item-actions {
opacity: 1;
}
.board-switcher__icon-btn,
.board-switcher__btn {
display: inline-flex;
align-items: center;
gap: 0.3rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-sm);
background: var(--surface-container);
color: var(--on-surface);
cursor: pointer;
font-family: var(--font-label);
}
.board-switcher__icon-btn {
padding: 0.25rem;
border-color: transparent;
background: transparent;
color: var(--on-surface-variant);
}
.board-switcher__icon-btn:hover {
color: var(--on-surface);
background: var(--surface-container-lowest);
}
.board-switcher__btn {
padding: 0.35rem 0.6rem;
font-size: 0.85rem;
}
.board-switcher__btn:hover {
border-color: var(--outline);
}
.board-switcher__input {
flex: 1;
padding: 0.3rem 0.4rem;
border: 1px solid var(--outline);
border-radius: var(--radius-sm);
background: var(--surface-container-lowest);
color: var(--on-surface);
font-size: 0.85rem;
}
/* ── AI panel ────────────────────────────────────────────── */
.board-ai-panel {
flex: 0 0 320px;
width: 320px;
height: 100%;
display: flex;
flex-direction: column;
border-left: 1px solid var(--outline-variant);
background: var(--surface-container-low);
overflow-y: auto;
}
.board-ai-panel__head {
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--outline-variant);
}
.board-ai-panel__title {
font-family: var(--font-headline);
font-size: 1rem;
color: var(--on-surface);
}
.board-ai-panel__subtitle {
font-size: 0.75rem;
color: var(--on-surface-variant);
margin-top: 0.15rem;
}
.board-ai-panel__body {
padding: 0.85rem 1rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.board-ai-panel__tabs {
display: flex;
gap: 0.35rem;
}
.board-ai-panel__tab {
flex: 1;
padding: 0.4rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container);
color: var(--on-surface-variant);
font-family: var(--font-label);
font-size: 0.8rem;
cursor: pointer;
}
.board-ai-panel__tab--active {
border-color: var(--primary);
color: var(--on-surface);
background: var(--surface-variant);
}
.board-ai-panel__label {
display: block;
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--on-surface-variant);
margin-bottom: 0.3rem;
font-family: var(--font-label);
}
.board-ai-panel__field {
display: flex;
flex-direction: column;
}
.board-ai-panel__select,
.board-ai-panel__input,
.board-ai-panel__textarea {
width: 100%;
padding: 0.45rem 0.55rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container-lowest);
color: var(--on-surface);
font-size: 0.85rem;
font-family: var(--font-body);
}
.board-ai-panel__textarea {
resize: vertical;
min-height: 76px;
}
.board-ai-panel__file-btn {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.4rem 0.55rem;
border: 1px dashed var(--outline);
border-radius: var(--radius-md);
background: var(--surface-container-lowest);
color: var(--on-surface-variant);
font-size: 0.8rem;
cursor: pointer;
width: 100%;
}
.board-ai-panel__file-btn--set {
border-style: solid;
color: var(--on-surface);
}
.board-ai-panel__file-actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 0.3rem;
}
.board-ai-panel__link-btn {
background: none;
border: none;
padding: 0;
color: var(--primary);
font-size: 0.75rem;
font-family: var(--font-label);
cursor: pointer;
text-decoration: underline;
}
.board-ai-panel__link-btn:hover {
color: var(--primary-dim);
}
.board-ai-panel__run {
margin-top: 0.25rem;
padding: 0.6rem;
border: none;
border-radius: var(--radius-md);
background: var(--primary);
color: var(--on-primary);
font-family: var(--font-label);
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
}
.board-ai-panel__run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.board-ai-panel__status {
font-size: 0.8rem;
color: var(--on-surface-variant);
padding: 0.5rem 0.6rem;
border-radius: var(--radius-md);
background: var(--surface-container);
}
.board-ai-panel__status--error {
color: var(--on-error-container);
background: var(--error-container);
}
.board-ai-panel__hint {
font-size: 0.72rem;
color: var(--on-surface-variant);
}

View file

@ -1,396 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Excalidraw, convertToExcalidrawElements } from '@excalidraw/excalidraw'
import '@excalidraw/excalidraw/index.css'
import Header from '../components/Header'
import Footer from '../components/Footer'
import SettingsModal from '../components/SettingsModal'
import BoardSwitcher from '../components/board/BoardSwitcher'
import BoardAiPanel from '../components/board/BoardAiPanel'
import { useProjects } from '../context/ProjectContext'
import { assetUrl } from '../config'
import {
sanitizeBoardAppState,
boardStateSignature,
urlToDataURL,
dataURLToFile,
measureImage,
mimeFromName,
extFromMime,
toServedAssetPath
} from '../utils/boardHelpers'
import './BoardPage.css'
const AUTOSAVE_DELAY = 800
export default function BoardPage() {
const [searchParams, setSearchParams] = useSearchParams()
const projectId = searchParams.get('projectId')
const boardId = searchParams.get('boardId')
const {
getProject,
getProjectBoards,
getBoard,
createBoard,
deleteBoard,
updateBoard,
saveBoardState,
uploadAsset
} = useProjects()
const [project, setProject] = useState(null)
const [boards, setBoards] = useState([])
const [board, setBoard] = useState(null)
const [initialData, setInitialData] = useState(null)
const [loadError, setLoadError] = useState('')
const [showSettings, setShowSettings] = useState(false)
const [saveStatus, setSaveStatus] = useState('idle') // 'idle' | 'saving' | 'saved' | 'error'
const excalidrawApiRef = useRef(null)
const bootstrappingRef = useRef(null) // projectId currently being bootstrapped (guards StrictMode double-run)
const imageRefsRef = useRef({}) // excalidraw fileId -> asset filename (url path)
const uploadingRef = useRef(new Set())
const lastSavedSigRef = useRef('')
const saveTimerRef = useRef(null)
const latestSceneRef = useRef(null) // latest { elements, appState } from onChange
const boardIdRef = useRef(null) // current boardId, so async saves target the right board
const selectedImageRef = useRef(null) // { fileId, filename } of the selected asset-backed image, or null
// ---- Load the project (name for the header) ------------------------------
useEffect(() => {
let cancelled = false
if (!projectId) return undefined
getProject(projectId)
.then(data => { if (!cancelled) setProject(data) })
.catch(() => { if (!cancelled) setProject(null) })
return () => { cancelled = true }
}, [projectId, getProject])
// ---- Load the project's boards + bootstrap a default when empty ----------
const refreshBoards = useCallback(async () => {
if (!projectId) return []
const list = await getProjectBoards(projectId)
setBoards(list)
return list
}, [projectId, getProjectBoards])
useEffect(() => {
let cancelled = false
if (!projectId) return undefined
;(async () => {
try {
let list = await getProjectBoards(projectId)
if (cancelled) return
// No board selected in the URL: open the first, or create one.
if (!boardId) {
if (list.length === 0) {
// Guard against StrictMode's double effect run creating two boards.
if (bootstrappingRef.current === projectId) return
bootstrappingRef.current = projectId
const created = await createBoard(projectId, 'Board 1')
list = [created]
}
if (cancelled) return
setBoards(list)
setSearchParams({ projectId, boardId: String(list[0].id) }, { replace: true })
return
}
setBoards(list)
} catch (err) {
if (!cancelled) setLoadError(err.message || 'Failed to load boards')
}
})()
return () => { cancelled = true }
}, [projectId, boardId, getProjectBoards, createBoard, setSearchParams])
// ---- Load the selected board + build Excalidraw initialData --------------
useEffect(() => {
let cancelled = false
if (!boardId) return undefined
setInitialData(null)
setSaveStatus('idle')
imageRefsRef.current = {}
uploadingRef.current = new Set()
latestSceneRef.current = null
boardIdRef.current = boardId
;(async () => {
try {
const data = await getBoard(boardId)
if (cancelled) return
setBoard(data)
const state = data?.state || {}
const elements = Array.isArray(state.elements) ? state.elements : []
const appState = sanitizeBoardAppState(state.appState || {})
const imageRefs = state.imageRefs && typeof state.imageRefs === 'object' ? state.imageRefs : {}
imageRefsRef.current = { ...imageRefs }
// Re-hydrate image binaries from their backing assets on disk.
const files = {}
await Promise.all(Object.entries(imageRefs).map(async ([fileId, filename]) => {
try {
const dataURL = await urlToDataURL(assetUrl(filename))
files[fileId] = { id: fileId, dataURL, mimeType: mimeFromName(filename), created: Date.now() }
} catch (err) {
console.error('Failed to load board image', filename, err)
}
}))
if (cancelled) return
lastSavedSigRef.current = boardStateSignature(elements, appState)
setInitialData({ elements, appState, files, scrollToContent: true })
} catch (err) {
if (!cancelled) setLoadError(err.message || 'Failed to load board')
}
})()
return () => { cancelled = true }
}, [boardId, getBoard])
// ---- Persist board state (debounced) -------------------------------------
// Saves from the latest onChange snapshot (falling back to the API) so it
// never silently no-ops if the API ref hasn't populated yet.
const persistNow = useCallback(async () => {
const targetBoardId = boardIdRef.current
if (!targetBoardId) return
let elements = latestSceneRef.current?.elements
let appState = latestSceneRef.current?.appState
if (!elements) {
const api = excalidrawApiRef.current
if (!api) return
elements = api.getSceneElements()
appState = api.getAppState()
}
elements = (elements || []).filter(el => !el.isDeleted)
appState = sanitizeBoardAppState(appState || {})
// Prune image refs whose element no longer exists on the canvas.
const liveFileIds = new Set(
elements.filter(el => el.type === 'image' && el.fileId).map(el => el.fileId)
)
const imageRefs = {}
for (const [fileId, filename] of Object.entries(imageRefsRef.current)) {
if (liveFileIds.has(fileId)) imageRefs[fileId] = filename
}
imageRefsRef.current = imageRefs
setSaveStatus('saving')
const ok = await saveBoardState(targetBoardId, { elements, appState, imageRefs })
setSaveStatus(ok ? 'saved' : 'error')
}, [saveBoardState])
const scheduleSave = useCallback(() => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
saveTimerRef.current = setTimeout(() => { saveTimerRef.current = null; persistNow() }, AUTOSAVE_DELAY)
}, [persistNow])
// ---- Upload pasted/dropped local images so they persist as assets --------
const backfillLocalImages = useCallback(async (elements, files) => {
if (!projectId || !files) return
const imageElements = elements.filter(el => el.type === 'image' && !el.isDeleted && el.fileId)
for (const el of imageElements) {
const fileId = el.fileId
if (imageRefsRef.current[fileId] || uploadingRef.current.has(fileId)) continue
const file = files[fileId]
if (!file?.dataURL) continue
uploadingRef.current.add(fileId)
try {
const ext = extFromMime(file.mimeType || 'image/png')
const uploadFile = dataURLToFile(file.dataURL, `board-${fileId}.${ext}`)
const asset = await uploadAsset(projectId, uploadFile, 'image', { source: 'board-upload' })
if (asset?.filename) {
imageRefsRef.current[fileId] = asset.filename
scheduleSave()
}
} catch (err) {
console.error('Failed to persist board image upload', err)
} finally {
uploadingRef.current.delete(fileId)
}
}
}, [projectId, uploadAsset, scheduleSave])
const handleChange = useCallback((elements, appState, files) => {
latestSceneRef.current = { elements, appState }
// Track the currently-selected asset-backed image (used by the AI panel's
// "Selected image" input option). Runs before the save early-return because
// selection changes don't alter the board-state signature.
const selectedIds = appState?.selectedElementIds || {}
const selectedImage = elements.find(el =>
el.type === 'image' && !el.isDeleted && el.fileId && selectedIds[el.id] && imageRefsRef.current[el.fileId]
)
selectedImageRef.current = selectedImage
? { fileId: selectedImage.fileId, filename: imageRefsRef.current[selectedImage.fileId] }
: null
const sig = boardStateSignature(elements, appState)
if (sig === lastSavedSigRef.current) return
lastSavedSigRef.current = sig
scheduleSave()
backfillLocalImages(elements, files)
}, [scheduleSave, backfillLocalImages])
const getSelectedBoardImage = useCallback(() => selectedImageRef.current, [])
// Flush a pending save on unmount / board switch.
useEffect(() => () => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
saveTimerRef.current = null
persistNow()
}
}, [persistNow])
// Flush on tab hide / close so in-flight edits aren't lost.
useEffect(() => {
const flush = () => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
saveTimerRef.current = null
persistNow()
}
}
window.addEventListener('pagehide', flush)
document.addEventListener('visibilitychange', flush)
return () => {
window.removeEventListener('pagehide', flush)
document.removeEventListener('visibilitychange', flush)
}
}, [persistNow])
// ---- Place an AI-generated (already-saved) asset onto the canvas ---------
const placeAssetImage = useCallback(async (asset) => {
const api = excalidrawApiRef.current
if (!api || !asset) return
// Edits return a stored filePath (with data/assets/ prefix) and no filename;
// normalize either to the served path so reload URLs resolve correctly.
const refPath = asset.filename || (asset.filePath ? toServedAssetPath(asset.filePath) : null)
try {
// ComfyUI results carry an absolute `url`; external-API/persisted assets
// resolve from their served filename. Either way we render from a data URL.
const src = (typeof asset.url === 'string' && /^(https?:|data:)/i.test(asset.url))
? asset.url
: (refPath ? assetUrl(refPath) : null)
if (!src) return
const dataURL = src.startsWith('data:') ? src : await urlToDataURL(src)
const fileId = `board-asset-${asset.id || Date.now()}`
api.addFiles([{ id: fileId, dataURL, mimeType: mimeFromName(refPath || 'image.png'), created: Date.now() }])
// Cap on-canvas size to a usable footprint regardless of render size.
const { width, height } = await measureImage(dataURL)
const st = api.getAppState()
const zoom = st.zoom?.value || 1
const centerX = (st.width / 2) / zoom - st.scrollX
const centerY = (st.height / 2) / zoom - st.scrollY
const skeleton = {
type: 'image',
x: centerX - width / 2,
y: centerY - height / 2,
width,
height,
fileId
}
const newElements = convertToExcalidrawElements([skeleton])
api.updateScene({ elements: [...api.getSceneElements(), ...newElements] })
// Only persist a ref when the image is backed by a served asset file
// (so it re-hydrates on reload); pure data-URL results won't be.
if (refPath) imageRefsRef.current[fileId] = refPath
// updateScene triggers onChange → scheduleSave; nudge it explicitly too.
scheduleSave()
} catch (err) {
console.error('Failed to place generated image on board', err)
}
}, [scheduleSave])
const handleBoardsChanged = useCallback((nextBoards) => {
if (Array.isArray(nextBoards)) setBoards(nextBoards)
else refreshBoards()
}, [refreshBoards])
const currentBoard = useMemo(
() => boards.find(b => String(b.id) === String(boardId)) || board,
[boards, boardId, board]
)
if (!projectId) {
return (
<div className="board-page">
<Header onSettingsClick={() => setShowSettings(true)} title="Boards" centerTitle />
<div className="board-page__empty">No project selected.</div>
<Footer />
</div>
)
}
return (
<div className="board-page">
<Header
onSettingsClick={() => setShowSettings(true)}
projectId={projectId}
title={project?.name || 'Boards'}
centerTitle
/>
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}
<div className="board-page__bar">
<BoardSwitcher
projectId={projectId}
boards={boards}
currentBoard={currentBoard}
onBoardsChanged={handleBoardsChanged}
createBoard={createBoard}
updateBoard={updateBoard}
deleteBoard={deleteBoard}
onSelect={(id) => setSearchParams({ projectId, boardId: String(id) })}
/>
<span className={`board-page__save board-page__save--${saveStatus}`}>
{saveStatus === 'saving' && 'Saving…'}
{saveStatus === 'saved' && 'All changes saved'}
{saveStatus === 'error' && 'Save failed — retrying on next edit'}
</span>
</div>
{loadError && <div className="board-page__error">{loadError}</div>}
<div className="board-page__body">
<div className="board-page__canvas">
{initialData ? (
<Excalidraw
key={boardId}
excalidrawAPI={(api) => { excalidrawApiRef.current = api }}
initialData={initialData}
onChange={handleChange}
theme="dark"
name={currentBoard?.name || 'Board'}
/>
) : (
<div className="board-page__loading">Loading board…</div>
)}
</div>
<BoardAiPanel
projectId={projectId}
projectName={project?.name || ''}
boardId={boardId}
onImageGenerated={placeAssetImage}
getSelectedBoardImage={getSelectedBoardImage}
/>
</div>
</div>
)
}

View file

@ -169,39 +169,6 @@
border: 1px solid rgba(71, 72, 74, 0.16);
}
.graph-page__reorganize {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.85rem;
border: 1px solid rgba(71, 72, 74, 0.18);
border-radius: var(--radius-md);
background: rgba(18, 19, 21, 0.96);
color: var(--on-surface);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.02em;
cursor: pointer;
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
transition: all var(--transition-base);
}
.graph-page__reorganize:hover:not(:disabled) {
border-color: rgba(143, 245, 255, 0.28);
background: rgba(143, 245, 255, 0.12);
color: var(--primary);
}
.graph-page__reorganize:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.graph-page__reorganize .material-symbols-outlined {
font-size: 1.05rem;
}
.graph-page__controls {
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.28);
}
@ -785,11 +752,7 @@
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
/* A flat fill instead of backdrop-filter: blur(). Every blurred element inside
the React Flow viewport costs a backdrop readback per frame, and with 3-4
badges per node (70+ on screen at low zoom) that collapsed dragging to
~2 fps in the desktop app (Electron/Chromium 130) while browsers coped. */
background: rgba(12, 14, 16, 0.55);
backdrop-filter: blur(10px);
pointer-events: none;
}

View file

@ -8,7 +8,6 @@ import {
EdgeLabelRenderer,
Handle,
MiniMap,
Panel,
Position,
ReactFlow,
useEdgesState,
@ -36,7 +35,6 @@ import {
IMAGE_COMPARE_INPUT_IDS,
IMAGE_COMPARE_NODE_TYPE_NAME,
LEGACY_INPUT_ID,
MESH_FILE_EXTENSIONS,
HITEM_MESH_API_OPTION,
HITEM_MESH_GENERATION_API_ID,
TENCENT_GENERATION_TYPE_OPTIONS,
@ -59,7 +57,6 @@ import {
canFetchTencentMeshResult,
canFetchTripoMeshResult,
canNodeTypeAcceptIncomingConnection,
computeReorganizedLayout,
createComfyExecutionId,
createWorkflowDraftBindings,
createWorkflowDraftInputs,
@ -80,7 +77,6 @@ import {
getNodeKind,
getNodeOutputType,
getPointerClientPosition,
getWorkflowFileInputAccept,
getWorkflowParameterBinding,
getWorkflowParameterValueType,
isFileWorkflowValueType,
@ -139,8 +135,7 @@ export default function GraphPage({ project }) {
runMeshGenerationApi,
queryTencentMeshGenerationResult,
queryTripoMeshGenerationResult,
queryHitemMeshGenerationResult,
saveGraphViewport
queryHitemMeshGenerationResult
} = useProjects()
const { settings } = useSettings()
const { addNotification } = useNotifications()
@ -166,15 +161,12 @@ export default function GraphPage({ project }) {
const fileInputRef = useRef(null)
const pendingUploadNodeIdRef = useRef(null)
const meshFileInputRef = useRef(null)
const pendingMeshUploadNodeIdRef = useRef(null)
const pendingConnectionRef = useRef(null)
const skipNextPaneClickRef = useRef(false)
const libraryLoadedRef = useRef(false)
const workflowsLoadedRef = useRef(false)
const graphCanvasRef = useRef(null)
const hasAutoFitOnLoadRef = useRef(false)
const viewportSaveTimeoutRef = useRef(null)
const pushMeshGenerationFailureNotification = useCallback((message, source = 'Mesh generation API') => {
addNotification({
@ -670,21 +662,6 @@ export default function GraphPage({ project }) {
}
}, [getComfyWorkflows, updateComfyWorkflow])
// Bumped when something outside this browser (e.g. an MCP client / AI
// agent) mutates this project — re-runs the loadGraph effect below.
const [externalReloadTick, setExternalReloadTick] = useState(0)
useEffect(() => {
const handleExternalMutation = (event) => {
const targetProjectId = event?.detail?.projectId
if (targetProjectId == null || Number(targetProjectId) === Number(project.id)) {
setExternalReloadTick(tick => tick + 1)
}
}
window.addEventListener('genstudio:external-mutation', handleExternalMutation)
return () => window.removeEventListener('genstudio:external-mutation', handleExternalMutation)
}, [project.id])
useEffect(() => {
let cancelled = false
@ -721,7 +698,7 @@ export default function GraphPage({ project }) {
return () => {
cancelled = true
}
}, [getProjectConnections, getProjectNodes, handleDeleteNode, project.id, setEdges, setNodes, externalReloadTick])
}, [getProjectConnections, getProjectNodes, handleDeleteNode, project.id, setEdges, setNodes])
const handleCreateNode = useCallback(async (nodeTypeName, initialData = {}) => {
const nextIndex = nodes.length
@ -1034,12 +1011,6 @@ export default function GraphPage({ project }) {
})
},
onMeshGenModeSelect: async (targetNodeId, mode) => {
if (mode === 'local') {
pendingMeshUploadNodeIdRef.current = String(targetNodeId)
meshFileInputRef.current?.click()
return
}
if (mode === 'api') {
await ensureLibraryLoaded()
}
@ -1270,56 +1241,27 @@ export default function GraphPage({ project }) {
}
const spawnAdditionalResultNodes = async (nodeTypeName, assets) => {
// The first result is applied to the target node, which keeps its existing
// reference connection(s). Every additional result becomes a new node that
// must be wired up to the same reference node(s) so it can be used the same way.
// For an image workflow the target can reference several nodes, so replicate all
// of its incoming edges (preserving handles); Image Edit / Mesh Gen wire the
// single image input to their default handle.
const referenceEdges = nodeTypeName === 'Image'
? edges
.filter(edge => edge.target === String(targetNodeId))
.map(edge => ({
source: edge.source,
inputId: edge.targetHandle || DEFAULT_INPUT_ID,
outputId: edge.sourceHandle || DEFAULT_OUTPUT_ID
}))
: (() => {
const sourceEdge = getInputSource(nodes, edges, targetNodeId, 'image').edge
return sourceEdge
? [{
source: sourceEdge.source,
inputId: DEFAULT_INPUT_ID,
outputId: sourceEdge.sourceHandle || DEFAULT_OUTPUT_ID
}]
: []
})()
// Stack the additional nodes in a single vertical column directly below the
// target node (which holds the first result). Use a fixed step: a collapsed
// image/mesh card is a fixed-size 360px-wide, ~480px-tall card, and the target
// node's live measured height is unreliable here (it's still in its taller
// processing layout when this runs).
const sourceEdge = getInputSource(nodes, edges, targetNodeId, 'image').edge
const baseX = targetNode.position.x
const baseY = targetNode.position.y
const verticalStep = 580
for (let index = 0; index < assets.length; index += 1) {
const asset = assets[index]
const createdNode = await handleCreateNode(nodeTypeName, {
name: asset.name || nodeTypeName,
assetId: asset.id,
xPos: baseX,
yPos: baseY + ((index + 1) * verticalStep),
xPos: baseX + 360,
yPos: baseY + ((index + 1) * 140),
metadata: {
createdFromNodeId: Number(targetNodeId)
}
})
for (const referenceEdge of referenceEdges) {
if ((nodeTypeName === 'Image Edit' || nodeTypeName === 'Mesh Gen') && sourceEdge) {
const newConnection = await createProjectConnection(project.id, {
sourceNodeId: Number(referenceEdge.source),
sourceNodeId: Number(sourceEdge.source),
targetNodeId: createdNode.id,
inputId: referenceEdge.inputId,
outputId: referenceEdge.outputId
inputId: DEFAULT_INPUT_ID,
outputId: sourceEdge.sourceHandle || DEFAULT_OUTPUT_ID
})
setEdges(currentEdges => {
@ -1449,54 +1391,6 @@ export default function GraphPage({ project }) {
return
}
// With an image attached to the node, an API run edits that image and
// saves the result as an edit of it; otherwise it's a plain generation.
const connectedInputAsset = getConnectedInputAssetFrom(nodes, edges, targetNodeId)
const editSourceReference = getAssetSourceReference(connectedInputAsset)
if (editSourceReference) {
await setProcessingState('processing', null, { processingSource: 'API', inputSource: editSourceReference })
try {
const response = await runImageEditApi(project.id, {
imageSource: editSourceReference,
name: targetDraft.name.trim(),
selectedApi: targetDraft.selectedApi,
prompt: targetDraft.prompt.trim()
})
const savedEdits = response?.savedEdits || []
if (savedEdits.length === 0) {
throw new Error('Image edit did not return any saved image')
}
await applyNodeResult({ id: savedEdits[0].id, name: savedEdits[0].name || targetDraft.name.trim() }, {
lastAction: 'image-edit-api',
inputSource: editSourceReference,
lastActionParams: buildLastActionParams({
source: 'API',
label: imageGenerationApis.find(api => api.id === targetDraft.selectedApi)?.name || targetDraft.selectedApi,
params: [
{ label: 'Prompt', type: 'string', value: targetDraft.prompt.trim() },
{ label: 'Image source', type: 'image', value: editSourceReference }
]
})
})
if (savedEdits.length > 1) {
await spawnAdditionalResultNodes('Image', savedEdits.slice(1).map(edit => ({
id: edit.id,
name: edit.name || targetDraft.name.trim()
})))
}
setActionDraftsByNodeId({})
} catch (err) {
await setProcessingState('error', null, { error: err.message || 'Image edit failed', inputSource: editSourceReference })
pushExternalApiFailureNotification(
'Image edit failed',
err.message || 'Image edit failed',
imageGenerationApis.find(api => api.id === targetDraft.selectedApi)?.name || 'Image edit API'
)
}
return
}
await setProcessingState('processing', null, { processingSource: 'API' })
try {
const generatedAsset = await generateImage(project.id, {
@ -1565,13 +1459,6 @@ export default function GraphPage({ project }) {
inputValues[parameter.id] = inputValue
}
// With an image attached to the node, the workflow output is saved as
// an edit of that image instead of as a brand-new asset — but only when
// the workflow exposes an image input to receive it. A pure text-to-image
// workflow can't edit the attached image, so it falls back to generation.
const connectedInputAsset = getConnectedInputAssetFrom(nodes, edges, targetNodeId)
const workflowAcceptsImageInput = (workflow.parameters || []).some(parameter => getWorkflowParameterValueType(parameter) === 'image')
const saveAsEdit = Boolean(connectedInputAsset && workflowAcceptsImageInput)
const promptId = createComfyExecutionId('graph-image-prompt')
const clientId = createComfyExecutionId('graph-image-client')
setActionDraftsByNodeId({})
@ -1581,55 +1468,15 @@ export default function GraphPage({ project }) {
projectName: project.name,
page: 'graph',
targetId: targetNodeId,
kind: saveAsEdit ? 'imageEdit' : 'image',
kind: 'image',
label: targetDraft.name.trim() || workflow.name
})
await setProcessingState('processing', 0, { processingSource: 'ComfyUI', promptId }, {
progressDetail: saveAsEdit ? 'Preparing ComfyUI image edit' : 'Preparing ComfyUI workflow',
progressDetail: 'Preparing ComfyUI workflow',
currentNodeLabel: 'Waiting for ComfyUI execution to start'
})
try {
if (saveAsEdit) {
const response = await runImageEditComfy(project.id, {
assetId: connectedInputAsset.id,
workflowId: Number(targetDraft.workflowId),
name: targetDraft.name.trim(),
inputValues,
promptId,
clientId
})
const savedEdits = response?.savedEdits || []
if (savedEdits.length === 0) {
throw new Error('ComfyUI image edit did not return any saved image')
}
setNodeTransientData(targetNodeId, {
status: 'processing',
progress: 100,
progressDetail: 'Saving edited image',
currentNodeLabel: 'ComfyUI image edit completed'
})
await applyNodeResult({ id: savedEdits[0].id, name: savedEdits[0].name || targetDraft.name.trim() }, {
lastAction: 'image-edit-comfy',
promptId,
inputSource: JSON.stringify(inputValues),
lastActionParams: buildLastActionParams({
source: 'ComfyUI',
label: workflow.name,
params: describeWorkflowParams(workflow, inputValues, targetDraft, targetInputSources)
})
})
if (savedEdits.length > 1) {
await spawnAdditionalResultNodes('Image', savedEdits.slice(1).map(edit => ({
id: edit.id,
name: edit.name || targetDraft.name.trim()
})))
}
await persistWorkflowDefaultsIfRequested(targetDraft, workflow, inputValues)
completeJob(promptId, { status: 'completed' })
return
}
const generatedAssets = await runComfyWorkflow(project.id, {
workflowId: Number(targetDraft.workflowId),
name: targetDraft.name.trim(),
@ -2532,20 +2379,15 @@ export default function GraphPage({ project }) {
}
const spawnAdditionalResultNodes = async (nodeTypeName, assets) => {
// Stack the additional nodes in a single vertical column directly below the
// target node (which holds the first result). Use a fixed step matching the
// collapsed fixed-size card (~480px tall) plus a gap; the target's live
// measured height is unreliable here (it's still in its taller processing layout).
const baseX = targetNode.position.x
const baseY = targetNode.position.y
const verticalStep = 580
for (let index = 0; index < assets.length; index += 1) {
const asset = assets[index]
await handleCreateNode(nodeTypeName, {
name: asset.name || nodeTypeName,
assetId: asset.id,
xPos: baseX,
yPos: baseY + ((index + 1) * verticalStep),
xPos: baseX + 360,
yPos: baseY + ((index + 1) * 140),
metadata: {
createdFromNodeId: Number(targetNodeId)
}
@ -2722,61 +2564,16 @@ export default function GraphPage({ project }) {
}
}, [project.id, replaceFlowNodeData, updateProjectNode, uploadAsset])
const handleMeshFileUpload = useCallback(async (event) => {
const file = event.target.files?.[0]
const nodeId = pendingMeshUploadNodeIdRef.current
event.target.value = ''
if (!file || !nodeId) {
pendingMeshUploadNodeIdRef.current = null
return
}
try {
const uploadedAsset = await uploadAsset(project.id, file, 'mesh', {
format: file.name.split('.').pop()?.toUpperCase() || 'MESH',
source: 'IMPORT'
})
try {
const thumbnailFile = await createMeshThumbnailFile(file)
if (thumbnailFile) {
await uploadAssetThumbnail(uploadedAsset.id, thumbnailFile)
}
} catch (thumbErr) {
console.warn('Failed to generate thumbnail for imported mesh:', thumbErr)
}
const updatedNode = await updateProjectNode(project.id, Number(nodeId), {
assetId: uploadedAsset.id,
name: uploadedAsset.name,
status: null,
progress: null,
metadata: {
lastAction: 'local-upload'
}
})
replaceFlowNodeData(updatedNode)
setActionDraftsByNodeId({})
} catch (err) {
console.error('Failed to upload mesh to node:', err)
} finally {
pendingMeshUploadNodeIdRef.current = null
}
}, [project.id, replaceFlowNodeData, updateProjectNode, uploadAsset, uploadAssetThumbnail])
const handleCanvasFileDragOver = useCallback((event) => {
if (!Array.from(event.dataTransfer?.types || []).includes('Files')) return
event.preventDefault()
event.dataTransfer.dropEffect = 'copy'
}, [])
// Import dropped image/mesh files into Assets and create the matching node
// (Image or Mesh) at the drop position for each file, then bind the uploaded
// asset to that node.
// Import dropped image files into Assets and create an Image node at the drop
// position for each file, then bind the uploaded asset to that node.
const handleCanvasFileDrop = useCallback(async (event) => {
const isMeshFile = (file) => MESH_FILE_EXTENSIONS.includes((file.name.split('.').pop() || '').toLowerCase())
const files = Array.from(event.dataTransfer?.files || []).filter(file => file.type.startsWith('image/') || isMeshFile(file))
const files = Array.from(event.dataTransfer?.files || []).filter(file => file.type.startsWith('image/'))
if (files.length === 0) return
event.preventDefault()
@ -2786,36 +2583,17 @@ export default function GraphPage({ project }) {
for (let index = 0; index < files.length; index += 1) {
const file = files[index]
const isMesh = isMeshFile(file)
try {
const createdNode = await handleCreateNode(isMesh ? 'Mesh' : 'Image', {
const createdNode = await handleCreateNode('Image', {
xPos: flowPosition.x + (index * 32),
yPos: flowPosition.y + (index * 32),
name: file.name?.replace(/\.[^.]+$/, '') || (isMesh ? 'Mesh' : 'Image')
name: file.name?.replace(/\.[^.]+$/, '') || 'Image'
})
const uploadedAsset = await uploadAsset(project.id, file, 'image', {
resolution: 'Unknown',
format: file.type.split('/')[1]?.toUpperCase() || 'IMG',
source: 'IMPORT'
})
const uploadedAsset = isMesh
? await uploadAsset(project.id, file, 'mesh', {
format: file.name.split('.').pop()?.toUpperCase() || 'MESH',
source: 'IMPORT'
})
: await uploadAsset(project.id, file, 'image', {
resolution: 'Unknown',
format: file.type.split('/')[1]?.toUpperCase() || 'IMG',
source: 'IMPORT'
})
if (isMesh) {
try {
const thumbnailFile = await createMeshThumbnailFile(file)
if (thumbnailFile) {
await uploadAssetThumbnail(uploadedAsset.id, thumbnailFile)
}
} catch (thumbErr) {
console.warn('Failed to generate thumbnail for imported mesh:', thumbErr)
}
}
const updatedNode = await updateProjectNode(project.id, Number(createdNode.id), {
assetId: uploadedAsset.id,
name: uploadedAsset.name,
@ -2825,10 +2603,10 @@ export default function GraphPage({ project }) {
})
if (updatedNode) replaceFlowNodeData(updatedNode)
} catch (err) {
console.error(`Failed to import dropped ${isMesh ? 'mesh' : 'image'} to graph:`, err)
console.error('Failed to import dropped image to graph:', err)
}
}
}, [handleCreateNode, project.id, reactFlowInstance, replaceFlowNodeData, updateProjectNode, uploadAsset, uploadAssetThumbnail])
}, [handleCreateNode, project.id, reactFlowInstance, replaceFlowNodeData, updateProjectNode, uploadAsset])
const handleDeleteConnection = useCallback(async (edgeToDelete) => {
if (!edgeToDelete) {
@ -2932,69 +2710,12 @@ export default function GraphPage({ project }) {
}
}, [project.id, updateProjectNodePosition])
// Tidy up the canvas: lay the nodes out in clean left-to-right columns that
// follow the connections, persist the new positions, then re-fit the view.
const handleReorganize = useCallback(async () => {
const layout = computeReorganizedLayout(nodes, edges)
const movedNodes = nodes.filter(node => {
const position = layout[node.id]
return position && (position.x !== node.position.x || position.y !== node.position.y)
})
if (movedNodes.length === 0) {
return
}
setNodes(currentNodes => currentNodes.map(node => (
layout[node.id] ? { ...node, position: layout[node.id] } : node
)))
window.requestAnimationFrame(() => {
reactFlowInstance?.fitView?.({ padding: 0.2, duration: 400 })
})
try {
await Promise.all(movedNodes.map(node => (
updateProjectNodePosition(project.id, Number(node.id), layout[node.id])
)))
} catch (err) {
console.error('Failed to persist reorganized node positions:', err)
}
}, [nodes, edges, setNodes, reactFlowInstance, project.id, updateProjectNodePosition])
const handleEdgesDelete = useCallback(async (deletedEdges) => {
await Promise.all(
deletedEdges.map(edge => handleDeleteConnection(edge))
)
}, [handleDeleteConnection])
// Persist the canvas pan + zoom (debounced) whenever the user finishes panning
// or zooming, so reopening the project restores the exact same view.
const handleMoveEnd = useCallback((_event, viewport) => {
// Ignore programmatic moves during initial load positioning; only persist
// once the load-time viewport decision (restore / fit / focus) has run.
if (!hasAutoFitOnLoadRef.current || !viewport) {
return
}
if (viewportSaveTimeoutRef.current) {
window.clearTimeout(viewportSaveTimeoutRef.current)
}
viewportSaveTimeoutRef.current = window.setTimeout(() => {
viewportSaveTimeoutRef.current = null
saveGraphViewport(project.id, {
x: viewport.x,
y: viewport.y,
zoom: viewport.zoom
})
}, 500)
}, [project.id, saveGraphViewport])
useEffect(() => () => {
if (viewportSaveTimeoutRef.current) {
window.clearTimeout(viewportSaveTimeoutRef.current)
}
}, [])
const renderedEdges = useMemo(() => edges.map(edge => ({
...edge,
data: {
@ -3110,33 +2831,6 @@ export default function GraphPage({ project }) {
hasAutoFitOnLoadRef.current = true
// Prefer the last saved viewport (pan + zoom) so reopening a project lands
// exactly where the user left off, instead of a generic fit-all-nodes.
const savedViewport = project?.graphViewport
const hasSavedViewport = savedViewport
&& Number.isFinite(savedViewport.x)
&& Number.isFinite(savedViewport.y)
&& Number.isFinite(savedViewport.zoom)
if (hasSavedViewport) {
const restoreViewport = () => {
try {
reactFlowInstance.setViewport(
{ x: savedViewport.x, y: savedViewport.y, zoom: savedViewport.zoom },
{ duration: 0 }
)
} catch {
// Instance torn down before this fired (e.g. StrictMode remount).
}
}
const frameId = window.requestAnimationFrame(restoreViewport)
const timeoutId = window.setTimeout(restoreViewport, 220)
return () => {
window.cancelAnimationFrame(frameId)
window.clearTimeout(timeoutId)
}
}
const fitWorkflow = () => {
reactFlowInstance.fitView({
padding: 0.18,
@ -3156,7 +2850,7 @@ export default function GraphPage({ project }) {
window.cancelAnimationFrame(frameId)
window.clearTimeout(timeoutId)
}
}, [edges.length, loading, nodes.length, project.id, project?.graphViewport, reactFlowInstance, location.state?.focusTargetId])
}, [edges.length, loading, nodes.length, project.id, reactFlowInstance, location.state?.focusTargetId])
// Deep-link focus: when the user clicks a workflow notification, the Header
// navigates here with a focus target in router state. Once the graph and its
@ -3226,7 +2920,6 @@ export default function GraphPage({ project }) {
onSettingsClick={() => setShowSettings(true)}
title={project?.name || 'Workspace'}
centerTitle
projectId={project?.id}
/>
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}
@ -3252,7 +2945,6 @@ export default function GraphPage({ project }) {
)}
<input ref={fileInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFileUpload} />
<input ref={meshFileInputRef} type="file" accept={getWorkflowFileInputAccept('mesh')} style={{ display: 'none' }} onChange={handleMeshFileUpload} />
<div className="graph-page__body">
<main className="graph-page__main" id="graph-main">
@ -3321,7 +3013,6 @@ export default function GraphPage({ project }) {
onDragOver={handleCanvasFileDragOver}
onDrop={handleCanvasFileDrop}
onNodeDragStop={handleNodeDragStop}
onMoveEnd={handleMoveEnd}
onEdgesDelete={handleEdgesDelete}
defaultViewport={{ x: 0, y: 0, zoom: 0.9 }}
minZoom={0.2}
@ -3329,18 +3020,6 @@ export default function GraphPage({ project }) {
deleteKeyCode={null}
proOptions={{ hideAttribution: true }}
>
<Panel position="top-left">
<button
type="button"
className="graph-page__reorganize"
onClick={handleReorganize}
disabled={nodes.length === 0}
title="Reorganize nodes by following their connections"
>
<span className="material-symbols-outlined">account_tree</span>
<span>Reorganize</span>
</button>
</Panel>
<Background gap={24} size={1} color="rgba(143, 245, 255, 0.14)" />
<MiniMap pannable zoomable className="graph-page__minimap" nodeColor={minimapNodeColor} />
<Controls className="graph-page__controls" showInteractive={false} />

View file

@ -55,24 +55,10 @@ import {
normalizeCustomApiType
} from '../utils/kanbanHelpers'
import { saveWorkflowDefaults } from '../utils/workflowDefaults'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../utils/workflowEnums'
// Database id of the "Mesh Gen" kanban column (see IMAGE_CARD_COLUMNS).
const MESH_GEN_COLUMN_ID = 3
// Extensions accepted for 3D mesh imports, derived from the shared mesh accept
// list so drag-and-drop stays in sync with the file picker. Meshes dropped from
// the OS often arrive with an empty MIME type, so we detect them by extension.
const MESH_FILE_EXTENSIONS = getWorkflowFileInputAccept('mesh')
.split(',')
.map(entry => entry.trim().replace(/^\./, '').toLowerCase())
.filter(Boolean)
const isMeshFile = (file) => {
const extension = (file?.name?.split('.').pop() || '').toLowerCase()
return MESH_FILE_EXTENSIONS.includes(extension)
}
export default function KanbanPage() {
const { projectId } = useParams()
const navigate = useNavigate()
@ -100,7 +86,6 @@ export default function KanbanPage() {
queryHitemMeshGenerationResult,
runMeshEditApi,
runMeshTexturingApi,
runMeshRiggingApi,
runImageEditComfy,
generateImage,
getComfyWorkflows,
@ -139,7 +124,7 @@ export default function KanbanPage() {
const fileInputRef = useRef(null)
const fileUploadContextRef = useRef({ cardId: null, closeDraft: true })
const meshFileInputRef = useRef(null)
const meshUploadContextRef = useRef({ cardId: null, closeDraft: true })
const meshUploadContextRef = useRef({ closeDraft: true })
const pendingMeshProgressSubscriptionRef = useRef(null)
const pendingComfyProgressSubscriptionRef = useRef(null)
const imageEditProgressSubscriptionsRef = useRef(new Map())
@ -148,11 +133,11 @@ export default function KanbanPage() {
const [assetSelectorOpen, setAssetSelectorOpen] = useState(false);
const [pendingAssetCardId, setPendingAssetCardId] = useState(null);
const [assetSelectorType, setAssetSelectorType] = useState('image'); // 'image' | 'mesh'
const [assetSelectorType, setAssetSelectorType] = useState('image'); // only 'image' for now
const handleOpenAssetSelector = (cardId, type = 'image') => {
const handleOpenAssetSelector = (cardId) => {
setPendingAssetCardId(cardId);
setAssetSelectorType(type);
setAssetSelectorType('image');
setAssetSelectorOpen(true);
};
@ -238,7 +223,6 @@ export default function KanbanPage() {
}
const openImageSourceMenu = (cardId = null) => {
setMeshDraft(null)
setImageDraft({ mode: 'select', cardId })
}
@ -344,22 +328,6 @@ export default function KanbanPage() {
setCardAttributes(attributesData)
}
// Reload board data when something outside this browser (e.g. an MCP
// client / AI agent) mutates this project.
useEffect(() => {
const handleExternalMutation = (event) => {
const targetProjectId = event?.detail?.projectId
if (targetProjectId != null && Number(targetProjectId) !== Number(projectId)) return
refreshProjectAssets().catch(() => {})
refreshCardAttributes().catch(() => {})
}
window.addEventListener('genstudio:external-mutation', handleExternalMutation)
return () => window.removeEventListener('genstudio:external-mutation', handleExternalMutation)
// refreshCardAttributes is re-created per render; the listener only needs
// a working copy, so deps stay minimal to avoid re-subscribing every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId, refreshProjectAssets])
const closePendingComfyProgressSubscription = () => {
pendingComfyProgressSubscriptionRef.current?.()
pendingComfyProgressSubscriptionRef.current = null
@ -499,9 +467,7 @@ export default function KanbanPage() {
const handleRemoveImage = async (assetId) => {
try {
// Scope the removal to THIS project — an asset shared with another project
// must keep its membership there.
await deleteAsset(assetId, { projectId })
await deleteAsset(assetId)
await Promise.all([refreshProjectAssets(), refreshCardAttributes()])
} catch (err) {
console.error('Failed to remove image:', err)
@ -512,7 +478,7 @@ export default function KanbanPage() {
const handleRemoveImageCard = async (cardId, cardAssets) => {
try {
for (const asset of cardAssets) {
await deleteAsset(asset.id, { projectId })
await deleteAsset(asset.id)
}
if (cardId) {
@ -651,13 +617,8 @@ export default function KanbanPage() {
}
}
// Assets on column-less "detached" container cards (Brainstorming Board
// generations) have kanbanColumnId === null. They belong to the project (and
// are returned by listProjectAssets for MCP/clients) but must NOT appear on
// the Kanban board, so exclude them from the columns entirely.
const kanbanAssets = assets.filter(a => a.kanbanColumnId !== null && a.kanbanColumnId !== undefined)
const images = kanbanAssets.filter(a => a.type === 'image')
const meshes = kanbanAssets.filter(a => a.type === 'mesh')
const images = assets.filter(a => a.type === 'image')
const meshes = assets.filter(a => a.type === 'mesh')
const meshAssetsByCardId = useMemo(() => {
return meshes.reduce((accumulator, asset) => {
@ -713,10 +674,7 @@ export default function KanbanPage() {
}
});
if (isMesh) {
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!pendingAssetCardId) {
await moveCardToMeshGen(cardId);
}
await moveCardToMeshGen(cardId);
await ensureGeneratedMeshThumbnails(attachedAsset);
}
await refreshProjectAssets();
@ -1019,15 +977,9 @@ export default function KanbanPage() {
.map(api => ({ id: `custom_${api.id}`, name: api.name }))
), [customApis])
const meshRiggingApis = useMemo(() => (
customApis
.filter(api => normalizeCustomApiType(api?.type) === 'mesh-rigging')
.map(api => ({ id: `custom_${api.id}`, name: api.name }))
), [customApis])
const getWorkflowsForCard = (card) => {
if (card?.kanbanColumnId === 3) return meshGenWorkflows
if ([4, 5, 6].includes(card?.kanbanColumnId)) return meshEditWorkflows
if ([4, 5].includes(card?.kanbanColumnId)) return meshEditWorkflows
return imageEditWorkflows
}
@ -1035,7 +987,6 @@ export default function KanbanPage() {
if (columnId === 3) return meshGenerationApis
if (columnId === 4) return meshEditApis
if (columnId === 5) return meshTexturingApis
if (columnId === 6) return meshRiggingApis
return imageEditApis
}
@ -1046,15 +997,12 @@ export default function KanbanPage() {
// ---- "Add New Mesh" (Mesh Gen column) ----------------------------------
const selectedMeshComfyWorkflow = meshGenWorkflows.find(workflow => workflow.id == meshDraft?.workflowId) || null
// `cardId` targets an existing card ("Add more meshes" on any card); null
// creates a brand new Mesh Gen card ("ADD NEW MESH" at the bottom of the column).
const openMeshSourceMenu = (cardId = null) => {
setImageDraft(null)
setMeshDraft({ mode: 'select', cardId })
const openMeshSourceMenu = () => {
setMeshDraft({ mode: 'select' })
}
const openMeshLocalFilePicker = (cardId = meshDraft?.cardId || null) => {
meshUploadContextRef.current = { cardId, closeDraft: true }
const openMeshLocalFilePicker = () => {
meshUploadContextRef.current = { closeDraft: true }
if (meshFileInputRef.current) {
meshFileInputRef.current.value = ''
@ -1066,8 +1014,8 @@ export default function KanbanPage() {
const files = Array.from(e.target.files || [])
if (files.length === 0) return
const { cardId: targetCardId, closeDraft } = meshUploadContextRef.current
const cardId = targetCardId || createImageCardId()
const { closeDraft } = meshUploadContextRef.current
const cardId = createImageCardId()
try {
setLoading(true)
@ -1083,10 +1031,7 @@ export default function KanbanPage() {
uploadedAssets.push(uploaded)
}
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!targetCardId) {
await moveCardToMeshGen(cardId)
}
await moveCardToMeshGen(cardId)
await ensureGeneratedMeshThumbnails(uploadedAssets)
await refreshProjectAssets()
@ -1099,21 +1044,23 @@ export default function KanbanPage() {
} finally {
setLoading(false)
e.target.value = ''
meshUploadContextRef.current = { cardId: null, closeDraft: true }
meshUploadContextRef.current = { closeDraft: true }
}
}
const openMeshAssetLibrary = async (cardId = meshDraft?.cardId || null) => {
const openMeshAssetLibrary = async () => {
try {
await getLibraryAssets() // preload library if needed
handleOpenAssetSelector(cardId, 'mesh')
setPendingAssetCardId(null)
setAssetSelectorType('mesh')
setAssetSelectorOpen(true)
} catch (err) {
console.error('Failed to load mesh library:', err)
showStatusMessage(err.message || 'Failed to load meshes library', 'error')
}
}
const openMeshComfyDraft = (cardId = meshDraft?.cardId || null) => {
const openMeshComfyDraft = () => {
if (meshGenWorkflows.length === 0) {
showStatusMessage('No compatible ComfyUI workflows available. Import a workflow with at least one mesh output.', 'error')
return
@ -1121,16 +1068,16 @@ export default function KanbanPage() {
setMeshDraft({
...getComfyDraftFromWorkflow(meshGenWorkflows[0]),
cardId
cardId: null
})
}
const handleMeshComfyWorkflowChange = (workflowId) => {
const workflow = meshGenWorkflows.find(item => item.id == workflowId)
setMeshDraft(prev => ({
setMeshDraft({
...getComfyDraftFromWorkflow(workflow),
cardId: prev?.cardId || null
}))
cardId: null
})
}
const handleMeshComfyInputChange = (parameter, rawValue) => {
@ -1192,8 +1139,7 @@ export default function KanbanPage() {
detail: 'Preparing ComfyUI workflow',
progressPercent: 0,
currentNodeLabel: 'Waiting for ComfyUI execution to start',
promptId,
cardId: draft.cardId || null
promptId
})
setMeshDraft(null)
setLoading(true)
@ -1221,10 +1167,7 @@ export default function KanbanPage() {
currentNodeLabel: 'Generated mesh received'
} : prev)
await persistWorkflowDefaultsIfRequested(draft, workflow)
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!draft.cardId) {
await moveCardToMeshGen(cardId)
}
await moveCardToMeshGen(cardId)
await ensureGeneratedMeshThumbnails(generatedMeshes)
await refreshProjectAssets()
completeJob(promptId, { status: 'completed' })
@ -1259,16 +1202,16 @@ export default function KanbanPage() {
}
const prompt = draft.prompt.trim()
const cardId = draft.cardId || createImageCardId()
const cardId = createImageCardId()
const isTencentMeshApi = isTencentMeshGenerationApi(draft.selectedApi)
const isTripoMeshApi = isTripoMeshGenerationApi(draft.selectedApi)
const isHitemMeshApi = isHitemMeshGenerationApi(draft.selectedApi)
const isTripoP1Model = isTripoMeshApi && (draft.modelVersion || 'v2.5-20250123') === 'P1-20260311'
// Hitem3D is image-to-3D only; the mesh source draft has no image source, so
// it must be run from a card that already holds an image, via its Action menu.
// Hitem3D is image-to-3D only; the "Add New Mesh" draft has no image source,
// so it must be run from a Mesh Gen card that has an image dragged into it.
if (isHitemMeshApi) {
showStatusMessage('Hitem3D needs an image source. Add an image to a card and run it from the card Action menu.', 'error')
showStatusMessage('Hitem3D needs an image source. Drag an image into the Mesh Gen column and run it from the card.', 'error')
return
}
@ -1283,8 +1226,7 @@ export default function KanbanPage() {
selectedApi: draft.selectedApi,
title: name,
source: providerLabel,
detail: 'Submitting mesh generation request',
cardId: draft.cardId || null
detail: 'Submitting mesh generation request'
})
setMeshDraft(null)
setLoading(true)
@ -1672,9 +1614,7 @@ export default function KanbanPage() {
const getCardPreviewItems = (card, showAttributes = false) => {
const hasMeshAssets = (card.meshAssets?.length || 0) > 0
// Image Edit (2) is included so a mesh attached there via "Add more meshes"
// stays visible instead of being dropped from the preview.
const useMixedAssetCarousel = showAttributes && [2, 3, 4, 5, 6].includes(card.kanbanColumnId) && hasMeshAssets
const useMixedAssetCarousel = showAttributes && [3, 4, 5].includes(card.kanbanColumnId) && hasMeshAssets
if (!useMixedAssetCarousel) {
return []
@ -1844,7 +1784,7 @@ export default function KanbanPage() {
name: '',
selectedApi: defaultSelectedApi,
prompt: '',
selectedAssetId: [4, 5, 6].includes(card.kanbanColumnId)
selectedAssetId: [4, 5].includes(card.kanbanColumnId)
? (card.meshAssets[0]?.id ? `asset:${card.meshAssets[0].id}` : '')
: (card.assets[0]?.id ? `asset:${card.assets[0].id}` : ''),
workflowId: initialWorkflow?.id || '',
@ -2161,10 +2101,9 @@ export default function KanbanPage() {
const isMeshGenCard = card.kanbanColumnId === 3
const isMeshEditCard = card.kanbanColumnId === 4
const isTexturingCard = card.kanbanColumnId === 5
const isRiggingCard = card.kanbanColumnId === 6
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard || isRiggingCard
const actionLabel = isMeshGenCard ? 'mesh generation' : isMeshEditCard ? 'mesh edit' : isTexturingCard ? 'mesh texturing' : isRiggingCard ? 'mesh rigging' : 'image edit'
const sourceAssetLabel = isMeshEditCard || isTexturingCard || isRiggingCard ? 'mesh' : 'image'
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard
const actionLabel = isMeshGenCard ? 'mesh generation' : isMeshEditCard ? 'mesh edit' : isTexturingCard ? 'mesh texturing' : 'image edit'
const sourceAssetLabel = isMeshEditCard || isTexturingCard ? 'mesh' : 'image'
// Track every mesh item (roots and their versions/children) so the focus
// logic can detect a newly generated child mesh, not just new root meshes.
const existingMeshAssetIds = (card.meshAssets || [])
@ -2441,21 +2380,6 @@ export default function KanbanPage() {
cardId: card.id,
existingMeshAssetIds
})
} else if (isRiggingCard) {
const riggedMesh = await runMeshRiggingApi(projectId, {
meshSource: imageEditDraft.selectedAssetId,
name,
selectedApi: imageEditDraft.selectedApi,
prompt,
cardId: card.id
})
await ensureGeneratedMeshThumbnails(riggedMesh)
queueResultFocus({
type: 'mesh-result',
cardId: card.id,
existingMeshAssetIds
})
} else {
await runImageEditApi(projectId, {
imageSource: imageEditDraft.selectedAssetId,
@ -2607,9 +2531,9 @@ export default function KanbanPage() {
inputs: inputValues,
promptId,
clientId,
// Mesh Edit / Texturing / Rigging operate on an existing mesh — save
// the result as a version (child) of that source mesh.
parentAssetId: (isMeshEditCard || isTexturingCard || isRiggingCard) ? primaryMeshAssetId : null
// Mesh Edit / Texturing operate on an existing mesh — save the result
// as a version (child) of that source mesh.
parentAssetId: (isMeshEditCard || isTexturingCard) ? primaryMeshAssetId : null
})
await ensureGeneratedMeshThumbnails(generatedMeshes)
@ -2625,8 +2549,8 @@ export default function KanbanPage() {
[card.id]: {
...prev[card.id],
progressPercent: 100,
detail: isMeshGenCard ? 'Saving generated mesh' : isTexturingCard ? 'Saving textured mesh' : isRiggingCard ? 'Saving rigged mesh' : 'Saving edited mesh',
currentNodeLabel: isMeshGenCard ? 'ComfyUI mesh generation completed' : isTexturingCard ? 'ComfyUI mesh texturing completed' : isRiggingCard ? 'ComfyUI mesh rigging completed' : 'ComfyUI mesh edit completed'
detail: isMeshGenCard ? 'Saving generated mesh' : isTexturingCard ? 'Saving textured mesh' : 'Saving edited mesh',
currentNodeLabel: isMeshGenCard ? 'ComfyUI mesh generation completed' : isTexturingCard ? 'ComfyUI mesh texturing completed' : 'ComfyUI mesh edit completed'
}
}
: prev)
@ -2675,8 +2599,6 @@ export default function KanbanPage() {
? 'Mesh edit completed successfully.'
: isTexturingCard
? 'Mesh texturing completed successfully.'
: isRiggingCard
? 'Mesh rigging completed successfully.'
: 'Image edit completed successfully.', 'success')
} catch (err) {
console.error(`Failed to run ${actionLabel}:`, err)
@ -2689,8 +2611,6 @@ export default function KanbanPage() {
? 'Failed to run mesh edit'
: isTexturingCard
? 'Failed to run mesh texturing'
: isRiggingCard
? 'Failed to run mesh rigging'
: 'Failed to run image edit')
showStatusMessage(failureMessage, 'error')
@ -2722,12 +2642,6 @@ export default function KanbanPage() {
failureMessage,
meshTexturingApis.find(api => api.id === imageEditDraft?.selectedApi)?.name || 'Mesh texturing API'
)
} else if (isRiggingCard) {
pushExternalApiFailureNotification(
'Mesh rigging failed',
failureMessage,
meshRiggingApis.find(api => api.id === imageEditDraft?.selectedApi)?.name || 'Mesh rigging API'
)
} else {
pushExternalApiFailureNotification(
'Image edit failed',
@ -2876,72 +2790,43 @@ export default function KanbanPage() {
setFileDropColumnId(prev => (prev === columnId ? null : prev))
}
// Move a freshly created card into the column it was dropped on. New assets and
// cards are always created in the Images column server-side, so anything dropped
// elsewhere needs to be relocated afterwards.
const moveDroppedCardToColumn = async (cardId, columnId) => {
if (columnId === IMAGE_CARD_COLUMNS[0].dbId) return
const position = projectCards.filter(card => card.kanbanColumnId === columnId).length
await moveKanbanCard(projectId, cardId, columnId, position)
}
// Import dropped image and/or 3D mesh files into Assets, creating one card per
// file type in the column they were dropped on. Meshes are imported as mesh
// assets and get a rendered thumbnail like generated meshes do.
// Import dropped image files into Assets and create a single image card in the
// column they were dropped on. New assets are created in the Images column
// server-side, so cards dropped elsewhere are relocated afterwards.
const handleColumnFileDrop = async (event, columnId) => {
if (draggedCard || !isFileDrag(event)) return
event.preventDefault()
setFileDropColumnId(null)
const droppedFiles = Array.from(event.dataTransfer?.files || [])
const imageFiles = droppedFiles.filter(file => file.type.startsWith('image/'))
const meshFiles = droppedFiles.filter(isMeshFile)
if (imageFiles.length === 0 && meshFiles.length === 0) {
showStatusMessage('Only image or 3D mesh files can be dropped here', 'error')
const files = Array.from(event.dataTransfer?.files || []).filter(file => file.type.startsWith('image/'))
if (files.length === 0) {
showStatusMessage('Only image files can be dropped here', 'error')
return
}
const cardId = createImageCardId()
try {
setLoading(true)
if (imageFiles.length > 0) {
const imageCardId = createImageCardId()
for (const file of imageFiles) {
await uploadAsset(projectId, file, 'image', {
resolution: 'Unknown',
format: file.type.split('/')[1]?.toUpperCase() || 'IMG',
source: 'IMPORT',
cardId: imageCardId
})
}
await moveDroppedCardToColumn(imageCardId, columnId)
for (const file of files) {
await uploadAsset(projectId, file, 'image', {
resolution: 'Unknown',
format: file.type.split('/')[1]?.toUpperCase() || 'IMG',
source: 'IMPORT',
cardId
})
}
if (meshFiles.length > 0) {
const meshCardId = createImageCardId()
const uploadedMeshes = []
for (const file of meshFiles) {
const uploaded = await uploadAsset(projectId, file, 'mesh', {
resolution: 'Unknown',
format: file.name.split('.').pop()?.toUpperCase() || 'MESH',
source: 'IMPORT',
cardId: meshCardId
})
uploadedMeshes.push(uploaded)
}
await moveDroppedCardToColumn(meshCardId, columnId)
await ensureGeneratedMeshThumbnails(uploadedMeshes)
if (columnId !== IMAGE_CARD_COLUMNS[0].dbId) {
const position = projectCards.filter(card => card.kanbanColumnId === columnId).length
await moveKanbanCard(projectId, cardId, columnId, position)
}
await Promise.all([refreshProjectAssets(), refreshCardAttributes()])
} catch (err) {
console.error('Failed to import dropped files:', err)
showStatusMessage(err.message || 'Failed to import dropped files', 'error')
console.error('Failed to import dropped image:', err)
showStatusMessage(err.message || 'Failed to import dropped image', 'error')
} finally {
setLoading(false)
}
@ -3011,18 +2896,9 @@ export default function KanbanPage() {
)
}
// Image / mesh source drafts render inside the column of the card they target
// ("Add more images" / "Add more meshes"), and default to their own column when
// they are creating a brand new card.
const resolveDraftColumnId = (cardId, fallbackColumnId) => (
cardId
? imageCards.find(card => card.id === cardId)?.kanbanColumnId || fallbackColumnId
: fallbackColumnId
)
const draftColumnId = resolveDraftColumnId(imageDraft?.cardId, IMAGE_CARD_COLUMNS[0].dbId)
const meshDraftColumnId = resolveDraftColumnId(meshDraft?.cardId, MESH_GEN_COLUMN_ID)
const pendingMeshColumnId = resolveDraftColumnId(pendingMeshGeneration?.cardId, MESH_GEN_COLUMN_ID)
const draftColumnId = imageDraft?.cardId
? imageCards.find(card => card.id === imageDraft.cardId)?.kanbanColumnId || IMAGE_CARD_COLUMNS[0].dbId
: IMAGE_CARD_COLUMNS[0].dbId
const renderDropZone = (columnId, position, isEmpty = false) => {
const isActive = dropTarget?.columnId === columnId && dropTarget?.position === position
@ -3035,11 +2911,7 @@ export default function KanbanPage() {
onDragOver={event => handleCardDragOver(event, columnId, position)}
onDrop={event => handleCardDrop(event, columnId, position)}
>
{isEmpty
&& !(imageDraft && draftColumnId === columnId)
&& !(pendingImageGeneration && columnId === IMAGE_CARD_COLUMNS[0].dbId)
&& !(meshDraft && meshDraftColumnId === columnId)
&& !(pendingMeshGeneration && pendingMeshColumnId === columnId) && (
{isEmpty && !imageDraft && !pendingImageGeneration && !(columnId === MESH_GEN_COLUMN_ID && (meshDraft || pendingMeshGeneration)) && (
<span className="kanban-drop-zone__label font-label">
{column?.emptyLabel || 'Drop image cards here'}
</span>
@ -3078,7 +2950,6 @@ export default function KanbanPage() {
handleCardDragStart,
handleCardDragEnd,
openImageSourceMenu,
openMeshSourceMenu,
handleRemoveImageCard,
openMeshPreview,
handleRemoveImage,
@ -3219,16 +3090,6 @@ export default function KanbanPage() {
</div>
<span>{parameter.label || 'Toggle value'}</span>
</label>
) : getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]) ? (
<select
className="params-card__select"
value={imageDraft.inputs?.[parameter.id] == null ? '' : String(imageDraft.inputs[parameter.id])}
onChange={e => handleComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]).map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : getWorkflowParameterValueType(parameter) === 'string' ? (
<div className="comfy-textfield-wrap">
<textarea
@ -3374,33 +3235,44 @@ export default function KanbanPage() {
</div>
)}
{column.dbId === IMAGE_CARD_COLUMNS[0].dbId
&& !(imageDraft && draftColumnId === column.dbId)
&& !pendingImageGeneration && (
<button className="kanban-col__add-btn" id="add-image-btn" onClick={() => openImageSourceMenu()}>
<span className="material-symbols-outlined">add_photo_alternate</span>
<span className="font-label">ADD NEW IMAGE</span>
</button>
{column.dbId === IMAGE_CARD_COLUMNS[0].dbId && (
<>
<input
type="file"
accept="image/*"
multiple
style={{ display: 'none' }}
onChange={handleFileUpload}
ref={fileInputRef}
/>
{!imageDraft && !pendingImageGeneration && (
<button className="kanban-col__add-btn" id="add-image-btn" onClick={() => openImageSourceMenu()}>
<span className="material-symbols-outlined">add_photo_alternate</span>
<span className="font-label">ADD NEW IMAGE</span>
</button>
)}
</>
)}
{meshDraft && meshDraftColumnId === column.dbId && (
{meshDraft && column.dbId === MESH_GEN_COLUMN_ID && (
<div className="image-card image-card--draft">
{meshDraft.mode === 'select' && (
<div className="image-card__options">
<span className="font-label" style={{ fontSize: '0.65rem', color: 'var(--primary)', marginBottom: '0.5rem' }}>MESH SOURCE</span>
<button className="option-btn" onClick={() => openMeshLocalFilePicker(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshLocalFilePicker()}>
<span className="material-symbols-outlined">computer</span>
Local Computer
</button>
<button className="option-btn" onClick={() => openMeshAssetLibrary(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshAssetLibrary()}>
<span className="material-symbols-outlined">folder_open</span>
From Assets
</button>
<button className="option-btn" onClick={() => openMeshComfyDraft(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshComfyDraft()}>
<span className="material-symbols-outlined">account_tree</span>
ComfyUI Workflow
</button>
<button className="option-btn" onClick={() => setMeshDraft({ mode: 'api', selectedApi: meshGenerationApis[0]?.id || '', prompt: '', name: '', ...getMeshGenApiDefaults(), cardId: meshDraft?.cardId || null })}>
<button className="option-btn" onClick={() => setMeshDraft({ mode: 'api', selectedApi: meshGenerationApis[0]?.id || '', prompt: '', name: '', ...getMeshGenApiDefaults() })}>
<span className="material-symbols-outlined">api</span>
Remote API
</button>
@ -3463,16 +3335,6 @@ export default function KanbanPage() {
</div>
<span>{parameter.label || 'Toggle value'}</span>
</label>
) : getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]) ? (
<select
className="params-card__select"
value={meshDraft.inputs?.[parameter.id] == null ? '' : String(meshDraft.inputs[parameter.id])}
onChange={e => handleMeshComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]).map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : getWorkflowParameterValueType(parameter) === 'string' ? (
<textarea
className="gen-prompt-input image-card__param-textarea"
@ -3530,7 +3392,7 @@ export default function KanbanPage() {
<span>No mesh workflows available. Open the Library page to import one.</span>
</div>
)}
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu(meshDraft?.cardId || null)} style={{ justifyContent: 'center' }}>BACK</button>
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu()} style={{ justifyContent: 'center' }}>BACK</button>
</div>
)}
@ -3588,13 +3450,13 @@ export default function KanbanPage() {
<span>No mesh generation APIs available. Configure one in Settings.</span>
</div>
)}
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu(meshDraft?.cardId || null)} style={{ justifyContent: 'center' }}>BACK</button>
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu()} style={{ justifyContent: 'center' }}>BACK</button>
</div>
)}
</div>
)}
{pendingMeshGeneration && pendingMeshColumnId === column.dbId && (
{pendingMeshGeneration && column.dbId === MESH_GEN_COLUMN_ID && (
<div className="image-card image-card--loading" id="mesh-card-loading">
<div className="image-card__thumb image-card__thumb--loading">
<div className="image-card__loading-state">
@ -3623,13 +3485,24 @@ export default function KanbanPage() {
</div>
)}
{column.dbId === MESH_GEN_COLUMN_ID
&& !(meshDraft && meshDraftColumnId === column.dbId)
&& !(pendingMeshGeneration && pendingMeshColumnId === column.dbId) && (
<button className="kanban-col__add-btn" id="add-mesh-btn" onClick={() => openMeshSourceMenu()}>
<span className="material-symbols-outlined">deployed_code</span>
<span className="font-label">ADD NEW MESH</span>
</button>
{column.dbId === MESH_GEN_COLUMN_ID && (
<>
<input
type="file"
accept={getWorkflowFileInputAccept('mesh')}
multiple
style={{ display: 'none' }}
onChange={handleMeshFileUpload}
ref={meshFileInputRef}
/>
{!meshDraft && !pendingMeshGeneration && (
<button className="kanban-col__add-btn" id="add-mesh-btn" onClick={() => openMeshSourceMenu()}>
<span className="material-symbols-outlined">deployed_code</span>
<span className="font-label">ADD NEW MESH</span>
</button>
)}
</>
)}
</div>
</div>
@ -3642,7 +3515,6 @@ export default function KanbanPage() {
onSettingsClick={() => setShowSettings(true)}
title={project?.name || 'Workspace'}
centerTitle
projectId={projectId}
/>
{statusMessage && (
@ -3656,25 +3528,6 @@ export default function KanbanPage() {
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}
{/* Rendered once at page level: "Add more images"/"Add more meshes" can be
triggered from a card in any column, not just Images / Mesh Gen. */}
<input
type="file"
accept="image/*"
multiple
style={{ display: 'none' }}
onChange={handleFileUpload}
ref={fileInputRef}
/>
<input
type="file"
accept={getWorkflowFileInputAccept('mesh')}
multiple
style={{ display: 'none' }}
onChange={handleMeshFileUpload}
ref={meshFileInputRef}
/>
{meshPreviewAsset && <MeshPreviewDialog asset={meshPreviewAsset} titleId="kanban-mesh-preview-dialog-title" onClose={() => setMeshPreviewAsset(null)} />}
{assetSelectorOpen && (

View file

@ -23,64 +23,12 @@ const PRESETS = [
]
const CHANGE_LOG_ENTRIES = [
{
version: 'v2.1.2',
date: '2026-07-28',
items: [
'Fixed Desktop App on Linux',
'ComfyUI: Added Enums',
'Wireframe mode in Mesh Previewer'
],
},
{
version: 'v2.1.1',
date: '2026-07-27',
items: [
'ComfyUI: Custom models folder',
'Mesh Export: Save last output folder',
'DB: Fixed assets linked to a project',
'Kanban: Can add more meshes and images from any column',
'Desktop App: Fixed Graph page slowness'
],
},
{
version: 'v2.1.0',
date: '2026-07-23',
items: [
'Added Brainstorming Boards',
'MCP: Fixed Optimize tool'
],
},
{
version: 'v2.0.0',
date: '2026-07-20',
items: [
'MCP Server: Connect your AI with 3D Gen Studio',
'Graph Page: Added Reorganize button',
'Graph Page: Save the last position and zoom level',
'Graph Page: Simplified Image Node Actions',
'Desktop App: Fixed Wiki',
'Desktop App: Auto-start python services in Settings',
'3D Mesh: Thumbnail is now generated by mesh-tools (python)'
],
},
{
version: 'v1.5.0',
date: '2026-07-16',
items: [
'MeshPreviewer: Export to Unity, Unreal Engine, FBX',
'Graph Page: Add a mesh directly from the Local Computer',
'Graph Page: Can drag and drop a mesh from your computer',
'Kanban Board: Can drag and drop a mesh from your computer',
'Kanban Board: Added Rigging column'
],
},
{
version: 'v1.4.0',
date: '2026-07-15',
items: [
'MeshEditor: Added Auto Rig with Skintokens',
'Fixed Desktop App Setup'
'Fixed Desktop App Setup',
],
},
{

View file

@ -1,96 +0,0 @@
// Pure helpers for the Brainstorming Board (BoardPage). No React state.
// Fields of Excalidraw's appState that are safe + useful to persist. We
// deliberately drop transient/unserializable ones (collaborators, selection,
// cursor, etc.) so re-hydrating via initialData never crashes.
export function sanitizeBoardAppState(appState = {}) {
const { viewBackgroundColor, scrollX, scrollY, zoom, gridSize } = appState
return {
viewBackgroundColor: viewBackgroundColor ?? '#0d0e10',
scrollX: Number.isFinite(scrollX) ? scrollX : 0,
scrollY: Number.isFinite(scrollY) ? scrollY : 0,
zoom: zoom && Number.isFinite(zoom.value) ? { value: zoom.value } : { value: 1 },
gridSize: gridSize ?? null
}
}
// A cheap change signature so the debounced autosave skips redundant writes
// (e.g. the initial onChange that echoes the data we just loaded, or pure
// selection changes which live in appState we don't include here).
export function boardStateSignature(elements = [], appState = {}) {
const sanitized = sanitizeBoardAppState(appState)
const elementSig = elements.map(el => `${el.id}:${el.version}`).join(',')
return JSON.stringify({ e: elementSig, a: sanitized })
}
// Normalize an asset path to the served (url) form assetUrl() expects. Assets
// created as edits return a stored filePath ("data/assets/images/x.png") with no
// filename field; the served mount strips the "data/assets/" prefix.
export function toServedAssetPath(pathOrFilename) {
return String(pathOrFilename || '').replace(/\\/g, '/').replace(/^data\/assets\//, '')
}
export function mimeFromName(name = '') {
const ext = String(name).split('.').pop().toLowerCase()
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
if (ext === 'webp') return 'image/webp'
if (ext === 'gif') return 'image/gif'
if (ext === 'svg') return 'image/svg+xml'
return 'image/png'
}
export function extFromMime(mime = '') {
if (mime.includes('jpeg')) return 'jpg'
if (mime.includes('webp')) return 'webp'
if (mime.includes('gif')) return 'gif'
if (mime.includes('svg')) return 'svg'
return 'png'
}
// Fetch a served asset URL and return it as a data URL (Excalidraw renders
// images from data URLs in its `files` map).
export async function urlToDataURL(url) {
const res = await fetch(url)
if (!res.ok) throw new Error(`Failed to fetch image: ${res.status}`)
const blob = await res.blob()
return await blobToDataURL(blob)
}
export function blobToDataURL(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result)
reader.onerror = () => reject(new Error('Failed to read image blob'))
reader.readAsDataURL(blob)
})
}
export function dataURLToFile(dataURL, filename) {
const [meta, b64] = String(dataURL).split(',')
const mime = /data:(.*?)(;|$)/.exec(meta)?.[1] || 'image/png'
const binary = atob(b64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
return new File([bytes], filename, { type: mime })
}
// Natural pixel size of a data URL, capped so huge renders land at a usable
// size on the canvas while preserving aspect ratio.
export function measureImage(dataURL, maxDimension = 720) {
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
let { naturalWidth: w, naturalHeight: h } = img
if (!w || !h) { resolve({ width: 512, height: 512 }); return }
const largest = Math.max(w, h)
if (largest > maxDimension) {
const scale = maxDimension / largest
w = Math.round(w * scale)
h = Math.round(h * scale)
}
resolve({ width: w, height: h })
}
img.onerror = () => resolve({ width: 512, height: 512 })
img.src = dataURL
})
}

View file

@ -60,7 +60,7 @@ export const CONNECTOR_TYPE_META = {
}
export function normalizeCustomApiType(type) {
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing', 'mesh-rigging'].includes(type)
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing'].includes(type)
? type
: DEFAULT_CUSTOM_API_TYPE
}
@ -403,289 +403,6 @@ export function buildEdgeId(connection) {
return `edge:${connection.sourceNodeId}:${connection.outputId}:${connection.targetNodeId}:${connection.inputId}`
}
// Produce a clean, left-to-right layered layout that follows the connections.
//
// Nodes are layered into columns by longest path (roots with no incoming edge
// in column 0, every node one column right of its furthest-upstream source), so
// columns line up across the whole canvas. The nodes are then split into
// connected groups, and each group is laid out as its own tidy tree in a
// dedicated horizontal band stacked below the previous one — so distinct chains
// never interleave and it stays obvious which node feeds which. Within a group,
// each node's vertical center is relaxed toward the average of its connected
// neighbours (a few Sugiyama-style sweeps), which centers parents against their
// children. Returns a map of nodeId -> { x, y } for every id passed in.
export function computeReorganizedLayout(nodes, edges, options = {}) {
const horizontalGap = options.horizontalGap ?? 140
const verticalGap = options.verticalGap ?? 48
const groupGap = options.groupGap ?? 140
const defaultWidth = options.defaultWidth ?? 360
const defaultHeight = options.defaultHeight ?? 280
const sweeps = options.sweeps ?? 8
if (!Array.isArray(nodes) || nodes.length === 0) {
return {}
}
const nodeById = new Map(nodes.map(node => [node.id, node]))
const predecessors = new Map(nodes.map(node => [node.id, []]))
const successors = new Map(nodes.map(node => [node.id, []]))
const neighbours = new Map(nodes.map(node => [node.id, new Set()]))
for (const edge of edges || []) {
const source = String(edge.source)
const target = String(edge.target)
if (source === target || !nodeById.has(source) || !nodeById.has(target)) {
continue
}
successors.get(source).push(target)
predecessors.get(target).push(source)
neighbours.get(source).add(target)
neighbours.get(target).add(source)
}
// --- Layering (two passes) -----------------------------------------------
// Pass 1 (ASAP): longest path from the sources, via Kahn (cycle-safe). This
// gives the total number of columns.
const asapDepth = new Map(nodes.map(node => [node.id, 0]))
const remainingIndegree = new Map(nodes.map(node => [node.id, predecessors.get(node.id).length]))
const forwardQueue = nodes.filter(node => remainingIndegree.get(node.id) === 0).map(node => node.id)
const forwardProcessed = new Set()
while (forwardQueue.length > 0) {
const id = forwardQueue.shift()
if (forwardProcessed.has(id)) {
continue
}
forwardProcessed.add(id)
for (const next of successors.get(id)) {
if (asapDepth.get(next) < asapDepth.get(id) + 1) {
asapDepth.set(next, asapDepth.get(id) + 1)
}
remainingIndegree.set(next, remainingIndegree.get(next) - 1)
if (remainingIndegree.get(next) === 0) {
forwardQueue.push(next)
}
}
}
for (const node of nodes) {
if (!forwardProcessed.has(node.id)) {
const maxSourceDepth = predecessors.get(node.id)
.reduce((max, source) => Math.max(max, asapDepth.get(source) ?? 0), -1)
asapDepth.set(node.id, maxSourceDepth + 1)
}
}
const maxDepth = Math.max(...nodes.map(node => asapDepth.get(node.id)))
// Pass 2 (ALAP): longest path from each node to a sink, via reverse Kahn. The
// final column is `maxDepth - reverseDepth`, which pushes every node as far
// right as its earliest consumer allows. Input nodes therefore sit in the
// column immediately left of the node they feed, instead of being stranded in
// column 0 with an edge stretched across the whole graph.
const reverseDepth = new Map(nodes.map(node => [node.id, 0]))
const remainingOutdegree = new Map(nodes.map(node => [node.id, successors.get(node.id).length]))
const backwardQueue = nodes.filter(node => remainingOutdegree.get(node.id) === 0).map(node => node.id)
const backwardProcessed = new Set()
while (backwardQueue.length > 0) {
const id = backwardQueue.shift()
if (backwardProcessed.has(id)) {
continue
}
backwardProcessed.add(id)
for (const previous of predecessors.get(id)) {
if (reverseDepth.get(previous) < reverseDepth.get(id) + 1) {
reverseDepth.set(previous, reverseDepth.get(id) + 1)
}
remainingOutdegree.set(previous, remainingOutdegree.get(previous) - 1)
if (remainingOutdegree.get(previous) === 0) {
backwardQueue.push(previous)
}
}
}
for (const node of nodes) {
if (!backwardProcessed.has(node.id)) {
const maxSuccessorReverse = successors.get(node.id)
.reduce((max, successor) => Math.max(max, reverseDepth.get(successor) ?? 0), -1)
reverseDepth.set(node.id, maxSuccessorReverse + 1)
}
}
const depth = new Map(nodes.map(node => [node.id, maxDepth - reverseDepth.get(node.id)]))
const getDimensions = (id) => {
const node = nodeById.get(id)
return {
width: node.measured?.width || node.width || defaultWidth,
height: node.measured?.height || node.height || defaultHeight
}
}
// Column x positions use the widest node in each column, shared across every
// group so the columns stay aligned down the whole canvas.
const columnWidth = new Map()
for (const node of nodes) {
const columnKey = depth.get(node.id)
columnWidth.set(columnKey, Math.max(columnWidth.get(columnKey) ?? 0, getDimensions(node.id).width))
}
const columnX = new Map()
let cursorX = 0
for (const columnKey of [...columnWidth.keys()].sort((a, b) => a - b)) {
columnX.set(columnKey, cursorX)
cursorX += columnWidth.get(columnKey) + horizontalGap
}
// Split into connected groups (undirected) via flood fill.
const groupByNode = new Map()
const groups = []
for (const node of nodes) {
if (groupByNode.has(node.id)) {
continue
}
const members = []
const stack = [node.id]
groupByNode.set(node.id, groups.length)
while (stack.length > 0) {
const id = stack.pop()
members.push(id)
for (const neighbour of neighbours.get(id)) {
if (!groupByNode.has(neighbour)) {
groupByNode.set(neighbour, groups.length)
stack.push(neighbour)
}
}
}
groups.push(members)
}
// Keep groups in a stable order: by their leftmost column, then by their
// current average vertical position.
const averageOf = (values) => values.reduce((sum, value) => sum + value, 0) / values.length
groups.sort((a, b) => {
const columnA = Math.min(...a.map(id => depth.get(id)))
const columnB = Math.min(...b.map(id => depth.get(id)))
if (columnA !== columnB) {
return columnA - columnB
}
return averageOf(a.map(id => nodeById.get(id).position?.y ?? 0))
- averageOf(b.map(id => nodeById.get(id).position?.y ?? 0))
})
const positions = {}
let bandTop = 0
for (const members of groups) {
// Bucket this group's nodes into their columns.
const groupColumns = new Map()
for (const id of members) {
const columnKey = depth.get(id)
if (!groupColumns.has(columnKey)) {
groupColumns.set(columnKey, [])
}
groupColumns.get(columnKey).push(id)
}
const columnKeys = [...groupColumns.keys()].sort((a, b) => a - b)
// Seed each column's vertical order by current position, then refine with a
// barycenter pass so connected nodes end up adjacent (fewer crossings).
const orderIndex = new Map()
const reindex = (columnKey) => groupColumns.get(columnKey).forEach((id, index) => orderIndex.set(id, index))
for (const columnKey of columnKeys) {
groupColumns.get(columnKey).sort((a, b) => (nodeById.get(a).position?.y ?? 0) - (nodeById.get(b).position?.y ?? 0))
reindex(columnKey)
}
for (const columnKey of columnKeys) {
if (columnKey === columnKeys[0]) {
continue
}
const column = groupColumns.get(columnKey)
const barycenter = new Map()
for (const id of column) {
const sources = predecessors.get(id)
barycenter.set(id, sources.length > 0
? averageOf(sources.map(source => orderIndex.get(source) ?? 0))
: (orderIndex.get(id) ?? 0))
}
column.sort((a, b) => barycenter.get(a) - barycenter.get(b))
reindex(columnKey)
}
// Initial vertical centers: stack each column top-to-bottom.
const centerY = new Map()
for (const columnKey of columnKeys) {
let cursorY = 0
for (const id of groupColumns.get(columnKey)) {
const { height } = getDimensions(id)
centerY.set(id, cursorY + height / 2)
cursorY += height + verticalGap
}
}
// Pack a column: honor each node's desired center where possible while
// keeping the column order and a minimum gap (a forward pass that only ever
// pushes nodes downward, so overlaps are impossible), then apply a single
// uniform shift so the column stays centered on the neighbours' barycenter
// instead of drifting downward over repeated passes.
const packColumn = (column, desiredCenters) => {
centerY.set(column[0], desiredCenters.get(column[0]))
for (let index = 1; index < column.length; index += 1) {
const previous = column[index - 1]
const current = column[index]
const minCenter = centerY.get(previous)
+ getDimensions(previous).height / 2
+ verticalGap
+ getDimensions(current).height / 2
centerY.set(current, Math.max(desiredCenters.get(current), minCenter))
}
const drift = averageOf(column.map(id => desiredCenters.get(id)))
- averageOf(column.map(id => centerY.get(id)))
for (const id of column) {
centerY.set(id, centerY.get(id) + drift)
}
}
// Relaxation sweeps: alternate directions, pulling each node toward the
// average center of its neighbours in the adjacent columns.
for (let sweep = 0; sweep < sweeps; sweep += 1) {
const order = sweep % 2 === 0 ? columnKeys : [...columnKeys].reverse()
for (const columnKey of order) {
const column = groupColumns.get(columnKey)
const desiredCenters = new Map()
for (const id of column) {
const connected = [...predecessors.get(id), ...successors.get(id)]
.filter(neighbour => groupByNode.get(neighbour) === groupByNode.get(id))
desiredCenters.set(id, connected.length > 0
? averageOf(connected.map(neighbour => centerY.get(neighbour)))
: centerY.get(id))
}
packColumn(column, desiredCenters)
}
}
// Drop this group into its own band, normalising so the group's topmost
// edge starts at bandTop.
let groupTop = Infinity
let groupBottom = -Infinity
for (const id of members) {
const { height } = getDimensions(id)
groupTop = Math.min(groupTop, centerY.get(id) - height / 2)
groupBottom = Math.max(groupBottom, centerY.get(id) + height / 2)
}
for (const id of members) {
const { width, height } = getDimensions(id)
const column = depth.get(id)
positions[id] = {
x: columnX.get(column) + (columnWidth.get(column) - width) / 2,
y: bandTop + (centerY.get(id) - height / 2) - groupTop
}
}
bandTop += (groupBottom - groupTop) + groupGap
}
return positions
}
export function getPointerClientPosition(event) {
if ('clientX' in event && 'clientY' in event) {
return { x: event.clientX, y: event.clientY }
@ -761,11 +478,9 @@ export function isFileWorkflowValueType(valueType) {
return ['image', 'video', 'mesh'].includes(valueType)
}
export const MESH_FILE_EXTENSIONS = ['glb', 'gltf', 'obj', 'fbx', 'stl', 'ply', 'usdz', 'usd', 'usda', 'usdc']
export function getWorkflowFileInputAccept(valueType) {
if (valueType === 'video') return 'video/*'
if (valueType === 'mesh') return MESH_FILE_EXTENSIONS.map(ext => `.${ext}`).join(',')
if (valueType === 'mesh') return '.glb,.gltf,.obj,.fbx,.stl,.ply,.usdz,.usd,.usda,.usdc'
return 'image/*'
}

View file

@ -49,7 +49,6 @@ export const IMAGE_CARD_COLUMNS = [
{ id: 'meshgen', dbId: 3, icon: 'deployed_code', title: 'MESH GEN', showAttributes: true, emptyLabel: 'Drag an image card here to generate a mesh' },
{ id: 'meshedit', dbId: 4, icon: 'edit_square', title: 'MESH EDIT', showAttributes: true, emptyLabel: 'Drag a mesh card here to edit it' },
{ id: 'texturing', dbId: 5, icon: 'texture', title: 'TEXTURING', showAttributes: true, emptyLabel: 'Drag a mesh card here to texture it' },
{ id: 'rigging', dbId: 6, icon: 'accessibility_new', title: 'RIGGING', showAttributes: true, emptyLabel: 'Drag a mesh card here to rig it' },
]
export const DEFAULT_ATTRIBUTE_TYPE_ID = 1
@ -72,7 +71,7 @@ export function getWorkflowFileInputIcon(valueType) {
}
export function normalizeCustomApiType(type) {
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing', 'mesh-rigging'].includes(type)
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit', 'mesh-texturing'].includes(type)
? type
: DEFAULT_CUSTOM_API_TYPE
}

View file

@ -10,41 +10,13 @@ import { PLYExporter } from 'three/examples/jsm/exporters/PLYExporter.js'
import { STLExporter } from 'three/examples/jsm/exporters/STLExporter.js'
import { API_BASE } from '../config'
// kind 'local' — serialized in the browser with three.js exporters. GLB is
// special-cased by the export dialog: a .glb source asset is copied
// byte-for-byte (rig, animations and textures untouched) instead of being
// round-tripped through three.js; it imports natively into Blender.
// kind 'preset' — engine-targeted FBX exports (Unity/Unreal/generic). FBX has
// no three.js exporter, so those go through the mesh-tools service, which runs
// headless Blender to convert a GLB into an engine-tuned FBX (skeleton + one
// animation take per clip). Presets are only offered when exporting from a
// mesh URL (asset library preview) — the mesh editor exports raw geometry.
// Formats we can reliably serialize with three.js. FBX has no official
// exporter, so it is intentionally excluded.
export const EXPORT_FORMATS = [
{
value: 'glb', label: 'GLB — single file, textures embedded', extension: 'glb', multiFile: false, kind: 'local',
hint: 'Includes the rig and every animation clip; GLB source assets are copied byte-for-byte for perfect fidelity. Imports natively into Blender (File > Import > glTF 2.0). Note: Blender’s importer may add an "Icosphere" bone-widget object — viewport dressing created at import time, not part of the file (set Bone Dir to "Temperance" to avoid it).'
},
{
value: 'unity', label: 'Unity — FBX (rig + animation takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'unity', requiresService: true,
hint: 'Drop the .fbx into Assets. Textures are embedded — use Materials > Extract Textures. Pick the rig type under Rig (Humanoid may need Enforce T-Pose); each clip appears as a separate take.'
},
{
value: 'unreal', label: 'Unreal Engine — FBX (cm, rig + takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'unreal', requiresService: true,
hint: 'Import as Skeletal Mesh with "Import Animations" enabled. The file is exported in centimeters at scale 1 — no unit conversion needed.'
},
{
value: 'fbx', label: 'FBX — generic (rig + animation takes)', extension: 'fbx', multiFile: false,
kind: 'preset', preset: 'generic', requiresService: true,
hint: 'Neutral FBX (meters, Y-up) with the skeleton and one take per animation clip. Suitable for Godot, Maya, 3ds Max and other DCC tools.'
},
{
value: 'obj', label: 'OBJ — geometry + .mtl + textures', extension: 'obj', multiFile: true, kind: 'local',
hint: 'OBJ saves geometry, materials and textures as separate files named after the mesh (e.g. mesh.obj, mesh.mtl, mesh_albedo.png).'
},
{ value: 'ply', label: 'PLY — geometry only', extension: 'ply', multiFile: false, kind: 'local' },
{ value: 'stl', label: 'STL — geometry only', extension: 'stl', multiFile: false, kind: 'local' }
{ value: 'glb', label: 'GLB — single file, textures embedded', extension: 'glb', multiFile: false },
{ value: 'obj', label: 'OBJ — geometry + .mtl + textures', extension: 'obj', multiFile: true },
{ value: 'ply', label: 'PLY — geometry only', extension: 'ply', multiFile: false },
{ value: 'stl', label: 'STL — geometry only', extension: 'stl', multiFile: false }
]
function defaultMaterial() {
@ -57,13 +29,6 @@ function getExtensionFromUrl(url) {
return dot >= 0 ? clean.slice(dot).toLowerCase() : ''
}
// True when the URL points at a binary glTF — those sources can be exported
// byte-for-byte (or fed to the FBX converter) without a lossy three.js
// round-trip.
export function isGlbUrl(url) {
return getExtensionFromUrl(url) === '.glb'
}
function loadWithLoader(loader, url) {
return new Promise((resolve, reject) => {
loader.load(url, resolve, undefined, reject)
@ -89,10 +54,6 @@ export async function loadObject3DFromUrl(url) {
if (!scene) {
throw new Error('The glTF file did not contain a scene to export.')
}
// Carry the clips on the object (FBXLoader's convention) so exportGlb can
// hand them to GLTFExporter — otherwise animated assets re-export silently
// stripped of their animations.
scene.animations = Array.isArray(gltf.animations) ? gltf.animations : []
return scene
}
@ -164,10 +125,7 @@ function exportGlb(object, base) {
resolve([{ filename: `${base}.glb`, blob: new Blob([result], { type: 'model/gltf-binary' }) }])
},
error => reject(error instanceof Error ? error : new Error('Failed to export the mesh as GLB.')),
// Loader-produced clips are already node-name-addressed, so they need no
// track renaming here — the `.bones[...]` rewrite in animationLibrary.js
// exists only for the retargeter's mixer-bound clips.
{ binary: true, onlyVisible: false, animations: object.animations || [] }
{ binary: true, onlyVisible: false }
)
})
}

View file

@ -127,14 +127,6 @@ export function repairMesh(meshBlob, opts = {}) {
return callMeshTool('/meshes/repair', meshBlob, opts)
}
// GLB -> FBX engine-preset conversion (headless Blender in the mesh-tools
// service). options: { preset: 'unity'|'unreal'|'generic', ... } — see the
// service's ConvertOptions. Same SSE contract; the returned blob is the FBX and
// stats.tool carries { bones, meshes, clips, preset, validation }.
export function convertMesh(meshBlob, opts = {}) {
return callMeshTool('/meshes/convert', meshBlob, { ...opts, format: 'fbx' })
}
// Auto Rig (SkinTokens/TokenRig). Proxies to the dedicated rigging service; the
// returned blob is a SKINNED GLB (mesh + skeleton + skin weights) — unlike the
// tools above it must NOT be flattened into editable geometry. Same SSE contract;

View file

@ -21,11 +21,7 @@ export function buildWorkflowDefaultsPayload(workflow, values = {}) {
const base = {
id: parameter.id,
name: parameter.name,
valueType,
// Echo the allowed-value list back so saving defaults never drops it.
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
? { enums: [...parameter.enums] }
: {})
valueType
}
// Only String / Number / Boolean fields are saved as defaults. File-type params

View file

@ -1,75 +0,0 @@
// Enum support for ComfyUI workflow parameters.
//
// A String or Number parameter can carry an `enums` array that restricts it to a
// fixed list of allowed values. Every AI panel renders such a parameter as a
// dropdown instead of a free-form field, so the value can only ever be one the
// workflow actually accepts.
//
// Values keep their real type in storage (numbers stay numbers) while <select>
// values are always strings — hence resolveWorkflowEnumValue, which maps a picked
// option back to its typed entry.
const ENUM_VALUE_TYPES = ['string', 'number']
// The allowed values of a parameter, or null when it isn't an enum parameter.
export function getWorkflowParameterEnums(parameter) {
if (!Array.isArray(parameter?.enums)) return null
const values = parameter.enums.filter(value => typeof value === 'string' || typeof value === 'number')
return values.length > 0 ? values : null
}
export function isEnumWorkflowValueType(valueType) {
return ENUM_VALUE_TYPES.includes(valueType)
}
// Options for a <select>, or null when the parameter has no enums. A current
// value outside the list is kept as an extra option so an older saved value is
// never silently rewritten.
export function getWorkflowEnumOptions(parameter, currentValue) {
const enums = getWorkflowParameterEnums(parameter)
if (!enums) return null
const options = enums.map(value => ({ value: String(value), label: String(value) }))
if (currentValue !== undefined && currentValue !== null && currentValue !== ''
&& !options.some(option => option.value === String(currentValue))) {
options.unshift({ value: String(currentValue), label: `${currentValue} (custom)` })
}
return options
}
// Map a <select> value (always a string) back to the typed enum entry.
export function resolveWorkflowEnumValue(parameter, rawValue) {
const enums = getWorkflowParameterEnums(parameter)
const match = enums?.find(value => String(value) === String(rawValue))
return match === undefined ? rawValue : match
}
// Parse the workflow editor's enum field (one value per line) into stored values.
export function parseWorkflowEnumsInput(text, valueType) {
if (!isEnumWorkflowValueType(valueType)) return []
const values = []
for (const line of String(text || '').split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
if (valueType === 'number') {
const numeric = Number(trimmed)
if (!Number.isFinite(numeric) || values.includes(numeric)) continue
values.push(numeric)
continue
}
if (!values.includes(trimmed)) values.push(trimmed)
}
return values
}
// Render stored enums back into the editor field (one value per line).
export function formatWorkflowEnumsInput(enums) {
return Array.isArray(enums) ? enums.join('\n') : ''
}

View file

@ -26,12 +26,7 @@ export function buildShareableWorkflow(workflow) {
parameters: (workflow?.parameters || []).map(parameter => ({
id: parameter.id,
name: parameter.name,
valueType: parameter.valueType,
// Only String/Number parameters carry an allowed-value list; omit the key
// entirely for the rest so bundles stay as small as they were.
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
? { enums: [...parameter.enums] }
: {})
valueType: parameter.valueType
})),
outputs: (workflow?.outputs || []).map(output => ({
nodeId: output.nodeId,

1016
storage.js

File diff suppressed because it is too large Load diff

View file

@ -14,9 +14,7 @@ exits non-zero on failure so the caller can skip the install.
"""
from __future__ import annotations
import os
import re
import shutil
import sys
import tempfile
import urllib.parse
@ -42,21 +40,13 @@ def download(url: str) -> str:
return hf_hub_download(repo_id=repo_id, filename=filename)
# Plain HTTP(S) download (e.g. GitHub release assets).
#
# The original basename MUST be preserved. pip/uv read the distribution name,
# version and compatibility tags out of the wheel FILENAME, so a mkstemp name
# like "flash_attn_t5eu90p9.whl" is rejected before the file is even opened:
# error: The wheel filename "flash_attn_t5eu90p9.whl" is invalid: Must have a version
# So download into a temp DIRECTORY and keep the name the server gave us.
name = os.path.basename(urllib.parse.unquote(urllib.parse.urlparse(url).path))
if not name.endswith(".whl"):
raise ValueError(f"URL does not name a .whl file: {url}")
path = os.path.join(tempfile.mkdtemp(prefix="flash_attn_"), name)
fd, path = tempfile.mkstemp(suffix=".whl", prefix="flash_attn_")
import os
os.close(fd)
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
# copyfileobj streams: these wheels are a few hundred MB and don't need to be
# held in memory in one piece.
with urllib.request.urlopen(req) as resp, open(path, "wb") as out:
shutil.copyfileobj(resp, out)
out.write(resp.read())
return path

View file

@ -1,3 +0,0 @@
Torch;Cuda;Link;PyTorchLink
2.13.0;12.6.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu126torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision --index-url https://download.pytorch.org/whl/cu126
2.13.0;13.0.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision

View file

@ -6,18 +6,12 @@
#
# On first run it uses `uv` to provision a pinned standalone Python (see
# .python-version -> 3.13) and installs the SkinTokens requirements, torch, a
# flash-attn wheel, and the model checkpoints. Like Windows, Linux installs
# flash-attn from a curated prebuilt wheel (flash_attention_linux.txt) rather than
# `pip install flash-attn`, which compiles from source and takes about an hour.
# uv is auto-installed if absent.
# flash-attn wheel, and the model checkpoints. Unlike Windows (which needs the
# curated flash_attention_windows.txt wheels), Linux gets flash-attn straight
# from pip, which resolves a prebuilt wheel for the installed torch/CUDA/Python
# (or builds it — needs the CUDA toolkit + ninja). uv is auto-installed if absent.
#
# Env overrides:
# RIGTOOLS_PORT / RIGTOOLS_HOST bind address
# RIGTOOLS_CUDA=12.6 force the CUDA build to target (skip nvidia-smi)
# RIGTOOLS_SKIP_FLASH=1 don't install flash-attn
# RIGTOOLS_BUILD_FLASH=1 if no curated wheel matches, build from source
# instead of giving up (~1 hour, needs nvcc+ninja)
# RIGTOOLS_SKIP_MODEL=1 don't download the model checkpoints
# Env overrides: RIGTOOLS_PORT/HOST, RIGTOOLS_SKIP_FLASH=1, RIGTOOLS_SKIP_MODEL=1.
set -euo pipefail
cd "$(dirname "$0")"
PYVER=3.13
@ -48,70 +42,22 @@ if [ ! -x ".venv/bin/python" ]; then
# shellcheck disable=SC1091
source .venv/bin/activate
# --- Pick a prebuilt flash-attn wheel + its matching torch install ----------
# select_flash_attn.py picks the table for this platform (flash_attention_linux.txt
# here) and, on a CUDA match, prints:
# WHEEL=<flash-attn wheel url>
# TORCHARGS=<torch~=.. torchvision .. [--index-url ..]>
# Prints nothing on no match. Python is pinned to 3.13 by uv, so the wheels (all
# cp313) always fit; only CUDA has to be matched.
echo
echo "Detecting CUDA to select a flash-attn wheel..."
WHEEL=""
TORCHARGS=""
while IFS= read -r line; do
case "$line" in
WHEEL=*) WHEEL="${line#WHEEL=}" ;;
TORCHARGS=*) TORCHARGS="${line#TORCHARGS=}" ;;
esac
done < <(python select_flash_attn.py)
echo
echo "Installing SkinTokens requirements..."
"$UV" pip install -r requirements.txt
# torch AFTER requirements so it overrides the torch `lightning` pulls in. The
# curated TORCHARGS pins torch to the version the flash-attn wheel was built
# against, so the ABI matches. On Linux the PyPI torch wheels bundle CUDA, so a
# row may legitimately carry no --index-url.
# torch AFTER requirements so it overrides the torch `lightning` pulls in. On
# Linux the default PyPI torch wheels bundle CUDA, so no custom index is needed.
echo
if [ -n "$TORCHARGS" ]; then
echo "Installing torch: $TORCHARGS"
# shellcheck disable=SC2086 -- curated arg list; word-splitting is intended
"$UV" pip install $TORCHARGS
else
echo "No matching prebuilt flash-attn wheel -- installing default torch (CUDA build from PyPI)..."
"$UV" pip install torch torchvision
fi
echo "Installing torch (CUDA build)..."
"$UV" pip install torch torchvision torchaudio
# --- flash-attn -------------------------------------------------------------
echo
if [ -n "${RIGTOOLS_SKIP_FLASH:-}" ]; then
echo "RIGTOOLS_SKIP_FLASH set -- skipping flash-attn."
elif [ -n "$WHEEL" ]; then
echo "Downloading + installing prebuilt flash-attn wheel..."
# Fetch to a local path first: `pip install <hf-url>` 403s on Hugging Face
# Xet-backed files. GitHub release assets go over plain urllib.
if FA_WHEEL="$(python download_wheel.py "$WHEEL" | tail -n 1)" && [ -n "$FA_WHEEL" ]; then
"$UV" pip install "$FA_WHEEL" || echo "[warn] flash-attn install failed; continuing without it."
else
echo "[warn] flash-attn download failed; continuing without it."
fi
elif [ -n "${RIGTOOLS_BUILD_FLASH:-}" ]; then
echo "No curated wheel matched -- building flash-attn from source (this takes ~an hour)..."
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn build failed; continuing without it."
else
echo "[warn] No prebuilt flash-attn wheel matched this CUDA; flash-attn was NOT installed."
echo " rig_server.py cannot import without it. Either add a row for your"
echo " CUDA/torch to flash_attention_linux.txt, or build from source with:"
echo " RIGTOOLS_BUILD_FLASH=1 ./run_server.sh # ~1 hour, needs nvcc + ninja"
fi
# A wheel built against a different torch ABI installs cleanly and only fails at
# import ("undefined symbol: _ZN3c10..."), so check now rather than mid-rig.
if [ -z "${RIGTOOLS_SKIP_FLASH:-}" ]; then
python -c 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)' \
|| echo "[warn] flash-attn does not import -- likely a torch ABI mismatch with the selected wheel."
echo "Installing flash-attn (prebuilt wheel if available, else builds from source)..."
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn install failed; continuing without it."
fi
echo

View file

@ -1,63 +1,50 @@
"""Pick the prebuilt flash-attn wheel + matching torch install for this machine.
Building flash-attn from source takes ~an hour on BOTH Windows and Linux, so we
always prefer a precompiled wheel. There is one curated table per platform —
``flash_attention_windows.txt`` (win_amd64 wheels) and
``flash_attention_linux.txt`` (linux_x86_64 wheels) — and this script picks the
table matching the host. Each lists, per row:
Building flash-attn from source on Windows takes ages, so we prefer a
precompiled wheel. ``flash_attention_windows.txt`` lists, per row:
Torch;Cuda;Link;PyTorchLink
│ │ │ └ the exact `pip install torch... [--index-url ...]` command
│ │ │ └ the exact `pip install torch... --index-url ...` command
│ │ │ that pairs with this flash-attn wheel (ABI-matched)
│ │ └ flash-attn wheel URL
│ └ CUDA build the wheel targets (match key against the driver;
│ "13.0" and "13.0.0" both work — only major.minor is compared)
│ └ CUDA build the wheel targets (match key against the driver)
└ torch version (informational; also encoded in the wheel + PyTorchLink)
Python is pinned to 3.13 by uv (see .python-version) so it is no longer a match
key — every wheel in both tables is cp313. We just pick the newest CUDA build
the driver can run and hand the caller both pieces to install.
key — every wheel here is cp313. We just pick the newest CUDA build the driver
can run and hand the caller both pieces to install.
On a match it prints two `KEY=value` lines to stdout:
WHEEL=https://.../flash_attn-...cp313-win_amd64.whl
TORCHARGS=torch==2.12.0 torchvision==0.27.0 --index-url https://download.pytorch.org/whl/cu130
(``TORCHARGS`` is column 4 with the leading ``pip install`` / ``pip3 install``
stripped, so the caller can run it with ``uv pip install``.) On no match — no
NVIDIA driver, an unsupported platform/arch, or a driver older than every listed
CUDA build — it prints nothing and exits 0; the caller decides what that means.
(``TORCHARGS`` is column 4 with the leading ``pip install`` stripped, so the
caller can run it with ``uv pip install``.) On no match it prints nothing.
Diagnostics go to stderr. Standard library + nvidia-smi only.
macOS has no CUDA, so rigging is unavailable there and this prints nothing.
Override CUDA detection with RIGTOOLS_CUDA (e.g. "12.8").
"""
from __future__ import annotations
import os
import platform
import re
import shutil
import subprocess
import sys
from pathlib import Path
_HERE = Path(__file__).resolve().parent
# Wheels are platform-tagged: a win_amd64 wheel is rejected outright by pip/uv on
# Linux ("wheel is compatible with Windows, but you're on Linux"), so the table
# MUST follow the host rather than being a single shared list.
WHEELS_FILE = _HERE / ("flash_attention_windows.txt" if sys.platform == "win32"
else "flash_attention_linux.txt")
WHEELS_FILE = Path(__file__).resolve().parent / "flash_attention_windows.txt"
def driver_cuda() -> float | None:
"""Max CUDA version the NVIDIA driver supports (from nvidia-smi), or None."""
override = os.environ.get("RIGTOOLS_CUDA")
if override:
forced = cuda_key(override)
if forced is not None:
return forced
try:
return float(override)
except ValueError:
pass
exe = shutil.which("nvidia-smi")
if not exe:
return None
@ -69,17 +56,6 @@ def driver_cuda() -> float | None:
return float(f"{m.group(1)}.{m.group(2)}") if m else None
def cuda_key(text: str) -> float | None:
"""Normalise a CUDA column to a comparable major.minor float.
Accepts "13", "13.0" and "13.0.0" — the Linux table quotes three-part CUDA
versions, and a bare float() on those raises, which would silently drop the
row and look identical to "no GPU".
"""
m = re.match(r"\s*(\d+)(?:\.(\d+))?", text)
return float(f"{m.group(1)}.{m.group(2) or 0}") if m else None
def parse_rows():
"""Yield (torch_ver, cuda: float, wheel_url, torch_args) from the wheels file."""
rows = []
@ -91,37 +67,19 @@ def parse_rows():
if len(parts) < 4:
continue
torch_ver, cuda, link, pytorch_cmd = parts[0], parts[1], parts[2], parts[3]
cuda_f = cuda_key(cuda)
if cuda_f is None:
try:
cuda_f = float(cuda)
except ValueError:
continue
# Strip the leading "pip install" / "pip3 install" (or the "uv "-prefixed
# forms) so the caller can run it via `uv pip install <args>`.
args = re.sub(r"^\s*(uv\s+)?pip3?\s+install\s+", "", pytorch_cmd).strip()
# Strip the leading "pip install" (or "uv pip install") so the caller can
# run it via `uv pip install <args>`.
args = re.sub(r"^\s*(uv\s+)?pip\s+install\s+", "", pytorch_cmd).strip()
rows.append((torch_ver, cuda_f, link, args))
return rows
def main() -> None:
py = f"{sys.version_info.major}.{sys.version_info.minor}"
# Platform/arch gates first: both tables ship x86_64 wheels for a CUDA GPU, so
# anywhere else there is nothing to pick and saying so beats letting the caller
# download multi-GB of torch on the way to an unavoidable failure.
if sys.platform == "darwin":
print("[flash-attn] macOS has no CUDA; rigging is unavailable here.", file=sys.stderr)
return
if sys.platform not in ("win32", "linux"):
print(f"[flash-attn] Unsupported platform {sys.platform!r}; no prebuilt wheels listed.", file=sys.stderr)
return
arch = platform.machine().lower()
if arch not in ("x86_64", "amd64"):
print(f"[flash-attn] Unsupported CPU architecture {arch!r} — the listed wheels are "
f"x86_64 only.", file=sys.stderr)
return
if not WHEELS_FILE.exists():
print(f"[flash-attn] Missing wheel table {WHEELS_FILE.name}.", file=sys.stderr)
return
cuda = driver_cuda()
if cuda is None:
print("[flash-attn] No NVIDIA GPU / CUDA detected; skipping prebuilt wheel.", file=sys.stderr)
@ -129,7 +87,7 @@ def main() -> None:
rows = parse_rows()
if not rows:
print(f"[flash-attn] No usable rows in {WHEELS_FILE.name}.", file=sys.stderr)
print("[flash-attn] No usable rows in flash_attention_windows.txt.", file=sys.stderr)
return
# Rows whose CUDA build the driver can run (wheel_cuda <= driver_cuda),
@ -145,8 +103,8 @@ def main() -> None:
if py != "3.13":
print(f"[flash-attn] WARNING: running Python {py}, but the wheels are cp313. "
f"Expect an install failure unless the venv is Python 3.13.", file=sys.stderr)
print(f"[flash-attn] {WHEELS_FILE.name}: driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, "
f"torch {torch_ver}.", file=sys.stderr)
print(f"[flash-attn] driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, torch {torch_ver}.",
file=sys.stderr)
print(f"WHEEL={link}")
print(f"TORCHARGS={torch_args}")

View file

@ -1,706 +0,0 @@
from copy import deepcopy
from dataclasses import dataclass
from typing import Tuple, Union, List, Optional, Dict
from numpy import ndarray
from abc import ABC, abstractmethod
from scipy.spatial.transform import Rotation as R
import numpy as np
import random
from .spec import ConfigSpec
from ..rig_package.utils import axis_angle_to_matrix
from ..rig_package.info.asset import Asset
@dataclass(frozen=True)
class Augment(ConfigSpec):
@classmethod
@abstractmethod
def parse(cls, **kwags) -> 'Augment':
pass
@abstractmethod
def transform(self, asset: Asset, **kwargs):
pass
@dataclass(frozen=True)
class AugmentTrim(Augment):
"""randomly delete joints and vertices"""
@classmethod
def parse(cls, **kwargs) -> 'AugmentTrim':
cls.check_keys(kwargs)
return AugmentTrim()
def transform(self, asset: Asset, **kwargs):
asset.trim_skeleton()
@dataclass(frozen=True)
class AugmentDelete(Augment):
"""randomly delete joints and vertices"""
# probability
p: float
# how much to keep
rate: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentDelete':
cls.check_keys(kwargs)
return AugmentDelete(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.5),
)
def transform(self, asset: Asset, **kwargs):
if asset.skin is None:
raise ValueError("do not have skin")
if asset.parents is None:
raise ValueError("do not have parents")
asset.normalize_skin()
def select_k(arr: List, k: int):
if len(arr) <= k:
return arr
else:
rest_indices = list(range(1, len(arr)))
selected_indices = sorted(random.sample(rest_indices, k))
return [arr[i] for i in selected_indices]
if np.random.rand() >= self.p:
return
ids = select_k([i for i in range(asset.J)], max(int(asset.J * (1 - np.random.rand() * self.rate)), 1))
if len(ids) == 0:
return
# keep bones with no skin
keep = {}
for id in ids:
keep[id] = True
for id in range(asset.J):
if np.all(asset.skin[:, id] < 0.1):
keep[id] = True
keep[asset.root] = True
vertices_to_delete = np.zeros(asset.N, dtype=bool)
for id in range(asset.J):
if id not in keep:
dominant = asset.skin.argmax(axis=1) == id
x = (asset.skin[:, id] > 0.1) & dominant
if np.all(~x) or x.sum() * asset.J < asset.N: # avoid collapsing
keep[id] = 1
continue
vertices_to_delete[x] = True
if np.all(vertices_to_delete):
return
if asset.faces is not None:
indices = np.where(~vertices_to_delete)[0]
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
if np.all(~face_mask):
return
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
asset.delete_joints(joints_to_delete)
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
@dataclass(frozen=True)
class AugmentDropPart(Augment):
"""randomly drop subtrees and their vertices"""
# probability
p: float
# drop rate
rate: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentDropPart':
cls.check_keys(kwargs)
return AugmentDropPart(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.5),
)
def transform(self, asset: Asset, **kwargs):
if np.random.rand() >= self.p:
return
if asset.parents is None:
raise ValueError("do not have parents")
if asset.skin is None:
raise ValueError("do not have skin")
keep = []
for id in range(asset.J):
if np.random.rand() < self.rate:
keep.append(id)
if len(keep) == 0:
return
for id in reversed(asset.dfs_order):
p = asset.parents[id]
if p == -1:
continue
if id in keep and p not in keep:
keep.append(p)
mask = np.zeros(asset.N, dtype=bool)
for id in keep:
mask[asset.skin[:, id] > 1e-5] = True
vertices_to_delete = ~mask
if np.all(vertices_to_delete):
return
if asset.faces is not None:
indices = np.where(~vertices_to_delete)[0]
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
if np.all(~face_mask):
return
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
asset.delete_joints(joints_to_delete)
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
def inverse(self, asset: Asset):
pass
@dataclass(frozen=True)
class AugmentCollapse(Augment):
"""randomly merge joints"""
# collapse the skeleton with probability p
p: float
# probability to merge the bone
rate: float
# max bones
max_bones: int
@classmethod
def parse(cls, **kwargs) -> 'AugmentCollapse':
cls.check_keys(kwargs)
return AugmentCollapse(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.),
max_bones=kwargs.get('max_bones', 2147483647),
)
def transform(self, asset: Asset, **kwargs):
def select_k(arr: List, k: int):
if len(arr) <= k:
return arr
else:
rest_indices = list(range(1, len(arr)))
selected_indices = sorted(random.sample(rest_indices, k))
return [arr[i] for i in selected_indices]
root = asset.root
if np.random.rand() < self.p:
ids = []
for id in range(asset.J):
if np.random.rand() >= self.rate:
ids.append(id)
if root not in ids:
ids.append(root)
keep: List[int|str] = select_k([i for i in range(asset.J) if i in ids], self.max_bones)
if root not in keep:
keep[0] = root
asset.set_order(new_orders=keep)
elif asset.J > self.max_bones:
ids = select_k([i for i in range(asset.J)], k=self.max_bones)
if root not in ids:
ids[0] = root
keep: List[int|str] = [i for i in range(asset.J) if i in ids]
asset.set_order(new_orders=keep)
@dataclass(frozen=True)
class AugmentJointDiscrete(Augment):
# perturb the skeleton with probability p
p: float
# num of discretized coord
discrete: int
# continuous range
continuous_range: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentJointDiscrete':
cls.check_keys(kwargs)
return AugmentJointDiscrete(
p=kwargs.get('p', 0.),
discrete=kwargs.get('discrete', 256),
continuous_range=kwargs.get('continuous_range', [-1., 1.]),
)
def _discretize(
self,
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = (t - lo) / (hi - lo)
t *= num_discrete
return np.clip(t.round(), 0, num_discrete - 1).astype(np.int64)
def _undiscretize(
self,
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = t.astype(np.float32) + 0.5
t /= num_discrete
return t * (hi - lo) + lo
def transform(self, asset: Asset, **kwargs):
if np.random.rand() < self.p:
joints = asset.joints
if joints is not None and asset.matrix_local is not None:
joints = self._undiscretize(self._discretize(
joints,
self.continuous_range,
self.discrete,
),
self.continuous_range,
self.discrete,
)
asset.matrix_local[:, :3, 3] = joints
@dataclass(frozen=True)
class AugmentJointPerturb(Augment):
# perturb the skeleton with probability p
p: float
# jitter sigma on joints
sigma: float
# jitter clip on joints
clip: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentJointPerturb':
cls.check_keys(kwargs)
return AugmentJointPerturb(
p=kwargs.get('p', 0.),
sigma=kwargs.get('sigma', 0.),
clip=kwargs.get('clip', 0.),
)
def transform(self, asset: Asset, **kwargs):
if np.random.rand() < self.p and asset.matrix_local is not None:
asset.matrix_local[:, :3] += np.clip(
np.random.normal(0, self.sigma, (asset.J, 3)),
-self.clip,
self.clip,
)
@dataclass(frozen=True)
class AugmentLBS(Augment):
# apply a random pose with probability p
random_pose_p: float
# random pose angle range
random_pose_angle: float
# random scale
random_scale_range: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentLBS':
cls.check_keys(kwargs)
return AugmentLBS(
random_pose_p=kwargs.get('random_pose_p', 0.),
random_pose_angle=kwargs.get('random_pose_angle', 0.),
random_scale_range=kwargs.get('random_scale_range', (1., 1.)),
)
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
def transform(self, asset: Asset, **kwargs):
def get_matrix_basis(angle: float):
matrix = axis_angle_to_matrix((np.random.rand(asset.J, 3) - 0.5) * angle / 180 * np.pi * 2).astype(np.float32)
return matrix
if np.random.rand() < self.random_pose_p and asset.joints is not None:
matrix_basis = get_matrix_basis(self.random_pose_angle)
max_offset = (asset.joints.max(axis=0) - asset.joints.min(axis=0)).max()
matrix_basis[:, :3, :3] *= np.tile(np.random.uniform(low=self.random_scale_range[0], high=self.random_scale_range[1], size=(asset.J, 1, 1)), (1, 3, 3))
asset.vertices_with_pose(matrix_basis=matrix_basis, inplace=True)
@dataclass(frozen=True)
class AugmentLinear(Augment):
# apply random rotation with probability p
random_rotate_p: float
# random rotation angle(degree)
random_rotate_angle: float
# swap x with probability p
random_flip_x_p: float
# swap y with probability p
random_flip_y_p: float
# swap z with probability p
random_flip_z_p: float
# probability to pick an angle in static_rotate_x
static_rotate_x_p: float
# rotate around x axis among given angles(degrees)
static_rotate_x: List[float]
# probability to pick an angle in static_rotate_y
static_rotate_y_p: float
# rotate around y axis among given angles(degrees)
static_rotate_y: List[float]
# probability to pick an angle in static_rotate_z
static_rotate_z_p: float
# rotate around z axis among given angles(degrees)
static_rotate_z: List[float]
# apply random scaling with probability p
random_scale_p: float
# random scaling xyz axis
random_scale: Tuple[float, float]
# randomly change xyz orientation
random_transpose: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentLinear':
if kwargs.get('random_flip_x_p', 0) > 0 or kwargs.get('random_flip_y_p', 0) > 0 or kwargs.get('random_flip_z_p', 0) > 0:
print("\033[31mWARNING: random flip is enabled and is very likely to confuse ar model !\033[0m")
cls.check_keys(kwargs)
return AugmentLinear(
random_rotate_p=kwargs.get('random_rotate_p', 0.),
random_rotate_angle=kwargs.get('random_rotate_angle', 0.),
random_flip_x_p=kwargs.get('random_flip_x_p', 0.),
random_flip_y_p=kwargs.get('random_flip_y_p', 0.),
random_flip_z_p=kwargs.get('random_flip_z_p', 0.),
static_rotate_x_p=kwargs.get('static_rotate_x_p', 0.),
static_rotate_x=kwargs.get('static_rotate_x', []),
static_rotate_y_p=kwargs.get('static_rotate_y_p', 0.),
static_rotate_y=kwargs.get('static_rotate_y', []),
static_rotate_z_p=kwargs.get('static_rotate_z_p', 0.),
static_rotate_z=kwargs.get('static_rotate_z', []),
random_scale_p=kwargs.get('random_scale_p', 0.),
random_scale=kwargs.get('random_scale', [1.0, 1.0]),
random_transpose=kwargs.get('random_transpose', 0.),
)
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
def transform(self, asset: Asset, **kwargs):
trans_vertex = np.eye(4, dtype=np.float32)
r = np.eye(4, dtype=np.float32)
if np.random.rand() < self.random_rotate_p:
angle = self.random_rotate_angle
axis_angle = (np.random.rand(3) - 0.5) * angle / 180 * np.pi * 2
r = R.from_rotvec(axis_angle).as_matrix()
r = np.pad(r, ((0, 1), (0, 1)), 'constant', constant_values=0.)
r[3, 3] = 1.
if np.random.uniform(0, 1) < self.random_flip_x_p:
r @= np.array([
[-1.0, 0.0, 0.0, 0.0],
[ 0.0, 1.0, 0.0, 0.0],
[ 0.0, 0.0, 1.0, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_flip_y_p:
r @= np.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, -1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_flip_z_p:
r @= np.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, -1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_x_p:
assert len(self.static_rotate_x) > 0, "static rotation of x is enabled, but static_rotate_x is empty"
angle = np.random.choice(self.static_rotate_x) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ 1.0, 0.0, 0.0, 0.0],
[ 0.0, c, s, 0.0],
[ 0.0, -s, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_y_p:
assert len(self.static_rotate_y) > 0, "static rotation of y is enabled, but static_rotate_y is empty"
angle = np.random.choice(self.static_rotate_y) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ c, 0.0, -s, 0.0],
[ 0.0, 1.0, 0.0, 0.0],
[ s, 0.0, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_z_p:
assert len(self.static_rotate_z) > 0, "static rotation of z is enabled, but static_rotate_z is empty"
angle = np.random.choice(self.static_rotate_z) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ c, s, 0.0, 0.0],
[ -s, c, 0.0, 0.0],
[ 0.0, 0.0, 1.0, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_scale_p:
scale_x = np.random.uniform(self.random_scale[0], self.random_scale[1])
scale_y = np.random.uniform(self.random_scale[0], self.random_scale[1])
scale_z = np.random.uniform(self.random_scale[0], self.random_scale[1])
r @= np.array([
[scale_x, 0.0, 0.0, 0.0],
[0.0, scale_y, 0.0, 0.0],
[0.0, 0.0, scale_z, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_transpose:
permutations = [
(0, 1, 2), # x, y, z
(0, 2, 1), # x, z, y
(1, 0, 2), # y, x, z
(1, 2, 0), # y, z, x
(2, 0, 1), # z, x, y
(2, 1, 0), # z, y, x
]
direction_signs = [
(1, 1, 1),
(1, 1, -1),
(1, -1, 1),
(1, -1, -1),
(-1, 1, 1),
(-1, 1, -1),
(-1, -1, 1),
(-1, -1, -1),
]
perm = permutations[np.random.randint(0, 6)]
sign = direction_signs[np.random.randint(0, 8)]
m = np.zeros((4, 4))
for i in range(3):
m[i, perm[i]] = sign[i]
m[3, 3] = 1.0
r = m @ r
trans_vertex = r @ trans_vertex
# apply transform here
asset.transform(trans=trans_vertex)
@dataclass(frozen=True)
class AugmentAffine(Augment):
# final normalization cube
normalize_into: Tuple[float, float]
# randomly scale coordinates with probability p
random_scale_p: float
# scale range (lower, upper)
random_scale: Tuple[float, float]
# randomly shift coordinates with probability p
random_shift_p: float
# shift range (lower, upper)
random_shift: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentAffine':
cls.check_keys(kwargs)
return AugmentAffine(
normalize_into=kwargs.get('normalize_into', [-1.0, 1.0]),
random_scale_p=kwargs.get('random_scale_p', 0.),
random_scale=kwargs.get('random_scale', [1., 1.]),
random_shift_p=kwargs.get('random_shift_p', 0.),
random_shift=kwargs.get('random_shift', [0., 0.]),
)
def transform(self, asset: Asset, **kwargs):
if asset.vertices is None:
raise ValueError("do not have vertices")
bound_min = asset.vertices.min(axis=0)
bound_max = asset.vertices.max(axis=0)
if asset.joints is not None:
joints_bound_min = asset.joints.min(axis=0)
joints_bound_max = asset.joints.max(axis=0)
bound_min = np.minimum(bound_min, joints_bound_min)
bound_max = np.maximum(bound_max, joints_bound_max)
trans_vertex = np.eye(4, dtype=np.float32)
trans_vertex = _trans_to_m(-(bound_max + bound_min)/2) @ trans_vertex
if self.normalize_into is not None:
# scale into the cube
normalize_into = self.normalize_into
scale = np.max((bound_max - bound_min) / (normalize_into[1] - normalize_into[0]))
trans_vertex = _scale_to_m(1. / scale) @ trans_vertex
bias = (normalize_into[0] + normalize_into[1]) / 2
trans_vertex = _trans_to_m(np.array([bias, bias, bias], dtype=np.float32)) @ trans_vertex
if np.random.rand() < self.random_scale_p:
scale = _scale_to_m(np.random.uniform(self.random_scale[0], self.random_scale[1]))
trans_vertex = scale @ trans_vertex
if np.random.rand() < self.random_shift_p:
l, r = self.random_shift
shift_vals = np.array([
np.random.uniform(l, r),
np.random.uniform(l, r),
np.random.uniform(l, r),
], dtype=np.float32)
if self.normalize_into is not None:
def _apply(v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
lo, hi = self.normalize_into
pts_min = _apply(bound_min[None, :], trans_vertex)[0]
pts_max = _apply(bound_max[None, :], trans_vertex)[0]
low_allowed = lo - pts_min
high_allowed = hi - pts_max
shift_vals = np.array([
np.random.uniform(low_allowed[0], high_allowed[0]),
np.random.uniform(low_allowed[1], high_allowed[1]),
np.random.uniform(low_allowed[2], high_allowed[2]),
], dtype=np.float32)
shift = _trans_to_m(shift_vals.astype(np.float32))
trans_vertex = shift @ trans_vertex
asset.transform(trans=trans_vertex)
@dataclass(frozen=True)
class AugmentJitter(Augment):
# probability
p: float
# jitter sigma on vertices
vertex_sigma: float
# jitter clip on vertices
vertex_clip: float
# jitter sigma on normals
normal_sigma: float
# jitter clip on normals
normal_clip: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentJitter':
cls.check_keys(kwargs)
return AugmentJitter(
p=kwargs.get('p', 0.5),
vertex_sigma=kwargs.get('vertex_sigma', 0.),
vertex_clip=kwargs.get('vertex_clip', 0.),
normal_sigma=kwargs.get('normal_sigma', 0.),
normal_clip=kwargs.get('normal_clip', 0.),
)
def transform(self, asset: Asset, **kwargs):
vertex_sigma = self.vertex_sigma
vertex_clip = self.vertex_clip
normal_sigma = self.normal_sigma
normal_clip = self.normal_clip
if np.random.rand() < self.p:
scale = np.random.rand() + 1e-6
vertex_sigma *= scale
vertex_clip *= scale
scale = np.random.rand() + 1e-6
normal_sigma *= scale
normal_clip *= scale
if vertex_sigma > 0 and asset.vertices is not None:
noise = np.clip(np.random.randn(*asset.vertices.shape) * vertex_sigma, -vertex_clip, vertex_clip).astype(np.float32)
asset.vertices += noise
if normal_sigma > 0:
if asset.vertex_normals is not None:
noise = np.clip(np.random.randn(*asset.vertex_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
asset.vertex_normals += noise
if asset.face_normals is not None:
noise = np.clip(np.random.randn(*asset.face_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
asset.face_normals += noise
@dataclass(frozen=True)
class AugmentNormalize(Augment):
@classmethod
def parse(cls, **kwargs) -> 'AugmentNormalize':
cls.check_keys(kwargs)
return AugmentNormalize()
def transform(self, asset: Asset, **kwargs):
epsilon = 1e-10
if asset.vertex_normals is not None:
vertex_norms = np.linalg.norm(asset.vertex_normals, axis=1, keepdims=True)
vertex_norms = np.maximum(vertex_norms, epsilon)
asset.vertex_normals = asset.vertex_normals / vertex_norms
asset.vertex_normals = np.nan_to_num(asset.vertex_normals, nan=0., posinf=0., neginf=0.) # type: ignore
if asset.face_normals is not None:
face_norms = np.linalg.norm(asset.face_normals, axis=1, keepdims=True)
face_norms = np.maximum(face_norms, epsilon)
asset.face_normals = asset.face_normals / face_norms
asset.face_normals = np.nan_to_num(asset.face_normals, nan=0., posinf=0., neginf=0.) # type: ignore
def _trans_to_m(v: ndarray):
m = np.eye(4, dtype=np.float32)
m[0:3, 3] = v
return m
def _scale_to_m(r: ndarray|float):
m = np.zeros((4, 4), dtype=np.float32)
m[0, 0] = r
m[1, 1] = r
m[2, 2] = r
m[3, 3] = 1.
return m
def get_augments(*args) -> List[Augment]:
MAP = {
'trim': AugmentTrim,
'delete': AugmentDelete,
'drop_part': AugmentDropPart,
'collapse': AugmentCollapse,
'lbs': AugmentLBS,
'linear': AugmentLinear,
'affine': AugmentAffine,
'jitter': AugmentJitter,
'joint_perturb': AugmentJointPerturb,
'joint_discrete': AugmentJointDiscrete,
'normalize': AugmentNormalize,
}
MAP: Dict[str, type[Augment]]
augments = []
for (i, config) in enumerate(args):
__target__ = config.get('__target__')
assert __target__ is not None, f"do not find `__target__` in augment of position {i}"
c = deepcopy(config)
del c['__target__']
augments.append(MAP[__target__].parse(**c))
return augments

View file

@ -1,344 +0,0 @@
from abc import abstractmethod, ABC
from collections import defaultdict
from dataclasses import dataclass, field
from numpy import ndarray
from random import shuffle
from typing import Dict, List, Optional
import numpy as np
import requests
import os
from ..rig_package.info.asset import Asset
from ..server.spec import BPY_SERVER, bytes_to_object, object_to_bytes
from .spec import ConfigSpec
@dataclass
class LazyAsset(ABC):
"""store datapath and load upon requiring"""
path: str
cls: Optional[str]=None
@abstractmethod
def load(self) -> 'Asset':
raise NotImplementedError()
@dataclass
class BpyLazyAsset(LazyAsset):
def load(self) -> 'Asset':
from ..rig_package.parser.bpy import BpyParser
asset = BpyParser.load(filepath=self.path)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class BpyServerLazyAsset(LazyAsset):
"""workaround while bpy is working in multiple threads"""
def load(self) -> 'Asset':
try:
asset = bytes_to_object(requests.get(f"{BPY_SERVER}/load", data=object_to_bytes(self.path)).content)
if isinstance(asset, str):
raise RuntimeError(f"bpy server failed: {asset}")
assert isinstance(asset, Asset)
asset.cls = self.cls
asset.path = self.path
return asset
except Exception as e:
raise RuntimeError(f"bpy server failed: {str(e)}")
@dataclass
class NpzLazyAsset(LazyAsset):
def load(self) -> 'Asset':
d = np.load(self.path, allow_pickle=True)
asset = Asset(
vertices=d['vertices'],
faces=d['faces'],
mesh_names=d.get('mesh_names', None),
joint_names=d.get('joint_names', None),
parents=d.get('parents', None),
lengths=d.get('lengths', None),
matrix_world=d.get('matrix_world', None),
matrix_local=d.get('matrix_local', None),
armature_name=d.get('armature_name', None),
skin=d.get('skin', None),
cls=self.cls,
path=self.path
)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class UniRigLazyAsset(LazyAsset):
"""map unirig's data correctly"""
def load(self) -> 'Asset':
def bn(x):
if isinstance(x, ndarray) and x.ndim==0:
return x.item()
return x
d = np.load(self.path, allow_pickle=True)
parents = bn(d.get('parents', None))
if parents is not None:
parents = [-1 if x is None else x for x in parents]
parents = np.array(parents)
matrix_local = bn(d.get('matrix_local', None))
joints = bn(d.get('joints', None))
if matrix_local is not None and matrix_local.ndim != 3 and joints is not None:
matrix_local = np.zeros((joints.shape[0], 4, 4))
matrix_local[...] = np.eye(4)
matrix_local[:, :3, 3] = joints
asset = Asset(
vertices=d['vertices'],
faces=d['faces'],
joint_names=bn(d.get('names', None)),
parents=parents, # type: ignore
lengths=bn(d.get('lengths', None)),
matrix_world=bn(d.get('matrix_world', None)),
matrix_local=matrix_local,
armature_name=bn(d.get('armature_name', None)),
skin=bn(d.get('skin', None)),
cls=self.cls,
path=self.path
).change_dtype(float_dtype=np.float32, int_dtype=np.int32)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class Datapath(ConfigSpec):
"""handle input data paths"""
# all filepaths
filepaths: List[str]
# root to add to prefix
input_dataset_dir: str=''
# name of class
cls_name: Optional[List[str]]=None
# bias in a single class
cls_bias: Optional[List[int]]=None
# num of files in a single class
cls_length: Optional[List[int]]=None
# how many files to return when using data sampling
num_files: Optional[int]=None
# use proportion data sampling
use_prob: bool=False
# weight
cls_weight: Optional[List[float]]=None
# use bpy loader
loader: type[LazyAsset]=BpyLazyAsset
# data name
data_name: Optional[str]=None
# check if path exists
ignore_check: bool=False
#################################################################
# other vertex groups
vertex_groups: Dict[str, ndarray]=field(default_factory=dict)
# sampled vertices
sampled_vertices: Optional[ndarray]=None
# sampled normals
sampled_normals: Optional[ndarray]=None
# sampled vertex groups
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
@classmethod
def parse(cls, **kwargs) -> 'Datapath':
MAP = {
None: BpyLazyAsset,
'bpy': BpyLazyAsset,
'bpy_server': BpyServerLazyAsset,
'npz': NpzLazyAsset,
'unirig': UniRigLazyAsset,
}
input_dataset_dir = kwargs.get('input_dataset_dir', '')
num_files = kwargs.get('num_files', None)
use_prob = kwargs.get('use_prob', False)
data_name = kwargs.get('data_name', 'raw_data.npz')
data_path = kwargs.get('data_path', None)
loader_cls = MAP[kwargs.get('loader', None)]
ignore_check = kwargs.get('ignore_check', False)
if data_path is not None:
filepaths = []
if isinstance(data_path, dict):
cls_name = []
cls_bias = []
cls_length = []
cls_weight = []
for name, v in data_path.items():
assert isinstance(v, list), "items in the dict must be a list of data list paths"
for item in v:
if isinstance(item, str):
datalist_path = item
weight = 1.0
else:
datalist_path = item[0]
weight = item[1]
cls_name.append(name)
lines = [x.strip() for x in open(datalist_path, "r").readlines()]
ok_lines = []
missing = 0
for line in lines:
if ignore_check:
ok_lines.append(line)
elif os.path.exists(os.path.join(input_dataset_dir, line, data_name)):
ok_lines.append(line)
else:
missing += 1
if missing != 0:
print(f"\033[31m{datalist_path}: {missing} missing files\033[0m")
cls_bias.append(len(filepaths))
cls_length.append(len(ok_lines))
cls_weight.append(weight)
filepaths.extend(ok_lines)
else:
raise NotImplementedError()
else:
_filepaths = kwargs['filepaths']
if isinstance(_filepaths, list):
filepaths = _filepaths
cls_name = None
cls_bias = None
cls_length = None
cls_weight = None
elif isinstance(_filepaths, dict):
filepaths = []
cls_name = []
cls_bias = []
cls_length = []
cls_weight = []
for k, v in _filepaths.items():
assert isinstance(v, list), "items in the dict must be a list of paths"
cls_name.append(k)
cls_bias.append(len(filepaths))
cls_length.append(len(v))
cls_weight.append(1.0)
filepaths.extend(v)
else:
raise NotImplementedError()
if cls_weight is not None:
total = sum(cls_weight)
cls_weight = [x/total for x in cls_weight]
return Datapath(
filepaths=filepaths,
input_dataset_dir=input_dataset_dir,
cls_name=cls_name,
cls_bias=cls_bias,
cls_length=cls_length,
num_files=num_files,
use_prob=use_prob,
cls_weight=cls_weight,
loader=loader_cls,
data_name=data_name,
ignore_check=ignore_check,
)
def make(self, path: str, cls: str|None) -> LazyAsset:
return self.loader(path=path, cls=cls)
def __getitem__(self, index: int) -> LazyAsset:
if self.use_prob and self.cls_weight is not None:
if self.cls_bias is None:
raise ValueError("do not have cls_bias")
if self.cls_length is None:
raise ValueError("do not have cls_length")
if not hasattr(self, "perms"):
self.perms = []
self.current_bias = []
for i in range(len(self.cls_weight)):
self.perms.append([x for x in range(self.cls_length[i])])
self.current_bias.append(0)
idx = np.random.choice(len(self.cls_weight), p=self.cls_weight)
i = self.perms[idx][self.current_bias[idx]]
self.current_bias[idx] += 1
if self.current_bias[idx] >= self.cls_length[idx]:
shuffle(self.perms[idx])
self.current_bias[idx] = 0
if self.cls_name is None:
name = None
else:
name = self.cls_name[idx]
path = os.path.join(self.input_dataset_dir, self.filepaths[i+self.cls_bias[idx]])
if self.data_name is not None:
path = os.path.join(path, self.data_name)
return self.make(path=path, cls=name)
else:
if self.cls_name is None or self.cls_bias is None or self.cls_length is None:
name = None
else:
name = None
for i in range(len(self.cls_bias)):
start = self.cls_bias[i]
end = start + self.cls_length[i]
if start <= index < end:
name = self.cls_name[i]
break
path = os.path.join(self.input_dataset_dir, self.filepaths[index])
if self.data_name is not None:
path = os.path.join(path, self.data_name)
return self.make(path=path, cls=name)
def get_data(self) -> List[LazyAsset]:
return [self[i] for i in range(len(self))]
def split_by_cls(self) -> Dict[str|None, 'Datapath']:
res: Dict[str|None, Datapath] = {}
if self.cls_name is None:
res[None] = self
return res
if self.cls_bias is None:
raise ValueError("do not have cls_bias")
if self.cls_length is None:
raise ValueError("do not have cls_length")
d_filepaths = defaultdict(list)
d_length = defaultdict(int)
d_weight = defaultdict(list)
for (i, cls) in enumerate(self.cls_name):
s = slice(self.cls_bias[i], self.cls_bias[i]+self.cls_length[i])
d_filepaths[cls].extend(self.filepaths[s].copy())
d_length[cls] += self.cls_length[i]
if self.cls_weight is not None:
d_weight[cls].append(self.cls_weight[i])
for cls in d_filepaths:
cls_weight = None if self.cls_weight is None else d_weight[cls]
if cls_weight is not None:
total = sum(cls_weight)
cls_weight = [x/total for x in cls_weight]
res[cls] = Datapath(
filepaths=d_filepaths[cls],
input_dataset_dir=self.input_dataset_dir,
cls_name=[cls],
cls_bias=[0],
cls_length=[len(d_filepaths[cls])],
num_files=self.num_files,
use_prob=self.use_prob,
cls_weight=cls_weight,
loader=self.loader,
data_name=self.data_name,
)
return res
def __len__(self):
if self.use_prob:
assert self.num_files is not None, 'num_files is not specified'
return self.num_files
return len(self.filepaths)

View file

@ -1,319 +0,0 @@
from copy import deepcopy
from dataclasses import dataclass
from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS
from numpy import ndarray
from torch import Tensor
from torch.utils import data
from torch.utils.data import DataLoader, Dataset
from typing import Dict, List, Tuple, Callable, Optional
import os
import lightning.pytorch as pl
import numpy as np
import torch
from .datapath import Datapath, LazyAsset
from .spec import ConfigSpec
from .transform import Transform
from ..model.spec import ModelInput
from ..rig_package.info.asset import Asset
from ..tokenizer.spec import Tokenizer, TokenizeInput
@dataclass
class DatasetConfig(ConfigSpec):
shuffle: bool
batch_size: int
num_workers: int
datapath: Datapath
pin_memory: bool=True
persistent_workers: bool=True
@classmethod
def parse(cls, **kwargs) -> 'DatasetConfig':
cls.check_keys(kwargs)
return DatasetConfig(
shuffle=kwargs.get('shuffle', False),
batch_size=kwargs.get('batch_size', 1),
num_workers=kwargs.get('num_workers', 1),
pin_memory=kwargs.get('pin_memory', True),
persistent_workers=kwargs.get('persistent_workers', True),
datapath=Datapath.parse(**kwargs.get('datapath')),
)
def split_by_cls(self) -> Dict[str|None, 'DatasetConfig']:
res: Dict[str|None, DatasetConfig] = {}
datapath_dict = self.datapath.split_by_cls()
for cls, v in datapath_dict.items():
res[cls] = DatasetConfig(
shuffle=self.shuffle,
batch_size=self.batch_size,
num_workers=self.num_workers,
datapath=v,
pin_memory=self.pin_memory,
persistent_workers=self.persistent_workers,
)
return res
class RigDatasetModule(pl.LightningDataModule):
def __init__(
self,
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
train_dataset_config: Optional[DatasetConfig]=None,
validate_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
predict_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
train_transform: Optional[Transform]=None,
validate_transform: Optional[Transform]=None,
predict_transform: Optional[Transform]=None,
tokenizer: Optional[Tokenizer]=None,
debug: bool=False,
):
super().__init__()
self.process_fn = process_fn
self.train_dataset_config = train_dataset_config
self.validate_dataset_config = validate_dataset_config
self.predict_dataset_config = predict_dataset_config
self.train_transform = train_transform
self.validate_transform = validate_transform
self.predict_transform = predict_transform
self.tokenizer = tokenizer
self.debug = debug
if debug:
print("\033[31mWARNING: debug mode, dataloader will be extremely slow !!!\033[0m")
# build train datapath
if self.train_dataset_config is not None:
self.train_datapath = self.train_dataset_config.datapath
else:
self.train_datapath = None
# build validate datapath
if self.validate_dataset_config is not None:
self.validate_datapath = {
cls: self.validate_dataset_config[cls].datapath
for cls in self.validate_dataset_config
}
else:
self.validate_datapath = None
# build predict datapath
if self.predict_dataset_config is not None:
self.predict_datapath = {
cls: self.predict_dataset_config[cls].datapath
for cls in self.predict_dataset_config
}
else:
self.predict_datapath = None
self.tokenizer = tokenizer
def prepare_data(self):
pass
def train_dataloader(self) -> TRAIN_DATALOADERS:
if self.train_dataset_config is None:
raise ValueError("do not have train_dataset_config")
if self.train_transform is None:
raise ValueError("do not have train_transform")
if self.train_datapath is not None:
self._train_ds = RigDataset(
process_fn=self.process_fn,
data=self.train_datapath.get_data(),
name="train",
tokenizer=self.tokenizer,
transform=self.train_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._train_ds,
config=self.train_dataset_config,
is_train=True,
drop_last=False,
)
def val_dataloader(self) -> EVAL_DATALOADERS:
if self.validate_dataset_config is None:
raise ValueError("do not have validate_dataset_config")
if self.validate_transform is None:
raise ValueError("do not have validate_transform")
if self.validate_datapath is not None:
self._validation_ds = {}
for cls in self.validate_datapath:
self._validation_ds[cls] = RigDataset(
process_fn=self.process_fn,
data=self.validate_datapath[cls].get_data(),
name=f"validate-{cls}",
tokenizer=self.tokenizer,
transform=self.validate_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._validation_ds,
config=self.validate_dataset_config,
is_train=False,
drop_last=False,
)
def predict_dataloader(self):
if self.predict_dataset_config is None:
raise ValueError("do not have predict_dataset_config")
if self.predict_transform is None:
raise ValueError("do not have predict_transform")
if self.predict_datapath is not None:
self._predict_ds = {}
for cls in self.predict_datapath:
self._predict_ds[cls] = RigDataset(
process_fn=self.process_fn,
data=self.predict_datapath[cls].get_data(),
name=f"predict-{cls}",
tokenizer=self.tokenizer,
transform=self.predict_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._predict_ds,
config=self.predict_dataset_config,
is_train=False,
drop_last=False,
)
def _create_dataloader(
self,
dataset: Dataset|Dict[str, Dataset],
config: DatasetConfig|Dict[str|None, DatasetConfig],
is_train: bool,
**kwargs,
) -> DataLoader|Dict[str, DataLoader]:
def create_single_dataloader(dataset, config: DatasetConfig, **kwargs):
return DataLoader(
dataset,
batch_size=config.batch_size,
shuffle=config.shuffle,
num_workers=config.num_workers,
pin_memory=config.pin_memory,
persistent_workers=config.persistent_workers,
collate_fn=dataset.collate_fn,
**kwargs,
)
if isinstance(dataset, Dict):
assert isinstance(config, dict)
return {k: create_single_dataloader(v, config[k], **kwargs) for k, v in dataset.items()}
else:
assert isinstance(config, DatasetConfig)
return create_single_dataloader(dataset, config, **kwargs)
class RigDataset(Dataset):
def __init__(
self,
data: List[LazyAsset],
transform: Transform,
name: Optional[str]=None,
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
tokenizer: Optional[Tokenizer]=None,
debug: bool=False,
) -> None:
super().__init__()
self.data = data
self.name = name
self.process_fn = process_fn
self.tokenizer = tokenizer
self.transform = transform
self.debug = debug
if not debug:
assert self.process_fn is not None, 'missing data processing function'
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, idx) -> ModelInput:
lazy_asset = self.data[idx]
asset = lazy_asset.load()
self.transform.apply(asset=asset)
if self.tokenizer is not None and asset.parents is not None:
x = TokenizeInput(
joints=asset.joints,
parents=asset.parents,
cls=asset.cls,
joint_names=asset.joint_names,
)
tokens = self.tokenizer.tokenize(input=x)
else:
tokens = None
return ModelInput(asset=asset, tokens=tokens)
def _collate_fn_debug(self, batch):
return batch
def _collate_fn(self, batch):
processed_batch = self.process_fn(batch) # type: ignore
processed_batch: List[Dict]
tensors_stack = {}
tensors_cat = {}
non_tensors = {}
vis = {}
def check(x):
assert x not in vis, f"multiple keys found: {x}"
vis[x] = True
for k, v in processed_batch[0].items():
if k == "cat":
assert isinstance(v, dict)
for k1 in v.keys():
check(k1)
tensors_cat[k1] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i]['cat'][k1]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
elif isinstance(v1, Tensor):
v1 = v1
else:
raise ValueError(f"cannot concatenate non-tensor type of key {k1}, type: {type(v1)}")
tensors_cat[k1].append(v1)
elif k == "non":
assert isinstance(v, dict)
for k1 in v.keys():
check(k1)
non_tensors[k1] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i]['non'][k1]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
non_tensors[k1].append(v1)
else:
check(k)
tensors_stack[k] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i][k]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
elif isinstance(v1, Tensor):
v1 = v1
else:
raise ValueError(f"cannot stack type of key {k}, type: {type(v1)}")
tensors_stack[k].append(v1)
collated_stack = {k: torch.stack(v) for k, v in tensors_stack.items()}
collated_cat = {k: torch.concat(v, dim=1) for k, v in tensors_cat.items()}
collated_batch = {
**collated_stack,
**collated_cat,
**non_tensors,
}
return collated_batch
def collate_fn(self, batch):
if self.debug:
return self._collate_fn_debug(batch)
return self._collate_fn(batch)

View file

@ -1,132 +0,0 @@
from collections import defaultdict
from dataclasses import dataclass
from numpy import ndarray
from omegaconf import OmegaConf
from typing import Dict, List, Tuple, Optional
from .spec import ConfigSpec
@dataclass
class Order(ConfigSpec):
# {part_name: [bone_name_1, bone_name_2, ...]}
parts: Dict[str, Dict[str, List[str]]]
# parts of bones to be arranged in [part_name_1, part_name_2, ...]
parts_order: Dict[str, List[str]]
# {skeleton_name: path}
skeleton_path: Optional[Dict[str, str]]=None
sort_by_xyz: bool=False
@classmethod
def parse(cls, **kwargs) -> 'Order':
cls.check_keys(kwargs)
skeleton_path = kwargs.get('skeleton_path', None)
if skeleton_path is not None:
parts = {}
parts_order = {}
for (cls, path) in skeleton_path.items():
assert cls not in parts, 'cls conflicts'
d = OmegaConf.load(path)
parts[cls] = d.parts
parts_order[cls] = d.parts_order
else:
parts = kwargs.get('parts')
parts_order = kwargs.get('parts_order')
assert parts is not None
assert parts_order is not None
return Order(
skeleton_path=skeleton_path,
parts=parts,
parts_order=parts_order,
sort_by_xyz=kwargs.get('sort_by_xyz', False),
)
def part_exists(self, cls: str, part: str, names: List[str]) -> bool:
'''
Check if part exists.
'''
if part not in self.parts[cls]:
return False
for name in self.parts[cls][part]:
if name not in names:
return False
return True
def make_names(self, cls: str|None, parts: List[str|None], num_bones: int) -> List[str]:
'''
Get names for specified cls.
'''
names = []
for part in parts:
if part is None: # spring
continue
if cls in self.parts and part in self.parts[cls]:
names.extend(self.parts[cls][part])
assert len(names) <= num_bones, "number of bones in required skeleton is more than existing bones"
for i in range(len(names), num_bones):
names.append(f"bone_{i}")
return names
def arrange_names(self, cls: str|None, names: List[str], parents: List[int], joints: Optional[ndarray]=None) -> Tuple[List[str], Dict[int, str|None]]:
'''
Arrange names according to required parts order.
'''
def sort_by_xyz(joints):
return sorted(joints, key=lambda joint: (joint[1][2], joint[1][0], joint[1][1]))
if self.sort_by_xyz:
assert joints is not None
new_names = []
root = -1
son = defaultdict(list)
not_root = {}
for (i, p) in enumerate(parents):
if p != -1:
son[p].append(i)
not_root[i] = True
for i in range(len(parents)):
if not_root.get(i, False) == False:
root = i
break
Q = [root]
while Q:
u = Q.pop(0)
new_names.append(names[u])
wait = []
for v in son[u]:
wait.append((v, joints[v]))
wait_sorted = sort_by_xyz(wait)
new_wait = [v for v, _ in wait_sorted]
Q = new_wait + Q
return new_names, {}
if cls not in self.parts_order:
return names, {0: None} # add a spring token
vis = defaultdict(bool)
name_to_id = {name: i for (i, name) in enumerate(names)}
new_names = []
parts_bias = {}
for part in self.parts_order[cls]:
if self.part_exists(cls=cls, part=part, names=names):
for name in self.parts[cls][part]:
vis[name] = True
flag = False
for name in self.parts[cls][part]:
pid = parents[name_to_id[name]]
if pid==-1:
continue
if not vis[names[pid]]:
flag = True
break
if flag: # incorrect parts order and should immediately add a spring token
break
parts_bias[len(new_names)] = part
new_names.extend(self.parts[cls][part])
parts_bias[len(new_names)] = None # add a spring token
for name in names:
if name not in new_names:
new_names.append(name)
return new_names, parts_bias

View file

@ -1,189 +0,0 @@
from dataclasses import dataclass
from abc import ABC, abstractmethod
from numpy import ndarray
from scipy.spatial import cKDTree # type: ignore
from typing import Dict, Optional
import numpy as np
import random
from ..rig_package.info.asset import Asset
from ..rig_package.utils import sample_vertex_groups
from .spec import ConfigSpec
@dataclass
class SamplerResult():
sampled_vertices: Optional[ndarray]=None
sampled_normals: Optional[ndarray]=None
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
# number of sampled skin
skin_samples: Optional[int]=None
class Sampler(ABC):
@abstractmethod
def sample(
self,
asset: Asset,
) -> SamplerResult:
'''
Return sampled vertices, sampled normals and vertex groups.
'''
pass
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'Sampler':
pass
@dataclass
class SamplerMix(Sampler, ConfigSpec):
num_samples: int
num_vertex_samples: int
num_skin_samples: Optional[int]=None
replace: bool=True
all_skeleton: Optional[bool]=None
max_distance: float=0.1
rate_distance: float=0.1
@classmethod
def parse(cls, **kwargs) -> 'SamplerMix':
cls.check_keys(kwargs)
return SamplerMix(
num_samples=kwargs.get('num_samples', 0),
num_vertex_samples=kwargs.get('num_vertex_samples', 0),
num_skin_samples=kwargs.get('num_skin_samples', None),
replace=kwargs.get('replace', True),
all_skeleton=kwargs.get('all_skeleton', None),
max_distance=kwargs.get('max_distance', 0.1),
rate_distance=kwargs.get('rate_distance', 0.1),
)
def sample_on_skin(
self,
skin: ndarray,
vertices: ndarray,
faces: ndarray,
):
face_has_skin = np.any(skin[faces] > 0, axis=-1)
if face_has_skin.sum() == 0:
face_has_skin = np.ones_like(face_has_skin)
elif self.max_distance < 1e-5:
return face_has_skin
else:
# sample near points
p = np.unique(faces[face_has_skin].reshape(-1))
tree = cKDTree(vertices[p])
dis, _ = tree.query(vertices, k=1)
dis_skin = np.sqrt(((np.max(vertices[p], axis=0) - np.min(vertices[p], axis=0))**2).sum())
mask_face_near = np.any(dis[faces] < min(self.max_distance, dis_skin * self.rate_distance), axis=-1)
face_has_skin |= mask_face_near
return face_has_skin
def sample(
self,
asset: Asset,
) -> SamplerResult:
if asset.vertices is None:
raise ValueError("do not have vertices")
if asset.faces is None:
raise ValueError("do not have faces")
vertex_groups = []
mapping = {}
tot = 0
for k, v in asset.vertex_groups.items():
if v.ndim == 1:
v = v[:, None]
elif v.ndim != 2:
raise ValueError(f"ndim of key {k} is {v.ndim}")
s = tot
e = tot + v.shape[1]
mapping[k] = slice(s,e)
vertex_groups.append(v)
if len(vertex_groups) > 0:
vertex_groups = np.concatenate(vertex_groups, axis=1)
else:
vertex_groups = None
final_sampled_vertices, final_sampled_normals, sampled_vertex_groups = sample_vertex_groups(
vertices=asset.vertices,
faces=asset.faces,
num_samples=self.num_samples,
vertex_normals=asset.vertex_normals,
face_normals=asset.face_normals,
vertex_groups=vertex_groups,
face_mask=None,
shuffle=True,
same=True,
)
if vertex_groups is not None:
final_sampled_vertices = final_sampled_vertices[:, 0]
if final_sampled_normals is not None:
final_sampled_normals = final_sampled_normals[:, 0]
final_sampled_vertex_groups = {}
if sampled_vertex_groups is not None:
for k, s in mapping.items():
final_sampled_vertex_groups[k] = sampled_vertex_groups[:, s] # (N, k)
if vertex_groups is not None and self.num_skin_samples is not None:
dense_vertices = []
dense_normals = []
dense_skin = []
if 'skin' not in mapping:
raise ValueError("do not have skin")
if self.all_skeleton:
dense_indices = [i for i in range(asset.J)]
else:
dense_indices = [random.randint(0, asset.J-1)]
for indice in dense_indices:
_s = asset.vertex_groups['skin'][:, indice]
face_has_skin = self.sample_on_skin(
skin=_s,
vertices=asset.vertices,
faces=asset.faces,
)
sampled_vertices, sampled_normals, sampled_skin = sample_vertex_groups(
vertices=asset.vertices,
faces=asset.faces,
vertex_normals=asset.vertex_normals,
face_normals=asset.face_normals,
vertex_groups=_s,
num_samples=self.num_skin_samples,
num_vertex_samples=self.num_vertex_samples,
face_mask=face_has_skin,
shuffle=True,
same=True,
)
assert sampled_skin is not None
assert sampled_skin.ndim == 2
dense_vertices.append(sampled_vertices[:, 0])
if sampled_normals is not None:
dense_normals.append(sampled_normals[:, 0])
dense_skin.append(sampled_skin[:, 0])
dense_vertices = np.stack(dense_vertices, axis=0) # (J, m, 3)
if len(dense_normals) > 0:
dense_normals = np.stack(dense_normals, axis=0) # (J, m, 3)
else:
dense_normals = None
dense_skin = np.stack(dense_skin, axis=0) # (J, m, 1)
final_sampled_vertex_groups['skin'] = final_sampled_vertex_groups['skin'][:, dense_indices]
if asset.meta is None:
asset.meta = {}
asset.meta['dense_vertices'] = dense_vertices
asset.meta['dense_normals'] = dense_normals
asset.meta['dense_skin'] = dense_skin
asset.meta['dense_indices'] = dense_indices
return SamplerResult(
sampled_vertices=final_sampled_vertices,
sampled_normals=final_sampled_normals if final_sampled_normals is not None else None,
sampled_vertex_groups=final_sampled_vertex_groups,
skin_samples=self.num_skin_samples,
)
def get_sampler(**kwargs) -> Sampler:
__target__ = kwargs.get('__target__')
assert __target__ is not None
del kwargs['__target__']
if __target__ == 'mix':
sampler = SamplerMix.parse(**kwargs)
else:
raise ValueError(f"sampler method {__target__} not supported")
return sampler

View file

@ -1,16 +0,0 @@
from abc import ABC, abstractmethod
from dataclasses import fields
class ConfigSpec(ABC):
@classmethod
def check_keys(cls, config, expect=None):
if expect is None:
expect = [field.name for field in fields(cls)] # type: ignore
for key in config.keys():
if key not in expect:
raise ValueError(f"expect names {expect} in {cls.__name__}, found {key}")
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'ConfigSpec':
raise NotImplementedError()

View file

@ -1,70 +0,0 @@
from dataclasses import dataclass
from typing import List, Optional
from ..rig_package.info.asset import Asset
from .augment import Augment, get_augments
from .order import Order
from .sampler import Sampler, get_sampler
from .spec import ConfigSpec
from .vertex_group import VertexGroup, get_vertex_groups
@dataclass
class Transform(ConfigSpec):
order: Optional[Order]=None
vertex_groups: Optional[List[VertexGroup]]=None
augments: Optional[List[Augment]]=None
sampler: Optional[Sampler]=None
@classmethod
def parse(cls, **kwargs) -> 'Transform':
cls.check_keys(kwargs)
order_config = kwargs.get('order')
vertex_groups_config = kwargs.get('vertex_groups')
augments_config = kwargs.get('augments')
sampler_config = kwargs.get('sampler')
d = {}
if order_config is not None:
d['order'] = Order.parse(**order_config)
if vertex_groups_config is not None:
d['vertex_groups'] = get_vertex_groups(*vertex_groups_config)
if augments_config is not None:
d['augments'] = get_augments(*augments_config)
if sampler_config is not None:
d['sampler'] = get_sampler(**sampler_config)
return Transform(**d)
def apply(self, asset: Asset, **kwargs):
# 1. arrange bones
if self.order is not None:
if asset.joint_names is not None and asset.parents is not None:
new_names, _ = self.order.arrange_names(cls=asset.cls, names=asset.joint_names, parents=asset.parents.tolist())
asset.set_order(new_orders=new_names) # type: ignore
# 2. collapse must perform first
if self.augments is not None:
kwargs = {}
for augment in self.augments:
augment.transform(asset=asset, **kwargs)
# 3. get vertex groups
if self.vertex_groups is not None:
d = {}
for v in self.vertex_groups:
d.update(v.get_vertex_group(asset=asset))
asset.vertex_groups = d
else:
asset.vertex_groups = {}
# 4. sample
if self.sampler is not None:
res = self.sampler.sample(asset=asset)
asset.sampled_vertices = res.sampled_vertices
asset.sampled_normals = res.sampled_normals
asset.sampled_vertex_groups = res.sampled_vertex_groups
asset.skin_samples = res.skin_samples

View file

@ -1,257 +0,0 @@
from abc import ABC, abstractmethod
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from numpy import ndarray
from scipy.spatial import cKDTree # type: ignore
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path, connected_components
from typing import Dict, List, Optional, Literal
import numpy as np
from ..rig_package.info.asset import Asset
@dataclass(frozen=True)
class VertexGroup(ABC):
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'VertexGroup':
pass
@abstractmethod
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
pass
@dataclass(frozen=True)
class VertexGroupSkin(VertexGroup):
"""capture skin"""
normalize: bool=True
@classmethod
def parse(cls, **kwargs) -> 'VertexGroupSkin':
return VertexGroupSkin(normalize=kwargs.get('normalize', True))
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
if asset.skin is None:
raise ValueError("do not have skin")
if self.normalize:
asset.normalize_skin()
return {'skin': asset.skin.copy()}
@dataclass(frozen=True)
class VertexGroupVoxelSkin(VertexGroup):
"""capture voxel skin"""
grid: int
alpha: float
link_dis: float
grid_query: int
vertex_query: int
grid_weight: float
mode: Literal['square', 'exp']
@classmethod
def parse(cls, **kwargs) -> 'VertexGroupVoxelSkin':
return VertexGroupVoxelSkin(
grid=kwargs.get('grid', 64),
alpha=kwargs.get('alpha', 0.5),
link_dis=kwargs.get('link_dis', 0.00001),
grid_query=kwargs.get('grid_query', 27),
vertex_query=kwargs.get('vertex_query', 27),
grid_weight=kwargs.get('grid_weight', 3.0),
mode=kwargs.get('mode', 'square'),
)
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
if asset.vertices is None:
raise ValueError("do not have vertices")
if asset.faces is None:
raise ValueError("do not have faces")
if asset.joints is None:
raise ValueError("do not have joints")
# normalize into [-1, 1] first
min_vals = np.min(asset.vertices, axis=0)
max_vals = np.max(asset.vertices, axis=0)
center = (min_vals + max_vals) / 2
scale = np.max(max_vals - min_vals) / 2
normalized_vertices = (asset.vertices - center) / scale
normalized_joints = (asset.joints - center) / scale
grid_coords = asset.voxel().coords
skin = voxel_skin(
grid=self.grid,
grid_coords=grid_coords,
joints=normalized_joints,
vertices=normalized_vertices,
faces=asset.faces,
alpha=self.alpha,
link_dis=self.link_dis,
grid_query=self.grid_query,
vertex_query=self.vertex_query,
grid_weight=self.grid_weight,
mode=self.mode,
)
skin = np.nan_to_num(skin, nan=0., posinf=0., neginf=0.)
return {'voxel_skin': skin,}
def voxel_skin(
grid: int,
grid_coords: ndarray, # (M, 3)
joints: ndarray, # (J, 3)
vertices: ndarray, # (N, 3)
faces: ndarray, # (F, 3)
alpha: float=0.5,
link_dis: float=0.00001,
grid_query: int=27,
vertex_query: int=27,
grid_weight: float=3.0,
voxel_size: Optional[float]=None,
mode: str='square',
parents: Optional[ndarray]=None,
):
# modified from https://dl.acm.org/doi/pdf/10.1145/2485895.2485919
assert mode in ['square', 'exp']
J = joints.shape[0]
M = grid_coords.shape[0]
N = vertices.shape[0]
if voxel_size is None:
_range = 2/grid*1.74
else:
_range = voxel_size*1.74
grid_tree = cKDTree(grid_coords)
vertex_tree = cKDTree(vertices)
if parents is not None:
son = defaultdict(list)
for i, p in enumerate(parents):
if i == -1:
continue
son[p].append(i)
divide_joints = []
joints_map = []
for u in range(len(parents)):
if len(son[u]) != 1:
divide_joints.append(joints[u])
joints_map.append(u)
else:
pu = joints[u]
pv = joints[son[u][0]]
seg = 10
for i in range(seg+1):
p = (pu*i + pv*(seg-i)) / seg
divide_joints.append(p)
joints_map.append(u)
divide_joints = np.stack(divide_joints)
joints_map = np.array(joints_map)
else:
divide_joints = joints
joints_map = np.arange(joints.shape[0])
joint_tree = cKDTree(divide_joints)
# make combined vertices
# 0 ~ N-1: mesh vertices
# N ~ N+M-1: grid vertices
combined_vertices = np.concatenate([vertices, grid_coords], axis=0)
# link adjacent grids
dist, idx = grid_tree.query(grid_coords, grid_query) # 3*3*3
dist = dist[:, 1:]
idx = idx[:, 1:]
mask = (0 < dist) & (dist < _range)
source_grid2grid = np.repeat(np.arange(M), grid_query-1)[mask.ravel()] + N
to_grid2grid = idx[mask] + N
weight_grid2grid = dist[mask] * grid_weight
# link very close vertices
dist, idx = vertex_tree.query(vertices, 4)
dist = dist[:, 1:]
idx = idx[:, 1:]
mask = (0 < dist) & (dist < link_dis)
source_close = np.repeat(np.arange(N), 3)[mask.ravel()]
to_close = idx[mask]
weight_close = dist[mask]
# link grids to mesh vertices
dist, idx = vertex_tree.query(grid_coords, vertex_query)
mask = (0 < dist) & (dist < _range) # sqrt(3)
source_grid2vertex = np.repeat(np.arange(M), vertex_query)[mask.ravel()] + N
to_grid2vertex = idx[mask]
weight_grid2vertex = dist[mask]
# build combined vertices tree
combined_tree = cKDTree(combined_vertices)
# link bones to the neartest vertices
_, joint_indices = combined_tree.query(divide_joints)
# build graph
source_vertex2vertex = np.concatenate([faces[:, 0], faces[:, 1], faces[:, 2]], axis=0)
to_vertex2vertex = np.concatenate([faces[:, 1], faces[:, 2], faces[:, 0]], axis=0)
weight_vertex2vertex = np.sqrt(((vertices[source_vertex2vertex] - vertices[to_vertex2vertex])**2).sum(axis=-1))
graph = csr_matrix(
(np.concatenate([weight_close, weight_vertex2vertex, weight_grid2grid, weight_grid2vertex]),
(
np.concatenate([source_close, source_vertex2vertex, source_grid2grid, source_grid2vertex], axis=0),
np.concatenate([to_close, to_vertex2vertex, to_grid2grid, to_grid2vertex], axis=0)),
),
shape=(N+M, N+M),
)
# get shortest path (J, N+M)
dist_matrix = shortest_path(graph, method='D', directed=False, indices=joint_indices)
# (sum_J, N)
dis_vertex2bone = dist_matrix[:, :N]
unreachable = np.isinf(dis_vertex2bone).all(axis=0)
k = min(J, 3)
dist, idx = joint_tree.query(vertices[unreachable], k)
# make sure at least one value in dis is not inf
unreachable_indices = np.where(unreachable)[0]
row_indices = idx
col_indices = np.repeat(unreachable_indices, k).reshape(-1, k)
dis_vertex2bone[row_indices, col_indices] = dist
finite_vals = dis_vertex2bone[np.isfinite(dis_vertex2bone)]
max_dis = np.max(finite_vals)
dis_vertex2bone = np.nan_to_num(dis_vertex2bone, nan=max_dis, posinf=max_dis, neginf=max_dis)
dis_vertex2bone = np.maximum(dis_vertex2bone, 1e-6)
# turn dis2bone to dis2vertex
dis_vertex2joint = np.full((joints.shape[0], vertices.shape[0]), max_dis)
for i in range(len(dis_vertex2bone)):
dis_vertex2joint[joints_map[i]] = np.minimum(dis_vertex2bone[i], dis_vertex2joint[joints_map[i]])
# (J, N)
if mode == 'exp':
skin = np.exp(-dis_vertex2joint / max_dis * 20.0)
elif mode == 'square':
skin = (1./((1-alpha)*dis_vertex2joint + alpha*dis_vertex2joint**2))**2
else:
assert False, f'invalid mode: {mode}'
skin = skin / skin.sum(axis=0)
# (N, J)
skin = skin.transpose()
return skin
def get_vertex_groups(*args) -> List[VertexGroup]:
vertex_groups = []
MAP = {
'skin': VertexGroupSkin,
'voxel_skin': VertexGroupVoxelSkin,
}
MAP: Dict[str, type[VertexGroup]]
for (i, c) in enumerate(args):
__target__ = c.get('__target__')
assert __target__ is not None, f"do not find `__target__` in config of vertex_groups of position {i}"
assert __target__ in MAP, f"expect: [{','.join(MAP.keys())}], found: {__target__}"
c = deepcopy(c)
del c['__target__']
vertex_groups.append(MAP[__target__].parse(**c))
return vertex_groups

View file

@ -1,4 +1,4 @@
{
"version": "2.1.2",
"message": "Fixed Desktop App on Linux - ComfyUI: Added Enums - Wireframe in Mesh Previewer"
"version": "1.4.0",
"message": "Added Auto Rig in Mesh Editor using Skintokens"
}

View file

@ -13,65 +13,56 @@ Automatically unwrap your mesh into a clean UV atlas — no manual seam painting
The result panel also reports metrics (chart count, distortion, etc.) so you can compare before committing.
## The core trade-off
Almost every parameter trades between two competing goals:
- **Fewer seams** — cleaner-looking texturing, but the flattened charts *stretch* (distortion), so painted detail looks squashed in places.
- **Less distortion** — every part flattens faithfully, but the surface is cut into *more charts*, so there are more seams to hide.
Reach for the segmentation and refinement settings below when you need to push one way or the other.
## Parameters
### Segmentation
Controls how the surface is cut into charts before unwrapping.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Normal-cone cap** | 50° | Maximum angular spread of face normals allowed within one chart. **Raise it** for fewer, larger charts with fewer seams — good for smooth organic surfaces, but expect more stretch. **Lower it** for more, smaller charts that flatten with very little distortion, at the cost of more seams. Lower this first if the texture looks stretched. |
| **Sharp-edge weight** | 0.35 | How strongly sharp edges attract seams. **Raise it** to snap seams onto hard creases so they hide where the eye already expects an edge — ideal for hard-surface / mechanical models. **Lower it** to place seams purely by distortion, ignoring creases — better for organic shapes with no real edges. |
| **Fold cap** | 88° | Dihedral fold angle that *forces* a seam: any edge bending more than this is always cut. **Lower it** to add more forced cuts, which stops charts from folding over themselves on crumpled or self-touching geometry. **Raise it** for fewer forced cuts on clean meshes. Lower it if charts overlap in the preview. |
| **Min faces / chart** | 20 | Charts with fewer faces than this are dissolved into their neighbours. **Raise it** to sweep away tiny sliver charts for a tidier atlas (a small chart merged into a big one may pick up some distortion). **Lower it** to preserve small detail charts as their own islands. |
| **Min area fraction** | 0.004 | Same idea as *Min faces*, but measured by area — the minimum chart area as a fraction of the total surface. **Raise it** to aggressively cull small charts; **lower it** to keep them. Use it to kill slivers that survive the face-count test. |
| **Normal-cone cap** | 50° | Maximum angular spread of face normals within one chart. Higher = fewer, larger, more distorted charts. |
| **Sharp-edge weight** | 0.35 | How strongly sharp edges attract seams. Higher pushes seams onto creases. |
| **Fold cap** | 88° | Dihedral fold angle that forces a seam. Edges that bend more than this are always cut. |
| **Min faces / chart** | 20 | Charts with fewer faces than this are dissolved into their neighbours. |
| **Min area fraction** | 0.004 | Minimum chart area as a fraction of the total surface area. Kills tiny slivers. |
### Refinement
An optional pass that merges small charts back together when merging doesn't add too much distortion.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Validated merge pass** | On | Runs an LSCM-validated chart merge. **On** gives fewer charts and a tidier atlas but is slower. **Turn it off** for a faster unwrap, or when you deliberately want many small, low-distortion charts. |
| **Merge below faces** | 80 | Charts smaller than this face count are candidates for merging. **Raise it** to merge more aggressively (fewer charts, but a bit more distortion). **Lower it** so only the very smallest charts are absorbed. *(Only when the merge pass is on.)* |
| **Merge distortion cap** | 1.32 | The most angle-distortion a merge is allowed to introduce — a merge is only accepted if it stays under this ratio. **Raise it** to tolerate more stretch in exchange for fewer seams. **Lower it** to keep distortion tight and leave more charts. Lower it if merged areas look stretched. *(Only when the merge pass is on.)* |
| **Validated merge pass** | On | Runs an LSCM-validated chart merge. Turn off for a faster unwrap that produces more charts. |
| **Merge below faces** | 80 | Charts smaller than this face count are candidates for merging. *(Only when the merge pass is on.)* |
| **Merge distortion cap** | 1.32 | Maximum angle-distortion ratio a merge is allowed to introduce. *(Only when the merge pass is on.)* |
### Parameterization
How each chart is flattened into 2D.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Method** | Auto | Flattening algorithm. **Auto** picks a suitable method per chart (recommended). **LSCM** is angle-preserving and fast, a solid default, but can stretch *areas*. **ARAP** (as-rigid-as-possible) balances angle and area for the least visible stretch, but is slower. **Planar** is a flat projection — only use it for near-flat charts (panels, decals). Switch to ARAP if LSCM shows area stretch. |
| **ARAP iterations** | 4 | Number of As-Rigid-As-Possible relaxation passes. **Raise it** to reduce distortion further (with diminishing returns and more time). **Lower it** for speed. **0** disables ARAP entirely (LSCM / planar only). |
| **Method** | Auto | Flattening algorithm: **Auto**, **LSCM**, **ARAP**, or **Planar**. |
| **ARAP iterations** | 4 | Number of As-Rigid-As-Possible relaxation passes. 0 disables ARAP (LSCM / planar only). |
### Packing
How the charts are arranged into the final atlas.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Atlas resolution** | 1024 px | Target atlas size (256 → 8192 px). **Higher** captures more texture detail with less pixelation, at the cost of larger files and more memory. **Lower** is lighter but softer. Match it to how close the model will be seen and your texture budget. |
| **Padding** | 4 texels | Gutter between charts. **Raise it** to stop colours bleeding across chart edges when the texture is mip-mapped or viewed at a distance — but padding eats usable atlas space. **Lower it** to pack tighter and reclaim resolution, at the risk of seam bleed. Note the gutter scales with resolution, so higher-res atlases often want a few more texels. |
| **Atlas resolution** | 1024 px | Target atlas size (256 → 8192 px). |
| **Padding** | 4 texels | Gutter between charts to prevent bleeding when sampling. |
### Topology repair
Cleans up broken geometry before unwrapping.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Proximity weld** | On | Welds coincident vertices before unwrapping. **Keep it on** — AI-generated meshes are often shattered along invisible cracks, and welding stitches those shells back together so charts don't fragment. **Turn it off** only when the mesh is already clean and you need to preserve exact vertex splits. |
| **Weld tolerance** | 0.1 | Weld distance, as a fraction of the median edge length. **Raise it** to fuse vertices that sit further apart (closes bigger gaps, but can collapse genuine fine detail). **Lower it** to fuse only near-exact duplicates. Raise it if shells still fragment; lower it if the weld is merging things it shouldn't. *(Only when weld is on.)* |
| **Proximity weld** | On | Welds coincident vertices before unwrapping — stitches shattered shells back together. |
| **Weld tolerance** | 0.1 | Weld distance, as a fraction of the median edge length. *(Only when weld is on.)* |
---

View file

@ -15,17 +15,15 @@ Rebuild your mesh with clean, evenly-distributed topology. Auto Retopo is ideal
Click **Check if Watertight** to analyze the current mesh topology. It reports whether the mesh is closed, and if not, how many **open edges** (used by a single face) and **non-manifold edges** (shared by more than two faces) it has.
This check is worth running first: if the mesh is already watertight you can turn the **Watertight shell** rebuild *off* and stay much closer to the original detail (see below).
## Clean Non-Manifold Edges
When the check finds a small number of **non-manifold edges**, you often don't need a full rebuild. A **Clean Non-Manifold Edges** button appears that repairs the topology directly on the Python service: it welds coincident vertices, drops duplicate/degenerate faces, then resolves the non-manifold edges and (optionally) closes the small holes that opens. It runs the same Keep/Revert round-trip as Auto Retopo and reports the before → after non-manifold and open-edge counts.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Repair method** | Remove faces | *Remove faces* deletes the offending faces — best when the non-manifold bits are junk (doubled or floating faces). *Split vertices* detaches the overlapping sheets instead, keeping every face but leaving clean open edges — best when the faces are real geometry you don't want to lose. |
| **Close resulting holes** | On | Seal the small holes that face removal opens. **Leave on** to aim for a closed result. **Turn it off** to guarantee no *new* non-manifold edges are introduced (at the cost of leaving the holes open) — useful when closing a hole would itself re-create a non-manifold junction. |
| **Max hole size** | 30 | Largest hole (in boundary edges) to close. **Lower it** to patch only tiny cracks and leave real openings (a mouth, an armhole) intact. **Raise it** to seal bigger gaps — but too high will close legitimate boundaries. |
| **Repair method** | Remove faces | *Remove faces* deletes the offending faces (small holes can then be closed). *Split vertices* detaches the overlapping sheets — it keeps every face but leaves clean open edges. |
| **Close resulting holes** | On | Seal the small holes that face removal opens. Turn this **off** to guarantee no new non-manifold edges are introduced (at the cost of leaving the holes open). |
| **Max hole size** | 30 | Largest hole (in boundary edges) to close. Bigger openings — legitimate mesh boundaries — are left intact. |
> Some meshes have genuinely non-manifold structures (for example, four surface patches meeting at one edge, or doubled "floating" faces) that cannot be resolved into a perfectly closed mesh automatically. In those cases the tool still reduces the defect count and reports honestly what it achieved — use the **Watertight shell** rebuild below if you need a guaranteed closed result.
@ -33,24 +31,24 @@ When the check finds a small number of **non-manifold edges**, you often don't n
### Target
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Target faces** | 6000 | Approximate face budget of the output mesh. **Higher** keeps more detail but produces a heavier mesh; **lower** gives a lighter mesh that drops fine features. Set it by purpose — a low budget for game/real-time LODs, a high one for a hero asset you'll sculpt or texture closely. |
| **Quad-dominant** | Off | **Turn it on** when you care about edge flow — quad-dominant topology subdivides and deforms better in a DCC tool. Note the result is only *reported* as quads in the metrics; the exported GLB is still triangulated. Leave it **off** if you only need clean triangles. |
| **Target faces** | 6000 | Approximate face budget of the output mesh. |
| **Quad-dominant** | Off | Convert to quad-dominant topology. Reported in the metrics, but the exported GLB stays triangulated. |
### Watertight shell
When enabled, the mesh is rebuilt from a unified voxel shell instead of remeshing the surface directly.
When enabled, the mesh is rebuilt from a unified voxel shell instead of remeshing the surface directly. This is the robust option — it heals cracks, self-intersections, and non-manifold geometry — at the cost of some fine detail and speed.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Watertight shell** | On | **On** is the robust option — it rebuilds from a voxel shell, healing cracks, self-intersections, and non-manifold geometry and guaranteeing a closed mesh, but it loses some fine detail and is slower. **Turn it off** to remesh the existing surface directly and stay far closer to the original detail — safe only when the mesh is already clean/watertight (check first). |
| **Shell resolution** | 256 | Voxel grid cells along the longest bounding-box axis. **Higher** captures finer detail but memory and time grow roughly with the cube of this number — big jumps get expensive fast. **Lower** gives a coarser, blobbier shell quickly. Raise it for detailed models, within your memory budget. |
| **Close iterations** | 1 | Morphological closing steps that bridge cracks and small gaps. **Raise it** only if the shell still has holes — too high fills in concavities and thin gaps you may want to keep (e.g. the gap between fingers). **0** applies no bridging. |
| **Smooth (sigma)** | 1.4 | SDF blur sigma in voxels — kills the voxel "staircase" ripple. **Lower it** for crisper, sharper output (better for hard-surface); **raise it** for smoother output (better for organic blobs), at the cost of rounding off sharp features. |
| **Taubin polish** | 10 | Taubin smoothing steps on the dense shell — smooths the surface without shrinking it. **Raise it** if the shell looks bumpy; **0** disables it. |
| **Samples / pitch** | 2 | Voxel sampling density. **≥ 2** guarantees gap-free coverage. **Raise it** to safely capture very thin features (slower); going below 2 risks leaks or holes on thin parts. |
| **Max memory (GB)** | 4 | Auto-lowers the shell resolution to fit this budget. Set it to the RAM/VRAM headroom you have — **higher** allows a higher effective resolution. **0** disables the cap (the shell may then run out of memory). |
| **Watertight shell** | On | Build a unified voxel shell (robust) vs. remesh the surface directly. |
| **Shell resolution** | 256 | Voxel grid cells along the longest bounding-box axis. Higher = more detail, more memory. |
| **Close iterations** | 1 | Morphological closing steps to bridge cracks and small gaps. |
| **Smooth (sigma)** | 1.4 | SDF blur sigma in voxels — kills voxel ripple. Lower = crisper. |
| **Taubin polish** | 10 | Taubin smoothing steps on the dense shell (0 disables). |
| **Samples / pitch** | 2 | Voxel sampling density. ≥ 2 guarantees gap-free coverage. |
| **Max memory (GB)** | 4 | Auto-lower the shell resolution to fit this budget (0 disables the cap). |
*All shell fields are only active when **Watertight shell** is on.*
@ -58,48 +56,42 @@ When enabled, the mesh is rebuilt from a unified voxel shell instead of remeshin
Controls how the surface is re-tessellated.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Curvature-adaptive** | On | **On** places more faces where the surface bends and fewer on flat areas — spends your face budget where detail matters (recommended). **Turn it off** for uniform density everywhere, e.g. when you want evenly-sized faces regardless of shape. |
| **Remesh iterations** | 10 | Number of remeshing passes. **Higher** gives more even edge lengths and better-quality topology, but is slower; **lower** is faster and rougher. |
| **Feature angle** | 30° | Crease angle preserved as a feature during remeshing. **Lower it** to treat gentler bends as features worth keeping (preserves more edges); **raise it** so only very sharp creases survive and everything else is smoothed. |
| **Calibrate passes** | 1 | Rough edge-length correction passes that help the face count land near your target. **Raise it** if the output count strays far from *Target faces* (slightly slower). |
| **Curvature-adaptive** | On | Place more faces where the surface bends and fewer on flat areas. |
| **Remesh iterations** | 10 | Number of remeshing passes. |
| **Feature angle** | 30° | Crease angle preserved as a feature during remeshing. |
| **Calibrate passes** | 1 | Rough edge-length correction passes. |
### Feature preservation
Hard-surface mode for mechanical / man-made objects with sharp edges.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Preserve features** | Off | **Turn it on** for hard-surface / man-made objects with crisp edges (bolts, panels, blades) — it keeps corners from being rounded off and skips the smoothing/projection that would soften them. **Leave it off** for organic, smooth shapes, where forcing hard edges would create ugly faceting. See the note below on how it interacts with projection. |
| **Feature angle** | 25° | Crease angle treated as a hard edge. **Lower it** to keep more edges sharp; **raise it** so only the sharpest corners are preserved. *(Only when preserve features is on.)* |
| **Preserve features** | Off | Keep sharp creases crisp and skip smoothing/projection. |
| **Feature angle** | 25° | Crease angle treated as a hard edge. *(Only when preserve features is on.)* |
### Silhouette projection
After remeshing, the new mesh can be projected back onto the original surface to recover its silhouette.
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Project to surface** | On | **Keep it on** — this snaps the rebuilt mesh back onto the original surface, recovering the detail and silhouette lost to remeshing or voxelization. **Turn it off** to leave the remesh/shell as-is (blobbier, but faster and more uniform). |
| **Projection iterations** | 10 | Number of projection passes. **Higher** hugs the original surface more tightly (slower); **lower** gives a looser fit. |
| **Move clamp** | 1.5 | Maximum per-vertex move, as a multiple of local edge length. **Higher** lets vertices travel far to recover deep detail — but can spike if the projection misfires. **Lower it** for a conservative, stable fit; lower it further if you see spikes or shards in the result. |
| **Relax strength** | 0.4 | Tangential relaxation applied each iteration. **Higher** evens out the triangle distribution along the surface (smoother mesh, but can blur fine detail); **lower** keeps vertices where they projected, which may let them cluster. |
| **Project to surface** | On | Project the remesh back onto the original surface. |
| **Projection iterations** | 10 | Number of projection passes. |
| **Move clamp** | 1.5 | Maximum per-vertex move, as a multiple of local edge length. |
| **Relax strength** | 0.4 | Tangential relaxation factor applied each iteration. |
**Note on Preserve features + Projection:**
- In **surface mode** (watertight off), projection is **skipped** when Preserve features is on — and the projection fields are disabled.
- In **surface mode** (watertight off), projection is **skipped** when Preserve features is on.
- **Watertight shells are always projected** onto the original surface, even with Preserve features on.
### Compute
| Field | Default | What it does & how to tune it |
| --- | --- | --- |
| **Device** | Auto (GPU if NVIDIA) | Where the heavy stages run. **Auto** uses an NVIDIA GPU when one is available and falls back to CPU otherwise. Choose **CUDA** to force the GPU, or **CPU** to force CPU (use this if the GPU runs out of memory, or you have no NVIDIA card). Only the watertight-shell stage (CuPy) and the surface-projection stage (NVIDIA Warp) are GPU-accelerated — the remesh / "building clean topology" stage always runs on the CPU regardless of this setting. |
### Misc
| Field | Default | What it does & how to tune it |
| Field | Default | What it does |
| --- | --- | --- |
| **Seed** | 0 | RNG seed for reproducible results. The same seed reproduces the same output; change it only to roll a different random variation. |
| **Seed** | 0 | RNG seed for reproducible results. |
---

View file

@ -1,49 +0,0 @@
# Auto Rig
Generate a full skeleton and skin weights for your mesh automatically. Auto Rig sends the current mesh to the **SkinTokens / TokenRig** rigging service, which predicts a humanoid skeleton, binds it to the surface with skin weights, and returns a **rigged (skinned) GLB**. The skeleton is then shown as an overlay in the viewport.
> Auto Rig runs on the **SkinTokens rigging service**. Configure and start it in **Settings → Rigging** before using this mode. It needs an **NVIDIA GPU**.
Unlike Auto UV and Auto Retopo, the rig result is **not** flattened back into the editable mesh — its value *is* the skeleton. So instead of Keep/Revert, you **Save as version** or **Download** the rigged GLB.
## Running it
1. Open the **Auto Rig** mode in the left toolbar.
2. Tune the **Skeleton** and (optionally) **Generation** options below.
3. Click **Run Auto Rig** and wait for the service to finish. A progress bar reports its state.
4. When it completes, the skeleton appears on the mesh and a **Rig generated** panel shows the result metrics (bone count, etc.).
5. Choose what to do with the result:
- **Save as version** — store the rigged GLB as a new version of the asset in your library.
- **Download** — save the rigged GLB to disk.
- **Dismiss** — hide the result panel (the skeleton overlay stays visible).
## Show skeleton
The **Show skeleton** toggle overlays the bones on the mesh in the viewport. It is enabled whenever the current mesh has a skeleton — either one you just generated, or one that was already present on a loaded rigged mesh. If the mesh has no skeleton yet, the toggle is disabled and a hint prompts you to run Auto Rig.
## Skeleton options
Control the skeleton that gets generated.
| Field | Default | What it does |
| --- | --- | --- |
| **Bone names** | Mixamo | Rename the generated bones to a standard humanoid convention for retargeting. Choose **Mixamo**, **Unreal Engine 5**, or **Keep model names**. |
| **Preserve texture & scale** | On | Transfer the rig onto your *original* mesh so it keeps its texture and scale. Recommended — leave on. |
| **Voxel-skin postprocess** | On | Clean up skin weights with a voxel pass to reduce weight bleed across disconnected parts. |
| **Keep model loaded in memory** | On | Keep the rig model in (GPU) memory for fast repeat rigs. Turn off to free memory after each rig — the next rig reloads it (slower first run). |
## Generation (advanced)
These control the sampling of the skeleton-prediction model. The defaults are tuned for good results — only adjust them if you need to experiment with the output.
| Field | Range | What it does |
| --- | --- | --- |
| **Top-k** | 1–200 | Top-k sampling limit. |
| **Top-p** | 0.1–1 | Nucleus (top-p) sampling threshold. |
| **Temperature** | 0.1–2 | Sampling randomness. Lower is more deterministic. |
| **Repetition penalty** | 0.5–3 | Penalizes repeated tokens during generation. |
| **Beams** | 1–20 | Beam-search width. |
---
The result is a **skinned mesh** — save it as a new version to keep the rig. Once a mesh is rigged, you can open the **[Skeleton](33.md)** panel to inspect its bones and the **[Animations](34.md)** tab to retarget motion onto it.

View file

@ -1,27 +0,0 @@
# Skeleton
When the current mesh is rigged (after running **[Auto Rig](32.md)**, or when you load an already-rigged mesh), a panel appears on the right of the Mesh Editor with two tabs: **Skeleton** and **[Animations](34.md)**. This page covers the **Skeleton** tab.
## Bone hierarchy
The Skeleton tab shows every bone in the mesh as a collapsible **hierarchy tree**, rooted at the skeleton's root bone(s). The header reports the total bone count.
- Bones with children show a **chevron** — click it to expand or collapse that branch.
- Each row is labelled with the bone's name (using whatever naming convention you chose in Auto Rig — Mixamo, UE5, or the model's own names).
## Selecting bones
Bone selection is **two-way** with the viewport:
- **Click a bone row** in the panel to select it. The matching bone is highlighted on the mesh via the skeleton overlay.
- **Click a bone on the mesh** to select it here. Its row is highlighted, its collapsed ancestors are automatically expanded so it is revealed, and the tree scrolls it into view.
This makes it easy to confirm *which* physical bone a name refers to — names alone rarely tell you where a bone actually sits.
## Requirements
The Skeleton panel only appears while you are in **Auto Rig** mode and the current mesh actually has a skeleton. If the mesh has no bones, the panel shows an empty state instead of a tree.
---
To animate a rigged mesh, switch to the **[Animations](34.md)** tab.

View file

@ -1,38 +0,0 @@
# Animations
The **Animations** tab (in the Mesh Editor's Auto Rig side panel, next to **[Skeleton](33.md)**) lets you retarget ready-made animation clips onto your rigged mesh, preview them live, and save the mesh with the animations you like embedded.
Animations are **retargeted** from a *reference mesh* — a pre-animated character whose motion is transferred onto your mesh's skeleton. To do that, the reference skeleton's bones must first be mapped to your mesh's bones (see **[Bone Mapping](35.md)**).
> This tab only works on a **rigged** mesh. Run **[Auto Rig](32.md)** first (or load a mesh that already has a skeleton).
## Workflow
1. **Select a reference mesh** from the dropdown. This is the source of the animation library.
2. Click **Map bones** to open the **[Bone Mapping](35.md)** dialog and match the reference skeleton to your mesh. (Once mapped, this button becomes **Edit mapping**.)
3. The animation clips from that reference load into the list. **Click a clip** to retarget it onto your mesh and preview it playing in the viewport.
4. **Tick** the clips you want to keep.
5. Click **Save mesh with N animations** to embed the selected clips and save the mesh as a **new version** in your library.
## Playback options
Once a mapping exists, extra controls appear above the clip list:
| Control | What it does |
| --- | --- |
| **Auto-align to floor** | Sit the animated mesh on the floor grid so it doesn't sink or float during playback. |
| **Expand / Contract arms** | A slider (−100% → +100%) that spreads or tucks the arms. Useful when the retargeted rest pose has arms too wide or too close to the body. A reset button returns it to 0. *(Shown only when the mesh's rig supports arm adjustment.)* |
## Searching and selecting clips
- The **search box** filters the clip list by name. The header shows the filtered count (e.g. `12 / 80` when a search is active).
- Each clip has a **preview thumbnail** and a **checkbox**. Clicking a clip selects it for live preview; ticking its box marks it to be embedded on save.
- The **Save** button is disabled until at least one clip is ticked, and shows a count of how many will be embedded.
## Saving
**Save mesh with N animations** embeds the ticked clips into the mesh and stores it as a **new version** of the asset. The original (unanimated) version is left untouched, so you can always go back.
---
Next: **[Bone Mapping](35.md)** — how to match the reference skeleton to your mesh.

View file

@ -1,42 +0,0 @@
# Bone Mapping
Before a reference animation can be retargeted onto your mesh, the app needs to know which bone on your mesh corresponds to each bone in the reference (animation) skeleton. The **Bone Mapping** dialog is where you set that up. It opens from the **[Animations](34.md)** tab via **Map bones** (or **Edit mapping** if a mapping already exists).
Each row maps one **source** bone (the reference animation skeleton, left) to one **target** bone (your rigged mesh, right). A source bone can be used at most once.
## Layout
The dialog has three parts:
- **3D skeleton views** (far left) — two live, rotatable skeletons: the **source** (reference) on top and your **target** mesh below. These make it obvious *where* each bone sits, which names alone rarely tell you.
- **Source column** — every bone in the reference animation skeleton, with a filter box.
- **Target column** — every bone in your mesh, with a filter box and the mapping actions.
The header and footer both show how many bones are currently mapped (e.g. *18 of 22 target bones mapped*).
## Mapping bones
There are several ways to create a mapping:
- **Drag** a source bone onto a target row.
- **Click a source** bone, then **click a target** — the source is assigned to that target.
- **Click a bone in either 3D view** to select it (same as clicking its row). If a source is already picked, clicking a target bone in the 3D view assigns it.
- **Hover a list row** to flash that bone in the corresponding 3D view.
Mapped source bones are marked with a check and greyed as "used". Each target row shows the source bone it is bound to as a chip, or **unmapped** if none. Click the **×** on a mapped target row to clear it.
## Actions
| Button | What it does |
| --- | --- |
| **Auto-Map** | Fill the mapping heuristically from scratch, **replacing** the current mapping entirely. |
| **Finish Mapping** | Fill only the *currently unmapped* target bones from the heuristic, **keeping** the ones you've already set and never reusing a source that's already in use. Disabled once every target is mapped. |
| **Clear** | Remove all mappings. |
## Saving
Click **Save mapping** to apply it. The button is enabled once at least one bone is mapped. After saving, the reference's animation clips load into the Animations tab, ready to preview and retarget. Press **Escape**, click **Cancel**, or click outside the dialog to close without saving.
---
Back to **[Animations](34.md)**.

View file

@ -1,13 +0,0 @@
# Imports / Exports
3DGenStudio can move work in and out of the app in two ways:
- **[Project](37.md)** — export an entire project (with all its assets) to a self-contained `.3dgp` bundle, and import one back. Use this to back up a project, move it to another machine, or share it with a teammate.
- **[Mesh](38.md)** — export a single mesh to a 3D file format (GLB, FBX, OBJ, PLY, STL) with engine-ready presets for Blender, Unity and Unreal. Use this to take a finished asset into a game engine or DCC tool.
Pick the page that matches what you want to move:
| I want to… | Use |
| --- | --- |
| Back up, move, or share a whole project | **[Project import / export](37.md)** |
| Send one mesh to Blender / Unity / Unreal / another tool | **[Mesh export](38.md)** |

View file

@ -1,35 +0,0 @@
# Project
Export and import entire projects as self-contained **`.3dgp` bundles**. A bundle carries the project *and* every asset it links to — meshes, images, sub-assets and thumbnails — so you can back it up, move it to another machine, or hand it to a teammate.
Both actions are available from the **Projects** page.
## Exporting a project
1. On the **Projects** page, hover a project card and click its **Export** action.
2. Give the export a **name** (defaults to the project's name).
3. Choose a **destination folder** — type the path or click **Browse**.
4. Click **Export**.
The app creates a folder named after the export containing:
```
<name>/
<name>.3dgp ← the project bundle file
assets/ ← every linked asset, sub-asset and thumbnail
```
On success the dialog reports how many assets and files were written, and where.
## Importing a project
1. On the **Projects** page, click **Import**.
2. Choose the **source folder** — the folder that contains the `.3dgp` file. Type the path or click **Browse**. (When you browse to a folder, its name is used as the default project name.)
3. Optionally set a **project name**. Leave it blank to keep the name stored in the bundle.
4. Click **Import**.
Every asset in the bundle is copied in as a **fresh library entry** and a **brand-new project** is created from it — the import never overwrites or merges with an existing project. When it finishes, the app opens the newly imported project.
---
To export a single mesh (rather than a whole project) to a 3D file format, see **[Mesh export](38.md)**.

View file

@ -1,39 +0,0 @@
# Mesh
Export a single mesh to a standard 3D file format, with engine-ready presets for Blender, Unity and Unreal. This is how you take a finished asset out of 3DGenStudio and into a game engine or another DCC tool.
## Where to export from
- **Mesh preview** — open a mesh asset's preview, then click **Export**. This path can carry the asset's **rig and animation clips**, so it offers the full set of engine presets.
- **Mesh Editor** — the editor can also export the mesh you're working on. Because the editor hands over rig-free geometry, only the plain geometry formats (GLB, OBJ, PLY, STL) are offered there.
## Exporting
1. Click **Export** to open the export dialog.
2. Choose a **format** (see below).
3. Set the **file name** — the extension is filled in automatically for the chosen format.
4. Choose an **output folder** — type the path or click **Browse**.
5. Click **Export**. A progress bar is shown for formats that need conversion, and a success message lists the files that were written.
## Formats
| Format | File | Notes |
| --- | --- | --- |
| **GLB** | `.glb` | Single file with textures embedded. The default. |
| **Blender — GLB (rig + animations)** | `.glb` | Blender imports GLB natively (*File → Import → glTF 2.0*) with the skeleton and every animation clip. GLB source assets are copied byte-for-byte for perfect fidelity. |
| **Unity — FBX (rig + takes)** | `.fbx` | Drop the `.fbx` into *Assets*. Textures are embedded — use *Materials → Extract Textures*. Pick the rig type under *Rig* (Humanoid may need *Enforce T-Pose*); each clip appears as a separate take. |
| **Unreal Engine — FBX (cm, rig + takes)** | `.fbx` | Import as a *Skeletal Mesh* with *Import Animations* enabled. Exported in centimeters at scale 1 — no unit conversion needed. |
| **FBX — generic (rig + takes)** | `.fbx` | Neutral FBX (meters, Y-up) with the skeleton and one take per clip. Suitable for Godot, Maya, 3ds Max and other DCC tools. |
| **OBJ — geometry + .mtl + textures** | `.obj` | Saves geometry, materials and textures as separate files named after the mesh (e.g. `mesh.obj`, `mesh.mtl`, `mesh_albedo.png`). |
| **PLY** | `.ply` | Geometry only. |
| **STL** | `.stl` | Geometry only. |
> The **FBX presets** (Unity, Unreal, generic) convert through the **Mesh Tools service**, which the app starts automatically when you export. GLB and the geometry-only formats (GLB, OBJ, PLY, STL) export directly and need no service.
## Rig and animations
The FBX and Blender presets exist specifically to carry a mesh's **skeleton and animation clips** into an engine. When the source asset is already a `.glb`, its original bytes are used so skin weights, clips and textures are preserved exactly. Otherwise the mesh is serialized through three.js, which still carries the loaded animations onto the export. After an FBX conversion the success message reports the bone and clip counts that were written.
---
To move a whole project (all its assets at once) rather than a single mesh, see **[Project import / export](37.md)**.

View file

@ -1,195 +0,0 @@
# MCP
3D Gen Studio ships an **MCP** ([Model Context Protocol](https://modelcontextprotocol.io)) server, so any AI assistant — Claude, GitHub Copilot, ChatGPT, or a local LLM — can drive the app for you: create projects, build node graphs, run ComfyUI workflows, generate images and meshes, run the mesh tools (Auto UV, Retopo, Repair, Rig, Optimize), and import/export projects.
## The endpoint
The MCP server is built into the app backend — there is no extra process to start. Launch the desktop app (or run `npm run dev`) and the endpoint is live at:
```
http://localhost:3001/mcp
```
It speaks **Streamable HTTP**. The app must be running whenever a client wants to use the tools.
### Security
- **Local by default** — with no token set, only clients on the same machine can connect.
- **Remote access** — set a bearer token and remote clients must send `Authorization: Bearer <token>`.
- **Disable** — turn the server off and the endpoint returns `404`.
Settings are stored in the app database. Set them with a request to `POST /api/settings`:
```json
{ "mcp": { "enabled": true, "token": "your-secret-token" } }
```
Leave `token` empty for local-only use.
## Configure with Claude
### Claude Code
One command adds the server:
```sh
claude mcp add --transport http 3d-gen-studio http://localhost:3001/mcp
```
Then just talk to Claude — the `3d-gen-studio` tools are available in any session.
### Claude Desktop
**Option A — Custom connector (recommended).** Open **Settings → Connectors → Add custom connector** and enter the URL:
```
http://localhost:3001/mcp
```
**Option B — Config file (stdio bridge).** Edit `claude_desktop_config.json` and add:
```json
{
"mcpServers": {
"3d-gen-studio": {
"command": "node",
"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]
}
}
}
```
Adjust the path to your checkout. The bridge requires the app to be running and talks to `http://127.0.0.1:3001` (override with the `GENSTUDIO_URL` environment variable).
If you don't have a local checkout, you can use `mcp-remote` instead:
```json
{
"mcpServers": {
"3d-gen-studio": {
"command": "npx",
"args": ["mcp-remote", "http://localhost:3001/mcp"]
}
}
}
```
Restart Claude Desktop after editing the file.
## Configure with Visual Studio Code
MCP tools in VS Code are used from **GitHub Copilot Agent mode**. You need VS Code 1.102+ with the **GitHub Copilot** and **GitHub Copilot Chat** extensions.
**Fastest path:** open the Command Palette (`Ctrl+Shift+P`) → **MCP: Add Server…** → **HTTP** → enter `http://localhost:3001/mcp` → name it `3d-gen-studio`.
**Or add it to your workspace** by creating `.vscode/mcp.json`. Note that VS Code uses the `servers` key (not `mcpServers`):
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp"
}
}
}
```
Start the server via the CodeLens shown in that file (or the MCP view), then:
1. Open **Copilot Chat**.
2. Switch to **Agent** mode.
3. Click the tools (🔧) picker and enable the 3D Gen Studio tools.
For a token-protected or remote endpoint, add an `Authorization` header and let VS Code prompt for the token:
```json
{
"servers": {
"3d-gen-studio": {
"type": "http",
"url": "http://localhost:3001/mcp",
"headers": { "Authorization": "Bearer ${input:genstudio-token}" }
}
},
"inputs": [
{
"id": "genstudio-token",
"type": "promptString",
"description": "3D Gen Studio MCP token",
"password": true
}
]
}
```
A `stdio` server also works (`"type": "stdio"`, `"command": "node"`, `"args": ["C:/Git/3DGenStudio/mcp/stdio.js"]`) and likewise needs the app running.
## Other clients
Any client that supports Streamable HTTP MCP servers can connect to `http://localhost:3001/mcp` — for example **ChatGPT** (developer mode) or a local LLM stack. Remote clients need the bearer token (see [Security](#security)).
To debug a connection, use the **MCP Inspector**:
```sh
npx @modelcontextprotocol/inspector
```
Connect with transport **Streamable HTTP** to `http://localhost:3001/mcp`.
## Example prompts
Once connected, ask your assistant in plain language. A few things to try:
**Explore & set up**
- *"List my 3D Gen Studio projects and tell me what's in the latest one."*
- *"Create a new graph project called 'Robot Concept'."*
- *"Which ComfyUI workflows do I have available, and what parameters does the text-to-image one take?"*
**Generate images**
- *"In the 'Robot Concept' project, generate an image of a friendly retro robot on a white background."*
- *"Run my text-to-image workflow with the prompt 'weathered stone golem, moss on shoulders' and show me the result."*
**Generate & refine meshes**
- *"Generate a 3D mesh from the robot image and display it on a node."*
- *"Generate a mesh with Tripo from this image, then run Auto Retopo on it to clean up the topology."*
- *"Run Auto UV on the latest mesh, then export it as a GLB to my Desktop."*
**Build a pipeline (graph projects)**
- *"Create an image node, generate a concept image on it, then add a mesh node wired to it and generate a 3D model."*
- *"Show me the current graph, then connect the image node to the mesh node and run the mesh generation."*
**Manage assets**
- *"List the assets in this project and show me the ones that are meshes."*
- *"Download the final textured mesh to `C:/Exports`."*
### Tips for good results
- **In graph projects, mention the node** you want results on (e.g. *"display it on the mesh node"*). The assistant passes the node id so the result appears on the canvas; without it, assets are saved but no node shows them.
- **Wire inputs before running.** When editing or deriving assets, connect the source node first — the assistant is guided to do this, but saying *"connect it, then run"* keeps the order right.
- **Some things need external services running:** ComfyUI (for `run_workflow`), provider API keys (for the mesh/image generators), and the Python mesh-tools service on `:8200` (for Auto UV / Retopo / Repair). The desktop app can start the Python service from Settings.
## What's available
The server exposes tools grouped by area:
| Group | What it covers |
|---|---|
| Projects | Create, list, update, delete, import, and export projects |
| Kanban cards | List and move cards, manage card attributes |
| Graph | Read the graph, create/move/delete nodes, connect and disconnect them |
| ComfyUI workflows | List, inspect, import, update, and run workflows |
| AI actions | Generate and edit images; generate meshes (built-in, Tencent, Tripo, Hitem3D); edit, texture, and rig meshes |
| Mesh tools | Auto UV, Auto Retopo, Repair, Auto Rig, Optimize, FBX convert, and export |
| Assets | List, view, download, upload, link, and delete assets |
| System | Read settings (secrets redacted) and system stats |
## Limitations
- The interactive **Mesh Editor** operations (sculpt, modeling, boolean, painting, projection, texture bake) and **Image Editor** pixel operations (crop, filters, shadow remover) run in the browser and are **not** exposed over MCP. Use the AI alternatives instead: ComfyUI workflows, prompt-based image edits, and the mesh-tool services.
- If the app is open in a browser while an MCP client changes data, open Graph and Kanban pages refresh automatically; other pages may need a manual refresh.

View file

@ -278,78 +278,6 @@
"position": 6,
"createdAt": 1783518027458,
"updatedAt": 1783518036189
},
{
"id": 32,
"parentId": 12,
"title": "Auto Rig",
"icon": "description",
"position": 7,
"createdAt": 1784129471917,
"updatedAt": 1784129481740
},
{
"id": 33,
"parentId": 32,
"title": "Skeleton",
"icon": "description",
"position": 0,
"createdAt": 1784129488969,
"updatedAt": 1784129500497
},
{
"id": 34,
"parentId": 32,
"title": "Animations",
"icon": "description",
"position": 1,
"createdAt": 1784129502193,
"updatedAt": 1784129513127
},
{
"id": 35,
"parentId": 34,
"title": "Bone Mapping",
"icon": "description",
"position": 0,
"createdAt": 1784129514439,
"updatedAt": 1784129524534
},
{
"id": 36,
"parentId": null,
"title": "Imports / Exports",
"icon": "description",
"position": 5,
"createdAt": 1784129581364,
"updatedAt": 1784129594826
},
{
"id": 37,
"parentId": 36,
"title": "Project",
"icon": "description",
"position": 0,
"createdAt": 1784129597001,
"updatedAt": 1784129608065
},
{
"id": 38,
"parentId": 36,
"title": "Mesh",
"icon": "description",
"position": 1,
"createdAt": 1784129609391,
"updatedAt": 1784129619051
},
{
"id": 39,
"parentId": null,
"title": "MCP",
"icon": "description",
"position": 6,
"createdAt": 1784492754708,
"updatedAt": 1784492762736
}
]
}

View file

@ -1,7 +1,7 @@
import path from 'path';
import process from 'process';
import fs from 'fs/promises';
import { existsSync } from 'fs';
import { fileURLToPath } from 'url';
// ─────────────────────────────────────────────────────────────────────────
// File-based wiki store. Lives in a git-tracked folder so the documentation
@ -9,17 +9,9 @@ import { fileURLToPath } from 'url';
// wiki/manifest.json — flat list of pages (the tree is derived from parentId)
// wiki/content/<id>.md — one Markdown file per page
// wiki/media/ — screenshots and videos referenced by the pages
//
// Resolve the folder relative to THIS module — NOT process.cwd(). The desktop
// app runs the backend with cwd set to the per-user data dir (so the writable
// data/ folder lands there), but the wiki is shipped, read-only documentation
// that sits beside this file: the repo root in dev, resources/app/ in a
// packaged build. Keying off cwd made the packaged app read (and seed a stray
// default) wiki under the user data dir instead of the shipped one.
// ─────────────────────────────────────────────────────────────────────────
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
export const WIKI_DIR = path.join(MODULE_DIR, 'wiki');
export const WIKI_DIR = path.join(process.cwd(), 'wiki');
export const WIKI_CONTENT_DIR = path.join(WIKI_DIR, 'content');
export const WIKI_MEDIA_DIR = path.join(WIKI_DIR, 'media');
const WIKI_MANIFEST = path.join(WIKI_DIR, 'manifest.json');