Mesh Thumnail is now generated with python-server -> MCP compatibility
This commit is contained in:
parent
cb7ca5ff91
commit
9c17e86a98
8 changed files with 513 additions and 7 deletions
|
|
@ -90,10 +90,28 @@ function startBackend() {
|
||||||
PORT: String(BACKEND_PORT),
|
PORT: String(BACKEND_PORT),
|
||||||
NODE_ENV: 'production',
|
NODE_ENV: 'production',
|
||||||
},
|
},
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
// 4th fd = IPC channel: lets the headless backend ask the main process to
|
||||||
|
// start a Python service on demand (e.g. to render a mesh thumbnail) —
|
||||||
|
// something it otherwise can't do (ensureService lives here, not there).
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
|
||||||
});
|
});
|
||||||
proc.stdout.pipe(out);
|
proc.stdout.pipe(out);
|
||||||
proc.stderr.pipe(out);
|
proc.stderr.pipe(out);
|
||||||
|
|
||||||
|
// Backend → main service requests. Reuses the same ensureService the Start
|
||||||
|
// buttons and on-demand UI path use (start + health wait + dedupe).
|
||||||
|
proc.on('message', async (msg) => {
|
||||||
|
if (!msg || msg.type !== 'services:ensure') return;
|
||||||
|
const { name, requestId } = msg;
|
||||||
|
let reply = { type: 'services:ensure:result', requestId };
|
||||||
|
try {
|
||||||
|
await ensureService(name);
|
||||||
|
reply.ok = true;
|
||||||
|
} catch (err) {
|
||||||
|
reply = { ...reply, ok: false, error: err?.message || String(err) };
|
||||||
|
}
|
||||||
|
try { proc.send(reply); } catch { /* backend gone */ }
|
||||||
|
});
|
||||||
proc.on('exit', (code, signal) => {
|
proc.on('exit', (code, signal) => {
|
||||||
log(`Backend exited (code=${code} signal=${signal})`);
|
log(`Backend exited (code=${code} signal=${signal})`);
|
||||||
if (!shuttingDown) {
|
if (!shuttingDown) {
|
||||||
|
|
@ -122,6 +140,38 @@ function waitForBackend(timeoutMs = 60000, intervalMs = 400) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fetch the app settings from the backend over HTTP (the backend owns the DB).
|
||||||
|
// Resolves null on any error — callers treat that as "no auto-start".
|
||||||
|
function fetchSettings(timeoutMs = 4000) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const req = http.get(`${BACKEND_ORIGIN}/api/settings`, (res) => {
|
||||||
|
if (res.statusCode !== 200) { res.resume(); return resolve(null); }
|
||||||
|
let body = '';
|
||||||
|
res.setEncoding('utf8');
|
||||||
|
res.on('data', (chunk) => { body += chunk; });
|
||||||
|
res.on('end', () => { try { resolve(JSON.parse(body)); } catch { resolve(null); } });
|
||||||
|
});
|
||||||
|
req.on('error', () => resolve(null));
|
||||||
|
req.setTimeout(timeoutMs, () => req.destroy());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start the services the user opted into auto-starting (Settings → Mesh Tools /
|
||||||
|
// Auto Rig). Non-blocking and best-effort: failures are logged, never fatal, and
|
||||||
|
// never delay the window. Setting key `rigtools` maps to service `rigging`.
|
||||||
|
async function autoStartServices() {
|
||||||
|
const settings = await fetchSettings();
|
||||||
|
const apis = settings?.apis || {};
|
||||||
|
const wanted = [
|
||||||
|
apis.meshtools?.autoStart ? 'meshtools' : null,
|
||||||
|
apis.rigtools?.autoStart ? 'rigging' : null,
|
||||||
|
].filter(Boolean);
|
||||||
|
for (const name of wanted) {
|
||||||
|
log(`Auto-starting ${name} service (enabled in Settings)`);
|
||||||
|
ensureService(name).catch((err) => log(`Auto-start of ${name} failed: ${err?.message || err}`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- On-demand Python service management ------------------------------------
|
// --- On-demand Python service management ------------------------------------
|
||||||
function serviceRegistry() {
|
function serviceRegistry() {
|
||||||
return {
|
return {
|
||||||
|
|
@ -369,6 +419,10 @@ async function boot() {
|
||||||
createWindow();
|
createWindow();
|
||||||
if (splash && !splash.isDestroyed()) splash.close();
|
if (splash && !splash.isDestroyed()) splash.close();
|
||||||
if (setupWindow && !setupWindow.isDestroyed()) setupWindow.close();
|
if (setupWindow && !setupWindow.isDestroyed()) setupWindow.close();
|
||||||
|
|
||||||
|
// Fire the opt-in service auto-starts AFTER the window is up so they never
|
||||||
|
// delay launch (fire-and-forget — each service reports its own readiness).
|
||||||
|
autoStartServices();
|
||||||
}
|
}
|
||||||
|
|
||||||
let didShutdown = false;
|
let didShutdown = false;
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,10 @@ MAX_UPLOAD_BYTES: int = _env_int("MESHTOOLS_MAX_UPLOAD_BYTES", 512 * 1024 * 1024
|
||||||
# import alone takes seconds and heavy scenes bake many animation takes.
|
# import alone takes seconds and heavy scenes bake many animation takes.
|
||||||
CONVERT_TIMEOUT_S: int = _env_int("MESHTOOLS_CONVERT_TIMEOUT", 600)
|
CONVERT_TIMEOUT_S: int = _env_int("MESHTOOLS_CONVERT_TIMEOUT", 600)
|
||||||
|
|
||||||
|
# Thumbnail render (headless Blender subprocess). Shorter than convert: a single
|
||||||
|
# low-sample Cycles-CPU render of one frame after the bpy import (~seconds).
|
||||||
|
THUMBNAIL_TIMEOUT_S: int = _env_int("MESHTOOLS_THUMBNAIL_TIMEOUT", 180)
|
||||||
|
|
||||||
# Scratch space for temp files when a tool needs real paths on disk
|
# Scratch space for temp files when a tool needs real paths on disk
|
||||||
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
|
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
|
||||||
WORK_DIR: Path = Path(
|
WORK_DIR: Path = Path(
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import queue
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
||||||
|
from fastapi.concurrency import run_in_threadpool
|
||||||
from fastapi.responses import StreamingResponse
|
from fastapi.responses import StreamingResponse
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
|
@ -33,6 +34,7 @@ from ..schemas import AutoRetopoOptions, AutoUvOptions, ConvertOptions, RepairOp
|
||||||
from ..services.auto_retopo import run_auto_retopo
|
from ..services.auto_retopo import run_auto_retopo
|
||||||
from ..services.auto_uv import run_auto_uv
|
from ..services.auto_uv import run_auto_uv
|
||||||
from ..services.convert_fbx import run_convert_fbx
|
from ..services.convert_fbx import run_convert_fbx
|
||||||
|
from ..services.mesh_thumbnail import render_mesh_thumbnail
|
||||||
from ..services.repair import run_repair
|
from ..services.repair import run_repair
|
||||||
|
|
||||||
router = APIRouter(prefix="/meshes", tags=["meshes"])
|
router = APIRouter(prefix="/meshes", tags=["meshes"])
|
||||||
|
|
@ -214,3 +216,21 @@ async def convert(
|
||||||
}
|
}
|
||||||
|
|
||||||
return _stream_payload(run, "Convert to FBX")
|
return _stream_payload(run, "Convert to FBX")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/thumbnail")
|
||||||
|
async def thumbnail(meshFile: UploadFile = File(...)) -> dict:
|
||||||
|
"""Render a GLB to a 512x512 PNG thumbnail (headless Blender subprocess).
|
||||||
|
|
||||||
|
Single-artifact endpoint (no SSE): returns plain JSON with the PNG base64 in
|
||||||
|
`preview_b64`. Used by the Node backend to give server-side-generated meshes
|
||||||
|
(ComfyUI / external-API, driven over MCP) a thumbnail — those never get the
|
||||||
|
browser's WebGL render. The render runs in a threadpool so the bpy subprocess
|
||||||
|
does not block the event loop.
|
||||||
|
"""
|
||||||
|
data = await _read_upload(meshFile)
|
||||||
|
try:
|
||||||
|
png = await run_in_threadpool(render_mesh_thumbnail, data)
|
||||||
|
except Exception as exc: # noqa: BLE001 — surface as a clean HTTP error
|
||||||
|
raise HTTPException(status_code=500, detail=f"Thumbnail render failed: {exc}") from exc
|
||||||
|
return {"preview_b64": base64.b64encode(png).decode("ascii")}
|
||||||
|
|
|
||||||
108
python-server/app/services/mesh_thumbnail.py
Normal file
108
python-server/app/services/mesh_thumbnail.py
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
"""GLB -> PNG thumbnail — subprocess driver for app/tools/thumbnail_worker.py.
|
||||||
|
|
||||||
|
The worker owns the actual Blender (bpy) render; this module only provisions a
|
||||||
|
job directory, spawns the worker with the venv's own interpreter, and returns
|
||||||
|
the PNG bytes.
|
||||||
|
|
||||||
|
bpy stays OUT of this process on purpose: it is not thread-safe, keeps ~1GB RSS
|
||||||
|
once imported, and a Blender crash must not take the API down. Renders are
|
||||||
|
serialized with a semaphore for the same reason (each subprocess peaks ~1-2GB).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from ..config import THUMBNAIL_TIMEOUT_S, WORK_DIR
|
||||||
|
|
||||||
|
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/tools/thumbnail_worker.py
|
||||||
|
|
||||||
|
_WORKER = Path(__file__).resolve().parents[1] / "tools" / "thumbnail_worker.py"
|
||||||
|
|
||||||
|
_render_lock = threading.Semaphore(1)
|
||||||
|
|
||||||
|
|
||||||
|
def render_mesh_thumbnail(glb_bytes: bytes) -> bytes:
|
||||||
|
"""Render a GLB to a 512x512 PNG thumbnail. Returns the PNG bytes; raises on
|
||||||
|
failure."""
|
||||||
|
job_dir = WORK_DIR / f"thumb-{uuid4().hex}"
|
||||||
|
job_dir.mkdir(parents=True)
|
||||||
|
try:
|
||||||
|
in_path = job_dir / "input.glb"
|
||||||
|
in_path.write_bytes(glb_bytes)
|
||||||
|
out_path = job_dir / "output.png"
|
||||||
|
|
||||||
|
with _render_lock:
|
||||||
|
result = _run_worker(in_path, out_path)
|
||||||
|
|
||||||
|
if not result.get("ok"):
|
||||||
|
raise RuntimeError(result.get("error") or "Thumbnail render failed.")
|
||||||
|
if not out_path.exists():
|
||||||
|
raise RuntimeError("Thumbnail worker reported success but produced no output file.")
|
||||||
|
return out_path.read_bytes()
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(job_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _run_worker(in_path: Path, out_path: Path) -> dict:
|
||||||
|
proc = subprocess.Popen(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
str(_WORKER),
|
||||||
|
"--input", str(in_path),
|
||||||
|
"--output", str(out_path),
|
||||||
|
],
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT,
|
||||||
|
text=True,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Watchdog instead of a read timeout: the stdout iteration below ends when
|
||||||
|
# the process dies, so killing it on expiry unblocks the loop too.
|
||||||
|
timed_out = threading.Event()
|
||||||
|
|
||||||
|
def _expire():
|
||||||
|
timed_out.set()
|
||||||
|
proc.kill()
|
||||||
|
|
||||||
|
watchdog = threading.Timer(THUMBNAIL_TIMEOUT_S, _expire)
|
||||||
|
watchdog.daemon = True
|
||||||
|
watchdog.start()
|
||||||
|
|
||||||
|
result: dict | None = None
|
||||||
|
tail: list[str] = [] # last non-protocol lines, for error context
|
||||||
|
try:
|
||||||
|
for line in proc.stdout:
|
||||||
|
if not line.startswith(SENTINEL):
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped:
|
||||||
|
tail.append(stripped)
|
||||||
|
del tail[:-8]
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
event = json.loads(line[len(SENTINEL):])
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
if event.get("type") == "result":
|
||||||
|
result = event
|
||||||
|
code = proc.wait()
|
||||||
|
finally:
|
||||||
|
watchdog.cancel()
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.kill()
|
||||||
|
|
||||||
|
if timed_out.is_set():
|
||||||
|
raise RuntimeError(f"Thumbnail render timed out after {THUMBNAIL_TIMEOUT_S}s.")
|
||||||
|
if result is None:
|
||||||
|
detail = f" Last output: {' | '.join(tail)}" if tail else ""
|
||||||
|
raise RuntimeError(f"Thumbnail worker exited (code {code}) without a result.{detail}")
|
||||||
|
return result
|
||||||
185
python-server/app/tools/thumbnail_worker.py
Normal file
185
python-server/app/tools/thumbnail_worker.py
Normal file
|
|
@ -0,0 +1,185 @@
|
||||||
|
"""GLB -> PNG thumbnail worker (headless Blender).
|
||||||
|
|
||||||
|
Runs `bpy` in ISOLATION: invoked as a subprocess by app/services/mesh_thumbnail.py
|
||||||
|
(`python thumbnail_worker.py --input in.glb --output out.png`). Never import this
|
||||||
|
module from the service — bpy is not thread-safe, holds ~1GB RSS once imported,
|
||||||
|
and a crash inside Blender must not take the API down.
|
||||||
|
|
||||||
|
Why a server-side render at all: mesh thumbnails are normally rendered in the
|
||||||
|
browser (src/utils/meshThumbnail.js, WebGL). Meshes created without a browser
|
||||||
|
(ComfyUI workflows / external-API generation driven over MCP) never get one, so
|
||||||
|
the app shows an empty image. This renders one headlessly instead.
|
||||||
|
|
||||||
|
Engine choice: Cycles on the CPU. Cycles needs no GL/display context, so it
|
||||||
|
renders reliably headless on every platform (EEVEE/Workbench depend on an
|
||||||
|
OpenGL context that is often absent on servers). Low samples keep a 512px frame
|
||||||
|
to ~1-3s. The framing/lighting mirrors the client renderer so thumbnails look
|
||||||
|
consistent: dark background, a 3/4 camera, key + fill + rim lights.
|
||||||
|
|
||||||
|
Protocol: progress/result JSON lines on stdout prefixed with GENSTUDIO_EVT (bpy
|
||||||
|
prints its own "Info:" noise, the parent ignores non-matching lines).
|
||||||
|
Exit codes: 0 ok, 2 render error, 4 bpy missing.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
|
||||||
|
SENTINEL = "GENSTUDIO_EVT " # keep in sync with app/services/mesh_thumbnail.py
|
||||||
|
|
||||||
|
RESOLUTION = 512
|
||||||
|
SAMPLES = 24
|
||||||
|
CAMERA_FOV_DEG = 35.0
|
||||||
|
# Camera direction (Blender is Z-up; the glTF importer puts model front toward
|
||||||
|
# -Y). A 3/4 view from front-right-above, matching the client's angle.
|
||||||
|
CAMERA_DIR = (0.9, -1.0, 0.7)
|
||||||
|
# Neutral world colour used only for soft ambient fill (never shown — the film
|
||||||
|
# is transparent). Blender colour inputs are linear.
|
||||||
|
AMBIENT_COLOR = (0.09, 0.095, 0.11)
|
||||||
|
|
||||||
|
|
||||||
|
def emit(obj: dict) -> None:
|
||||||
|
sys.stdout.write(SENTINEL + json.dumps(obj, separators=(",", ":")) + "\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def progress(stage: str, frac: float, message: str = "") -> None:
|
||||||
|
emit({"type": "progress", "stage": stage, "frac": round(float(frac), 4), "message": message})
|
||||||
|
|
||||||
|
|
||||||
|
def fail(error: str, code: int) -> None:
|
||||||
|
emit({"type": "result", "ok": False, "error": error})
|
||||||
|
sys.exit(code)
|
||||||
|
|
||||||
|
|
||||||
|
def _scene_bounds(objects):
|
||||||
|
"""World-space (min, max) corners over every mesh object's bounding box."""
|
||||||
|
from mathutils import Vector
|
||||||
|
|
||||||
|
lo = Vector((math.inf, math.inf, math.inf))
|
||||||
|
hi = Vector((-math.inf, -math.inf, -math.inf))
|
||||||
|
found = False
|
||||||
|
for obj in objects:
|
||||||
|
if obj.type != "MESH":
|
||||||
|
continue
|
||||||
|
found = True
|
||||||
|
for corner in obj.bound_box:
|
||||||
|
world = obj.matrix_world @ Vector(corner)
|
||||||
|
lo = Vector((min(lo.x, world.x), min(lo.y, world.y), min(lo.z, world.z)))
|
||||||
|
hi = Vector((max(hi.x, world.x), max(hi.y, world.y), max(hi.z, world.z)))
|
||||||
|
if not found:
|
||||||
|
return None
|
||||||
|
return lo, hi
|
||||||
|
|
||||||
|
|
||||||
|
def _add_sun(name, direction, energy):
|
||||||
|
import bpy
|
||||||
|
from mathutils import Vector
|
||||||
|
|
||||||
|
data = bpy.data.lights.new(name=name, type="SUN")
|
||||||
|
data.energy = energy
|
||||||
|
obj = bpy.data.objects.new(name=name, object_data=data)
|
||||||
|
bpy.context.scene.collection.objects.link(obj)
|
||||||
|
# A sun's rays travel along its local -Z; aim that at `direction`.
|
||||||
|
obj.rotation_euler = Vector(direction).normalized().to_track_quat("-Z", "Y").to_euler()
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
def render(input_path: str, output_path: str) -> None:
|
||||||
|
import bpy
|
||||||
|
from mathutils import Vector
|
||||||
|
|
||||||
|
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||||
|
scene = bpy.context.scene
|
||||||
|
|
||||||
|
progress("import", 0.2, "Importing GLB…")
|
||||||
|
# TEMPERANCE: the default bone heuristic spawns an Icosphere widget mesh for
|
||||||
|
# rigged meshes that would pollute the framing; TEMPERANCE only orients bones.
|
||||||
|
bpy.ops.import_scene.gltf(filepath=input_path, bone_heuristic="TEMPERANCE")
|
||||||
|
|
||||||
|
objects = list(scene.objects)
|
||||||
|
bounds = _scene_bounds(objects)
|
||||||
|
if bounds is None:
|
||||||
|
raise RuntimeError("The GLB contains no mesh geometry to render.")
|
||||||
|
lo, hi = bounds
|
||||||
|
center = (lo + hi) * 0.5
|
||||||
|
size = hi - lo
|
||||||
|
max_dim = max(size.x, size.y, size.z, 1e-4)
|
||||||
|
|
||||||
|
progress("camera", 0.4, "Framing camera…")
|
||||||
|
cam_data = bpy.data.cameras.new("thumb_cam")
|
||||||
|
cam_data.angle = math.radians(CAMERA_FOV_DEG)
|
||||||
|
cam_obj = bpy.data.objects.new("thumb_cam", cam_data)
|
||||||
|
scene.collection.objects.link(cam_obj)
|
||||||
|
scene.camera = cam_obj
|
||||||
|
|
||||||
|
direction = Vector(CAMERA_DIR).normalized()
|
||||||
|
distance = max_dim * 2.2
|
||||||
|
cam_obj.location = center + direction * distance
|
||||||
|
# Camera looks down its local -Z with +Y up.
|
||||||
|
cam_obj.rotation_euler = (-direction).to_track_quat("-Z", "Y").to_euler()
|
||||||
|
|
||||||
|
# Lights: a soft ambient world plus key/fill/rim suns (mirrors the client's
|
||||||
|
# ambient + key + rim setup).
|
||||||
|
world = bpy.data.worlds.new("thumb_world")
|
||||||
|
scene.world = world
|
||||||
|
world.use_nodes = True
|
||||||
|
bg = world.node_tree.nodes.get("Background")
|
||||||
|
if bg is not None:
|
||||||
|
bg.inputs[0].default_value = (*AMBIENT_COLOR, 1.0)
|
||||||
|
bg.inputs[1].default_value = 1.1 # ambient strength
|
||||||
|
_add_sun("key", (-0.5, 0.8, -1.0), 4.0)
|
||||||
|
_add_sun("fill", (0.9, 0.4, -0.6), 1.6)
|
||||||
|
_add_sun("rim", (0.4, -0.9, 0.5), 2.2)
|
||||||
|
|
||||||
|
progress("render", 0.6, "Rendering thumbnail…")
|
||||||
|
scene.render.engine = "CYCLES"
|
||||||
|
scene.cycles.device = "CPU"
|
||||||
|
scene.cycles.samples = SAMPLES
|
||||||
|
scene.cycles.use_denoising = True
|
||||||
|
scene.render.resolution_x = RESOLUTION
|
||||||
|
scene.render.resolution_y = RESOLUTION
|
||||||
|
scene.render.resolution_percentage = 100
|
||||||
|
# Transparent background (RGBA): the model composites cleanly over the app's
|
||||||
|
# dark cards, and it avoids the version-specific Blender compositor API. The
|
||||||
|
# world stays bright for ambient fill but is not shown.
|
||||||
|
scene.render.film_transparent = True
|
||||||
|
scene.render.image_settings.file_format = "PNG"
|
||||||
|
scene.render.image_settings.color_mode = "RGBA"
|
||||||
|
scene.render.filepath = output_path
|
||||||
|
# Match the client's plain-sRGB output: Blender's default AgX/Filmic view
|
||||||
|
# transform lifts darks and shifts colours. "Standard" keeps colours
|
||||||
|
# as-authored so thumbnails look like the in-app WebGL renders.
|
||||||
|
try:
|
||||||
|
scene.view_settings.view_transform = "Standard"
|
||||||
|
except TypeError: # build may name it differently — non-fatal
|
||||||
|
pass
|
||||||
|
bpy.ops.render.render(write_still=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--input", required=True, help="Source .glb path")
|
||||||
|
parser.add_argument("--output", required=True, help="Destination .png path")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
try:
|
||||||
|
import bpy # noqa: F401 — probe only; used inside render()
|
||||||
|
except ImportError as exc:
|
||||||
|
fail(f"bpy is not installed in this environment: {exc}", 4)
|
||||||
|
|
||||||
|
try:
|
||||||
|
render(args.input, args.output)
|
||||||
|
except Exception as exc: # noqa: BLE001 — everything must surface to the parent
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
traceback.print_exc()
|
||||||
|
fail(f"{type(exc).__name__}: {exc}", 2)
|
||||||
|
else:
|
||||||
|
emit({"type": "result", "ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
105
server.js
105
server.js
|
|
@ -2661,6 +2661,92 @@ async function downloadPreviewThumbnail(previewImageUrl, baseName = 'mesh') {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ask the Electron main process (desktop app only) to start a Python service on
|
||||||
|
// demand. The backend runs as a separate process with an IPC channel to main
|
||||||
|
// (electron/main.cjs startBackend); outside the desktop app `process.send` is
|
||||||
|
// undefined and this is a no-op. Best-effort: resolves true when the service is
|
||||||
|
// confirmed running, false otherwise (timeout / not desktop / start failed).
|
||||||
|
const pendingServiceEnsures = new Map();
|
||||||
|
if (typeof process.send === 'function') {
|
||||||
|
process.on('message', (msg) => {
|
||||||
|
if (!msg || msg.type !== 'services:ensure:result') return;
|
||||||
|
const pending = pendingServiceEnsures.get(msg.requestId);
|
||||||
|
if (!pending) return;
|
||||||
|
pendingServiceEnsures.delete(msg.requestId);
|
||||||
|
clearTimeout(pending.timer);
|
||||||
|
pending.resolve(Boolean(msg.ok));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureDesktopService(name, { timeoutMs = 120000 } = {}) {
|
||||||
|
if (typeof process.send !== 'function') return Promise.resolve(false);
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const requestId = randomUUID();
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
pendingServiceEnsures.delete(requestId);
|
||||||
|
resolve(false);
|
||||||
|
}, timeoutMs);
|
||||||
|
pendingServiceEnsures.set(requestId, { resolve, timer });
|
||||||
|
try {
|
||||||
|
process.send({ type: 'services:ensure', name, requestId });
|
||||||
|
} catch {
|
||||||
|
pendingServiceEnsures.delete(requestId);
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render a mesh thumbnail headlessly via the Python mesh-tools service (:8200),
|
||||||
|
// which runs a Blender subprocess (see app/routes/meshes.py /meshes/thumbnail).
|
||||||
|
// Meshes generated without a browser (ComfyUI / external API over MCP) have no
|
||||||
|
// client-side WebGL thumbnail; this is the fallback when there is no provider
|
||||||
|
// cover to use. Returns the stored thumbnail filename, or null on any failure —
|
||||||
|
// the render is best-effort and must never fail mesh generation (e.g. when the
|
||||||
|
// mesh-tools service is not installed or running).
|
||||||
|
async function renderMeshThumbnailViaService(buffer, baseName = 'mesh') {
|
||||||
|
if (!buffer?.length) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// In the desktop app, start the mesh-tools service on demand if it isn't
|
||||||
|
// running (best-effort — proceed regardless; a stopped service just yields
|
||||||
|
// no thumbnail, as before).
|
||||||
|
await ensureDesktopService('meshtools');
|
||||||
|
|
||||||
|
const settings = await getSettings();
|
||||||
|
const baseUrl = buildMeshToolsBaseUrl(settings);
|
||||||
|
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('meshFile', new Blob([buffer], { type: 'model/gltf-binary' }), 'mesh.glb');
|
||||||
|
|
||||||
|
const response = await fetch(`${baseUrl}/meshes/thumbnail`, { method: 'POST', body: form });
|
||||||
|
if (!response.ok) return null;
|
||||||
|
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
const pngBuffer = data?.preview_b64 ? Buffer.from(data.preview_b64, 'base64') : null;
|
||||||
|
if (!pngBuffer?.length) return null;
|
||||||
|
|
||||||
|
const thumbnailFilename = createLibraryThumbnailFilename(baseName);
|
||||||
|
const absoluteThumbnailPath = toAbsoluteStoragePath(toStoredThumbnailPath(thumbnailFilename));
|
||||||
|
await fs.mkdir(path.dirname(absoluteThumbnailPath), { recursive: true });
|
||||||
|
await fs.writeFile(absoluteThumbnailPath, pngBuffer);
|
||||||
|
return thumbnailFilename;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Failed to render mesh thumbnail via service:', err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve a thumbnail for a generated mesh: prefer the provider's own cover
|
||||||
|
// render (free, always available for the external APIs), else fall back to a
|
||||||
|
// headless Blender render (covers ComfyUI meshes, which have no cover). Returns
|
||||||
|
// the stored thumbnail filename, or null when neither is available.
|
||||||
|
async function resolveMeshThumbnailFilename({ buffer, previewImageUrl, baseName = 'mesh' }) {
|
||||||
|
const cover = await downloadPreviewThumbnail(previewImageUrl, baseName);
|
||||||
|
if (cover) return cover;
|
||||||
|
return renderMeshThumbnailViaService(buffer, baseName);
|
||||||
|
}
|
||||||
|
|
||||||
async function saveGeneratedMeshAssets({
|
async function saveGeneratedMeshAssets({
|
||||||
projectId,
|
projectId,
|
||||||
name,
|
name,
|
||||||
|
|
@ -2701,8 +2787,13 @@ async function saveGeneratedMeshAssets({
|
||||||
};
|
};
|
||||||
|
|
||||||
// Meshes have no client-side thumbnail on the headless generation path, so
|
// Meshes have no client-side thumbnail on the headless generation path, so
|
||||||
// store the provider's cover render as the thumbnail (best-effort).
|
// use the provider's cover render, falling back to a headless Blender render
|
||||||
const thumbnailFilename = await downloadPreviewThumbnail(downloadedFile.previewImageUrl, assetPayload.name);
|
// when there is no cover (best-effort).
|
||||||
|
const thumbnailFilename = await resolveMeshThumbnailFilename({
|
||||||
|
buffer: downloadedFile.buffer,
|
||||||
|
previewImageUrl: downloadedFile.previewImageUrl,
|
||||||
|
baseName: assetPayload.name
|
||||||
|
});
|
||||||
|
|
||||||
// When the mesh was edited from a connected mesh, save it as a version (child)
|
// 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.
|
// of that mesh instead of creating a new root asset.
|
||||||
|
|
@ -3697,11 +3788,17 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
|
||||||
await fs.mkdir(path.dirname(absoluteFilePath), { recursive: true });
|
await fs.mkdir(path.dirname(absoluteFilePath), { recursive: true });
|
||||||
await fs.writeFile(absoluteFilePath, downloadedFile.buffer);
|
await fs.writeFile(absoluteFilePath, downloadedFile.buffer);
|
||||||
|
|
||||||
|
// ComfyUI returns no cover image, so headless mesh outputs have no
|
||||||
|
// thumbnail — render one via the mesh-tools service (best-effort).
|
||||||
|
const meshThumbnailFilename = inferredAssetType === 'mesh'
|
||||||
|
? await renderMeshThumbnailViaService(downloadedFile.buffer, generatedAssetPayload.name)
|
||||||
|
: null;
|
||||||
|
|
||||||
// When a mesh output was edited from a connected mesh, store it as a
|
// When a mesh output was edited from a connected mesh, store it as a
|
||||||
// version (child) of that mesh instead of creating a new root asset.
|
// version (child) of that mesh instead of creating a new root asset.
|
||||||
const persistedAsset = (normalizedParentAssetId && inferredAssetType === 'mesh')
|
const persistedAsset = (normalizedParentAssetId && inferredAssetType === 'mesh')
|
||||||
? await createAssetVersion({ assetId: normalizedParentAssetId, ...generatedAssetPayload, inheritThumbnail: false })
|
? await createAssetVersion({ assetId: normalizedParentAssetId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false })
|
||||||
: await createProjectAsset(generatedAssetPayload);
|
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename });
|
||||||
generatedAssets.push({
|
generatedAssets.push({
|
||||||
...persistedAsset,
|
...persistedAsset,
|
||||||
url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`,
|
url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`,
|
||||||
|
|
|
||||||
|
|
@ -87,6 +87,23 @@ function ServiceControl({ name }) {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Desktop-only: opt a service into starting automatically when the app launches
|
||||||
|
// (the main process reads this setting on boot). Renders nothing outside the
|
||||||
|
// desktop app, where services are launched externally.
|
||||||
|
function AutoStartToggle({ checked, onChange, warning }) {
|
||||||
|
const isDesktop = typeof window !== 'undefined' && !!window.genStudioServices?.isDesktop
|
||||||
|
if (!isDesktop) return null
|
||||||
|
return (
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5em', marginTop: '10px', cursor: 'pointer' }}>
|
||||||
|
<input type="checkbox" checked={!!checked} onChange={e => onChange(e.target.checked)} />
|
||||||
|
<span className="settings-helper-text" style={{ margin: 0 }}>
|
||||||
|
Start automatically when the app launches
|
||||||
|
{warning ? ' (keeps ~14 GB of GPU memory in use the whole session)' : ''}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Desktop-only: install the (opt-in) rigging service after first run — for users
|
// Desktop-only: install the (opt-in) rigging service after first run — for users
|
||||||
// who upgraded, skipped it on the setup screen, or later added a GPU. Drives the
|
// who upgraded, skipped it on the setup screen, or later added a GPU. Drives the
|
||||||
// same uv provisioning as the first-run window via the genStudioSetup bridge and
|
// same uv provisioning as the first-run window via the genStudioSetup bridge and
|
||||||
|
|
@ -640,6 +657,13 @@ export default function SettingsModal({ onClose }) {
|
||||||
stop it here. Outside the desktop app, start it from python-server/run.
|
stop it here. Outside the desktop app, start it from python-server/run.
|
||||||
</p>
|
</p>
|
||||||
<ServiceControl name="meshtools" />
|
<ServiceControl name="meshtools" />
|
||||||
|
<AutoStartToggle
|
||||||
|
checked={localSettings?.apis?.meshtools?.autoStart}
|
||||||
|
onChange={v => setLocalSettings(prev => ({
|
||||||
|
...prev,
|
||||||
|
apis: { ...prev?.apis, meshtools: { ...prev?.apis?.meshtools, autoStart: v } }
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h3 className="settings-section-title font-label">Rigging (Python) Connection</h3>
|
<h3 className="settings-section-title font-label">Rigging (Python) Connection</h3>
|
||||||
|
|
@ -698,6 +722,14 @@ export default function SettingsModal({ onClose }) {
|
||||||
</p>
|
</p>
|
||||||
<RiggingInstaller />
|
<RiggingInstaller />
|
||||||
<ServiceControl name="rigging" />
|
<ServiceControl name="rigging" />
|
||||||
|
<AutoStartToggle
|
||||||
|
warning
|
||||||
|
checked={localSettings?.apis?.rigtools?.autoStart}
|
||||||
|
onChange={v => setLocalSettings(prev => ({
|
||||||
|
...prev,
|
||||||
|
apis: { ...prev?.apis, rigtools: { ...prev?.apis?.rigtools, autoStart: v } }
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
10
storage.js
10
storage.js
|
|
@ -181,11 +181,17 @@ export const DEFAULT_SETTINGS = {
|
||||||
},
|
},
|
||||||
meshtools: {
|
meshtools: {
|
||||||
url: 'http://127.0.0.1',
|
url: 'http://127.0.0.1',
|
||||||
port: '8200'
|
port: '8200',
|
||||||
|
// Desktop app: start this service automatically at launch (default off —
|
||||||
|
// services otherwise start on demand or from Settings).
|
||||||
|
autoStart: false
|
||||||
},
|
},
|
||||||
rigtools: {
|
rigtools: {
|
||||||
url: 'http://127.0.0.1',
|
url: 'http://127.0.0.1',
|
||||||
port: '8300'
|
port: '8300',
|
||||||
|
// Desktop app: start the rigging service at launch. Default off — it pins
|
||||||
|
// ~14GB of GPU memory for the whole session.
|
||||||
|
autoStart: false
|
||||||
},
|
},
|
||||||
custom: []
|
custom: []
|
||||||
},
|
},
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue