Compare commits

..

No commits in common. "main" and "v2.1.0" have entirely different histories.
main ... v2.1.0

50 changed files with 465 additions and 3879 deletions

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,8 +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 |

View file

@ -41,9 +41,6 @@ files:
- 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

@ -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,7 +21,6 @@ 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';
@ -196,11 +192,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 +214,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 +222,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).

View file

@ -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

@ -49,15 +49,10 @@ 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.')
},
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, includeChildren }) => {
const assets = await api.apiJson('GET', '/assets', {
query: { projectId, ...(includeChildren ? { includeChildren: 'true' } : {}) }
});
}, toolHandler(async ({ projectId }) => {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
return (Array.isArray(assets) ? assets : []).map(asset => withAssetUrls(api, asset));
}));
@ -106,48 +101,22 @@ export function registerAssetTools(server, { api, notifyMutation }) {
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.',
description: 'Attach an already-stored asset file (by its stored filename) to a project — creates the card/link without re-uploading.',
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.'),
filename: z.string().min(1).describe('Stored asset filename (from list_library_assets)'),
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.')
metadata: z.record(z.string(), z.any()).optional()
}
}, 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 } : {}) }
});
}, toolHandler(async ({ projectId, filename, type, name, metadata }) => {
const asset = 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.',

View file

@ -31,7 +31,7 @@ async function resolveWorkflowJson({ workflowJson, filePath }) {
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.',
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue) and output nodes.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const workflows = await api.apiJson('GET', '/library/comfy-workflows');
@ -58,7 +58,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
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.',
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}); 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)'),
@ -66,9 +66,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
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.')
valueType: z.string().optional()
})).optional().describe('Inputs to expose as parameters (ids from inspect_workflow)'),
outputs: z.array(z.object({
nodeId: z.string(),

2
package-lock.json generated
View file

@ -1,6 +1,6 @@
{
"name": "app",
"version": "2.1.2",
"version": "2.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {

View file

@ -1,7 +1,7 @@
{
"name": "app",
"private": true,
"version": "2.1.2",
"version": "2.1.0",
"type": "module",
"main": "electron/main.cjs",
"description": "AI-powered 3D mesh production studio — image generation, mesh generation, UV unwrapping, and texturing pipelines.",

193
server.js
View file

@ -65,8 +65,6 @@ import {
getWorkflowRecordById,
initializeStorage,
listLibraryAssetsByType,
linkExistingAssetToProject,
unlinkAssetFromProjectById,
listProjectAssets,
listProjectTasks,
listProjects,
@ -374,13 +372,10 @@ app.post('/api/library/comfy-workflows', async (req, res) => {
throw new Error(`Unknown workflow parameter: ${parameter.id}`);
}
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType,
enums: normalizeComfyEnums(parameter.enums, valueType)
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter))
};
});
@ -458,20 +453,10 @@ app.put('/api/library/comfy-workflows/:id', async (req, res) => {
defaultValue = cloneSerializable(sourceParameter.defaultValue);
}
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
// Same rule as defaultValue: an incoming list wins (including an empty one,
// which clears the enums), otherwise keep whatever was stored — callers such
// as "Set as default" send a minimal parameter list and must not wipe it.
const enums = Object.prototype.hasOwnProperty.call(parameter, 'enums')
? normalizeComfyEnums(parameter.enums, valueType)
: normalizeComfyEnums(storedParameter?.enums, valueType);
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType,
enums,
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter)),
defaultValue
};
});
@ -878,33 +863,6 @@ function normalizeComfyValueType(value, fallback = 'string') {
return ['string', 'number', 'boolean', 'image', 'video', 'mesh'].includes(value) ? value : fallback;
}
// Enums restrict a String / Number parameter to a fixed list of allowed values,
// which the UI renders as a dropdown. Entries are coerced to the parameter's value
// type and de-duplicated; a non-String/Number parameter never keeps a list.
// Returns undefined when there is nothing to store (JSON.stringify drops the key).
function normalizeComfyEnums(rawEnums, valueType) {
if (!Array.isArray(rawEnums) || !['string', 'number'].includes(valueType)) return undefined;
const values = [];
for (const entry of rawEnums) {
if (entry === null || entry === undefined || typeof entry === 'boolean' || typeof entry === 'object') continue;
if (valueType === 'number') {
const numericValue = Number(entry);
if (!Number.isFinite(numericValue) || values.includes(numericValue)) continue;
values.push(numericValue);
continue;
}
const textValue = String(entry).trim();
if (!textValue || values.includes(textValue)) continue;
values.push(textValue);
}
return values.length > 0 ? values : undefined;
}
function getComfyNodeLabel(nodeId, node = {}) {
return sanitizeDisplayName(node._meta?.title || node.title || node.class_type || `Node ${nodeId}`, `Node ${nodeId}`);
}
@ -1481,7 +1439,7 @@ async function sleep(ms) {
async function queueComfyPrompt(baseUrl, workflowJson, identifiers = {}) {
const clientId = String(identifiers?.clientId || '').trim() || randomUUID();
const promptId = randomUUID(); // patched 2026-07-30: ComfyUI now enforces UUID prompt_id, client-supplied ids can be non-UUID and get rejected
const promptId = String(identifiers?.promptId || '').trim() || randomUUID();
const response = await fetch(`${baseUrl}/prompt`, {
method: 'POST',
headers: {
@ -2846,7 +2804,7 @@ async function saveGeneratedMeshAssets({
// When the mesh was edited from a connected mesh, save it as a version (child)
// of that mesh instead of creating a new root asset.
savedAssets.push(normalizedParentAssetId
? await createAssetVersion({ assetId: normalizedParentAssetId, ...assetPayload, thumbnailPath: thumbnailFilename, inheritThumbnail: false, projectId: Number(projectId) })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...assetPayload, thumbnailPath: thumbnailFilename, inheritThumbnail: false })
: await createProjectAsset({ projectId: Number(projectId), ...assetPayload, thumbnailPath: thumbnailFilename }));
}
@ -3606,7 +3564,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
const persistProcessingCard = String(req.body.persistProcessingCard || '').toLowerCase() !== 'false';
const persistGeneratedAssets = String(req.body.persistGeneratedAssets || '').toLowerCase() !== 'false';
// Brainstorming Board generations link assets to the project without creating
// a visible Kanban card (an Assets_Projects row and no Cards_Assets row).
// a visible Kanban card (see ensureDetachedCard).
const persistAssetsDetached = String(req.body.detachedAsset || '').toLowerCase() === 'true';
// Default ON: when no explicit parentAssetId is given, save each output under
// the resolved input asset of the same type — a mesh output becomes a version of
@ -3884,7 +3842,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
// of the source image. Otherwise it's a new root asset.
const outputParentId = resolveOutputParentId(inferredAssetType);
const persistedAsset = (outputParentId && inferredAssetType === 'mesh')
? await createAssetVersion({ assetId: outputParentId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false, projectId: hasProjectId ? normalizedProjectId : null })
? await createAssetVersion({ assetId: outputParentId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false })
: (outputParentId && inferredAssetType === 'image')
? {
...(await createAssetEditRecord({
@ -3894,7 +3852,6 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
filePath: storedFilePath,
width: dimensions.width,
height: dimensions.height,
projectId: hasProjectId ? normalizedProjectId : null,
createdAt: generatedAssetPayload.createdAt
})),
type: 'image'
@ -4433,7 +4390,7 @@ app.post('/api/meshes/generate', async (req, res) => {
// When a mesh was connected to the node and used to edit it, save the
// result as a version (child) of that mesh instead of a new root asset.
const savedAsset = normalizedParentAssetId
? await createAssetVersion({ assetId: normalizedParentAssetId, ...meshAssetPayload, inheritThumbnail: false, projectId: Number(projectId) })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...meshAssetPayload, inheritThumbnail: false })
: await createProjectAsset({ projectId: Number(projectId), ...meshAssetPayload });
await clearCardProcessingState(processingProjectId, processingCardId, {
@ -5248,50 +5205,6 @@ app.delete('/api/projects/:id', async (req, res) => {
}
});
// Project <-> asset membership (Assets_Projects). An asset belongs to a project
// on its own, with no card required: any asset id works, root or edit/version.
app.post('/api/projects/:id/assets', async (req, res) => {
try {
const assetId = Number(req.body?.assetId);
if (!Number.isFinite(assetId)) {
return res.status(400).json({ error: 'assetId is required' });
}
const linked = await linkExistingAssetToProject(Number(req.params.id), assetId, {
cascadeChildren: req.body?.cascadeChildren === true
});
res.status(201).json(linked);
} catch (err) {
if (err.message === 'Asset not found') {
return res.status(404).json({ error: 'Asset not found' });
}
if (err.message?.startsWith('Project not found:')) {
return res.status(404).json({ error: 'Project not found' });
}
console.error('Failed to link asset to project:', err);
res.status(500).json({ error: 'Failed to link asset to project' });
}
});
app.delete('/api/projects/:id/assets/:assetId', async (req, res) => {
try {
const result = await unlinkAssetFromProjectById(Number(req.params.id), Number(req.params.assetId), {
cascadeChildren: req.query.cascadeChildren !== 'false'
});
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Asset not found' });
}
res.json(result);
} catch (err) {
console.error('Failed to unlink asset from project:', err);
res.status(500).json({ error: 'Failed to unlink asset from project' });
}
});
// Turn a filesystem-unsafe name into a folder base name (letters, digits,
// spaces, dot, dash, underscore) so it can name the export folder + .3dgp file.
function sanitizeProjectExportName(name, fallback = 'project') {
@ -5403,12 +5316,8 @@ app.post('/api/projects/import', async (req, res) => {
});
app.get('/api/assets', async (req, res) => {
const { projectId, includeChildren } = req.query;
// includeChildren returns every project-linked edit/version as a row of its
// own, on top of the copies nested in each root's `children` array.
res.json(await listProjectAssets(projectId ? Number(projectId) : null, {
includeChildren: String(includeChildren || '').toLowerCase() === 'true'
}));
const { projectId } = req.query;
res.json(await listProjectAssets(projectId ? Number(projectId) : null));
});
app.get('/api/cards', async (req, res) => {
@ -6656,40 +6565,10 @@ app.get('/api/assets/resolve-source', async (req, res) => {
app.post('/api/assets/link', async (req, res) => {
try {
const { projectId, assetId, filename, type = 'image', name, metadata, detached } = req.body;
const { projectId, filename, type = 'image', name, metadata, detached } = req.body;
if (!projectId) {
return res.status(400).json({ error: 'projectId is required' });
}
// Link an EXISTING asset by id — works for a root asset as well as for an
// image edit or a mesh version, which have no file of their own to look up
// in the library and previously could not be attached to a project at all.
if (assetId !== undefined && assetId !== null && assetId !== '') {
const numericAssetId = Number(assetId);
if (!Number.isFinite(numericAssetId)) {
return res.status(400).json({ error: 'assetId must be a number' });
}
try {
const linked = await linkExistingAssetToProject(Number(projectId), numericAssetId, {
cascadeChildren: req.body.cascadeChildren === true
});
return res.status(201).json(linked);
} catch (linkErr) {
if (linkErr.message === 'Asset not found') {
return res.status(404).json({ error: 'Asset not found' });
}
if (linkErr.message?.startsWith('Project not found:')) {
return res.status(404).json({ error: 'Project not found' });
}
throw linkErr;
}
}
if (!filename) {
return res.status(400).json({ error: 'assetId or filename is required' });
if (!projectId || !filename) {
return res.status(400).json({ error: 'projectId and filename are required' });
}
const assetType = type || inferAssetTypeFromFilename(filename);
@ -6734,10 +6613,7 @@ app.post('/api/assets/link', async (req, res) => {
app.delete('/api/assets/:id', async (req, res) => {
try {
const assetId = Number(req.params.id);
// With ?projectId= the asset is detached from that project only; without it,
// from every project (and deleted outright when it belonged to none).
const projectId = req.query.projectId ? Number(req.query.projectId) : null;
const result = await deleteAssetById(assetId, { projectId });
const result = await deleteAssetById(assetId);
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Asset card not found' });
@ -7721,14 +7597,8 @@ async function fileSizeOrNull(targetPath) {
}
}
function resolveComfySubPath(comfyPath, relativePath, modelsPath) {
function resolveComfySubPath(comfyPath, relativePath) {
const normalizedRelative = String(relativePath || '').replace(/^[/\\]+/, '');
if (modelsPath) {
const afterModels = normalizedRelative.replace(/^models[/\\]?/, '');
if (afterModels !== normalizedRelative) {
return path.join(modelsPath, afterModels);
}
}
return path.join(comfyPath, normalizedRelative);
}
@ -7768,7 +7638,7 @@ async function downloadFileWithProgress(url, destinationPath, onChunk) {
return { receivedBytes, totalBytes };
}
async function runSetupDownloads(jobId, comfyPath, files, modelsPath) {
async function runSetupDownloads(jobId, comfyPath, files) {
const totalExpectedBytes = files.reduce((sum, file) => sum + (Number(file.expectedBytes) || 0), 0);
let cumulativeCompletedBytes = 0;
@ -7785,7 +7655,7 @@ async function runSetupDownloads(jobId, comfyPath, files, modelsPath) {
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
const destinationPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir, file.fileName), modelsPath);
const destinationPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir, file.fileName));
try {
await fs.mkdir(path.dirname(destinationPath), { recursive: true });
@ -7903,13 +7773,10 @@ async function installSetupWorkflow(workflowConfig, diffusionModelFileName = '')
if (!sourceParameter) {
throw new Error(`Workflow "${workflowConfig.Name}": input ${parameterId} not found`);
}
const valueType = normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter));
parameters.push({
...sourceParameter,
name: sanitizeDisplayName(inputCfg.Name || sourceParameter.name, sourceParameter.name),
valueType,
// Optional "Enums": [...] in setup.json turns the field into a dropdown.
enums: normalizeComfyEnums(inputCfg.Enums, valueType)
valueType: normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter))
});
}
@ -8025,7 +7892,6 @@ app.get('/api/setup/config', async (req, res) => {
app.post('/api/setup/check-comfy-path', async (req, res) => {
try {
const comfyPath = String(req.body?.path || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
if (!comfyPath) {
return res.status(400).json({ error: 'A ComfyUI folder path is required' });
}
@ -8035,30 +7901,23 @@ app.post('/api/setup/check-comfy-path', async (req, res) => {
return res.status(400).json({ error: `Folder does not exist: ${comfyPath}` });
}
if (modelsPath) {
const modelsPathExists = await pathExists(modelsPath);
if (!modelsPathExists) {
return res.status(400).json({ error: `Models folder does not exist: ${modelsPath}` });
}
} else {
const modelsDir = path.join(comfyPath, 'models');
const modelsExist = await pathExists(modelsDir);
if (!modelsExist) {
return res.status(400).json({ error: `This does not look like a ComfyUI folder (missing "models" subfolder): ${comfyPath}` });
}
const modelsDir = path.join(comfyPath, 'models');
const modelsExist = await pathExists(modelsDir);
if (!modelsExist) {
return res.status(400).json({ error: `This does not look like a ComfyUI folder (missing "models" subfolder): ${comfyPath}` });
}
const config = await loadSetupConfig();
const created = [];
for (const relativePath of Object.values(config.ComfyUIPaths || {})) {
const target = resolveComfySubPath(comfyPath, relativePath, modelsPath);
const target = resolveComfySubPath(comfyPath, relativePath);
if (!(await pathExists(target))) {
await fs.mkdir(target, { recursive: true });
created.push(relativePath);
}
}
res.json({ ok: true, comfyPath, modelsPath, createdSubfolders: created });
res.json({ ok: true, comfyPath, createdSubfolders: created });
} catch (err) {
console.error('Failed to validate ComfyUI path:', err);
res.status(500).json({ error: err.message || 'Failed to validate ComfyUI path' });
@ -8068,7 +7927,6 @@ app.post('/api/setup/check-comfy-path', async (req, res) => {
app.post('/api/setup/check-files', async (req, res) => {
try {
const comfyPath = String(req.body?.comfyPath || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
const files = Array.isArray(req.body?.files) ? req.body.files : [];
if (!comfyPath) {
@ -8077,7 +7935,7 @@ app.post('/api/setup/check-files', async (req, res) => {
const results = [];
for (const file of files) {
const absPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir || '', file.fileName || ''), modelsPath);
const absPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir || '', file.fileName || ''));
const size = await fileSizeOrNull(absPath);
results.push({
relativeDir: file.relativeDir || '',
@ -8097,7 +7955,6 @@ app.post('/api/setup/check-files', async (req, res) => {
app.post('/api/setup/download', async (req, res) => {
try {
const comfyPath = String(req.body?.comfyPath || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
const files = Array.isArray(req.body?.files) ? req.body.files : [];
if (!comfyPath) {
@ -8113,7 +7970,7 @@ app.post('/api/setup/download', async (req, res) => {
const jobId = randomUUID();
getSetupDownloadJob(jobId);
runSetupDownloads(jobId, comfyPath, files, modelsPath).catch(err => {
runSetupDownloads(jobId, comfyPath, files).catch(err => {
console.error('[setup] download job crashed:', err);
publishSetupDownloadProgress(jobId, { status: 'error', error: err.message || String(err) });
});

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

@ -1,8 +1,7 @@
import { useEffect, useState } from 'react'
import { useState } from 'react'
import FolderBrowserDialog from './FolderBrowserDialog'
import {
EXPORT_FORMATS,
browseFolders,
exportObject3D,
isGlbUrl,
loadObject3DFromUrl,
@ -12,8 +11,6 @@ import {
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.
@ -34,15 +31,6 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
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
@ -115,7 +103,6 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
setProgress({ frac: 0.97, message: 'Writing files…' })
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}`)
} catch (err) {

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 = [
@ -183,48 +182,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 +536,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">

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

@ -14,7 +14,6 @@ import {
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).
@ -280,24 +279,6 @@ export default function BoardAiPanel({ projectId, projectName, boardId, onImageG
)
}
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}>

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">

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,
@ -88,12 +86,9 @@ export default function KanbanImageCard({
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard || isRiggingCard
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))
@ -119,28 +114,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 +148,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 +181,7 @@ export default function KanbanImageCard({
} : undefined}
>
{previewType === 'mesh' && previewUrl ? (
meshThumbnail ? (
asset.previewFilename ? (
<img
src={previewUrl}
alt={previewName}
@ -230,13 +213,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}
@ -604,12 +587,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 +600,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"

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

@ -590,9 +590,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()
}
@ -879,39 +878,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 +903,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(() => ({}))
@ -1353,8 +1318,6 @@ export function ProjectProvider({ children }) {
getPaintDocument,
savePaintDocument,
attachExistingAsset,
linkAssetToProject,
unlinkAssetFromProject,
resolveAssetSourceReference,
deleteAsset,
moveKanbanCard,

View file

@ -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,

View file

@ -8,11 +8,6 @@ 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
@ -79,8 +74,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 +92,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 +127,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 +454,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))
)]
@ -1112,17 +1097,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 +1664,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

@ -785,11 +785,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

@ -55,7 +55,6 @@ 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
@ -139,7 +138,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 +147,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 +237,6 @@ export default function KanbanPage() {
}
const openImageSourceMenu = (cardId = null) => {
setMeshDraft(null)
setImageDraft({ mode: 'select', cardId })
}
@ -499,9 +497,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 +508,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) {
@ -713,10 +709,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();
@ -1046,15 +1039,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 +1056,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 +1073,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 +1086,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 +1110,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 +1181,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 +1209,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 +1244,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 +1268,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 +1656,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, 6].includes(card.kanbanColumnId) && hasMeshAssets
if (!useMixedAssetCarousel) {
return []
@ -3011,18 +2993,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 +3008,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 +3047,6 @@ export default function KanbanPage() {
handleCardDragStart,
handleCardDragEnd,
openImageSourceMenu,
openMeshSourceMenu,
handleRemoveImageCard,
openMeshPreview,
handleRemoveImage,
@ -3219,16 +3187,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 +3332,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 +3432,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 +3489,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 +3547,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 +3582,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>
@ -3656,25 +3626,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,26 +23,6 @@ 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',

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,

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": "2.1.0",
"message": "Added Brainstorming Boards"
}