Type a motion, watch a rigged character perform it: fast video model + GVHMR + live Mixamo retargeting
JavaScript
Studio stage, cinematic camera, character swap, Blender renderer
blendi-remade39c6ae44c3f0
diff --git a/.gitignore b/.gitignoreindex caeb919..7c398d1 100644--- a/.gitignore+++ b/.gitignore@@ -15,3 +15,7 @@ vendor/node_modules/__pycache__/.DS_Store++# exported takes and Blender renders+takes/+renders/diff --git a/README.md b/README.mdindex 6f4180d..9c84509 100644--- a/README.md+++ b/README.md@@ -28,7 +28,7 @@ flowchart LRThe live pass hides the wait; the HQ pass is the real result. GVHMR sees the whole clip at once, outputs joint *rotations* on a fixed-proportion body, and recovers a gravity-aware root path — so there's no jitter, limb stretching, or twisted forearms.-+## Quick start@@ -57,18 +57,33 @@ hq\.venv\Scripts\python hq\worker.py # → 127.0.0.1:5178, loads once and sta- **Generate** a prompt or click a preset. By default every clip starts from the same flux-generated *performer* (one person, full body, plain backdrop, static camera — ideal pose-estimation input).- **Video model** — *H3 Max Turbo* for the snappiest loop and Stream mode; *FLUX 3 Max* for more realistic motion (best for single takes — at ~9s per 5s clip it can't keep a chained stream fed yet).- **Character** — X Bot, Michelle or Soldier (textured Mixamo rigs from the three.js examples), or **Load Mixamo file…** for any Mixamo `.fbx`/`.glb` (download from [mixamo.com](https://www.mixamo.com), T-pose).+- **Swap character every loop** — X Bot → Michelle → Soldier, cutting on each loop (or each new clip in Stream mode). The motion lives on one hidden driver rig; the character on stage copies its pose, so swapping is instant.+- **Cinematic camera** — slow arc and push-in around the performer on a studio stage (environment lighting, warm key + cool rim, soft reflective floor, contact shadows). Drag to take over; it resumes after a few seconds.- **Orientation** — portrait 9:16 (default) or landscape 16:9. Portrait gives the performer ~70% more pixels of height at 480P, which helps pose estimation.- **Stream mode** — one continuous performance: each clip continues from the previous clip's last frame, plays once its HQ motion is ready while the next one generates, and short idle clips fill gaps between prompts. First motion ≈ 6s after the first prompt, continuous after that.-- **⬇ GLB** on any take exports the skinned character with the animation clip (Blender, Unity, three.js).+- **⬇ GLB** on any take exports the skinned character with the animation clip (Blender, Unity, three.js), and keeps a copy plus the source-clip URL in `takes/`.+- **Prompts that retarget well** face the camera with limbs clear of the body — dance, boxing, golf/basketball mimes, celebrations, kata. Flips, spins, floor work and crossed or hidden arms confuse any monocular pose estimator. The presets and the prompt template steer toward this.- **Use a video file…** runs the live pass on your own footage.+## Blender renders++Turn any saved take into a polished clip — studio cyclorama, three-point lighting, slow camera arc — headlessly:++```powershell+& "C:\Program Files\Blender Foundation\Blender 5.2lender.exe" -b -P tools/render_blender.py -- takes/<take>.glb --side-by-side+```++Writes `renders/<take>.mp4` (1080×1920 by default, `--res 1920x1080` for landscape) and, with `--side-by-side`, `renders/<take>_compare.mp4` with the generated source clip next to the render. Pass several `.glb` files to place characters side by side; `--preview` renders a quick low-res draft.+## Project layout| Path | ||---|---|| `server.mjs` | zero-dependency server; proxies fal (key stays server-side) and the HQ worker || `public/app.js` | UI, generation queue, live pose loop, playback & blending, stream mode, GLB export |-| `public/retarget.js` | Mixamo rig wrapper: MediaPipe landmarks → bones, SMPL rotations → bones, grounding |+| `public/stage.js` | studio stage: lighting, reflective floor, contact shadows, cinematic camera |+| `public/retarget.js` | Mixamo rig wrapper: MediaPipe landmarks → bones, SMPL rotations → bones, rig-to-rig pose copy, grounding |+| `tools/render_blender.py` | headless Blender (5.x) renderer for exported takes || `hq/worker.py` | FastAPI worker around the `gvhmr` package, tuned for single-person generated clips |<details>diff --git a/docs/app.jpg b/docs/app.jpgnew file mode 100644index 0000000..8eb6367Binary files /dev/null and b/docs/app.jpg differdiff --git a/docs/app.png b/docs/app.pngdeleted file mode 100644index 8480a08..0000000Binary files a/docs/app.png and /dev/null differdiff --git a/public/app.js b/public/app.jsindex 6e93cae..2850290 100644--- a/public/app.js+++ b/public/app.js@@ -1,11 +1,11 @@// Prompt2Rig — prompt → H3 Max Turbo video → live pose (MediaPipe) → Mixamo rig,// with an optional GVHMR "HQ" pass on the local GPU that swaps in when ready.import * as THREE from 'three';-import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';import { FilesetResolver, PoseLandmarker, DrawingUtils } from '@mediapipe/tasks-vision';+import { createStage } from './stage.js';import { Rig, OneEuro, Track, trackToClip, blendSnapshots, smplGlobals, aaToQuat } from './retarget.js';const $ = (s) => document.querySelector(s);@@ -26,15 +26,20 @@ const PERFORMER_PROMPT ='with empty space above the head and below the feet, the person is centered. Plain seamless ' +'light-grey studio backdrop and floor, flat even soft lighting, sharp focus, 35mm photo.';+// Presets chosen to retarget cleanly: facing the camera, limbs clearly separated from the body.+// Avoid flips, spins, floor work and arms crossing/hiding behind the torso — pose estimators+// lose track of which limb is which, and the error shows on the rig.const PRESETS = [- 'does an energetic hip hop dance with big arm movements',- 'throws a fast boxing combo of jabs, hooks and an uppercut',+ 'does an energetic hip hop dance with wide, open arm movements',+ 'throws boxing jabs and hooks toward the camera','does jumping jacks',- 'walks in a small circle and waves at the camera',- 'does a shuffling zombie walk with arms stretched forward',- 'celebrates a victory, jumping and pumping both fists',- 'does a slow tai chi sequence',- 'does a high spinning kick',+ 'mimes a full golf swing',+ 'shoots an imaginary basketball jump shot',+ 'celebrates a victory, jumping and pumping both fists in the air',+ 'does a stiff zombie walk in place with arms stretched forward',+ 'does a karate kata with straight punches and front kicks',+ 'waves hello with both arms, then takes a bow',+ 'does a big superhero landing pose, then stands up proudly',];const IDLE_PROMPT = 'stands in place in a relaxed idle pose, breathing and gently shifting weight from foot to foot';@@ -43,15 +48,18 @@ const MAX_IDLE_STREAK = 3;const chainOn = () => settings.chain || settings.stream;const waitOn = () => settings.hq && hqOnline && (settings.waitHq || settings.stream);+// Shared staging that keeps clips easy to read for pose estimation.+const STAGING = 'They stay roughly in place facing the camera, with both arms clearly visible and held away from the torso, no turning around, no flips. ' ++ 'Their entire body, including both feet, stays visible in frame the whole time. Static locked-off camera, no camera movement, no zoom, no cuts.';const videoPrompt = (action, fromImage) => fromImage- ? `The person ${action}. They perform the full motion while their entire body, including both feet, stays visible in frame the whole time. Static locked-off camera, no camera movement, no zoom, no cuts. Plain studio background.`- : `Wide full-body shot of one person wearing a plain grey t-shirt and dark pants in an empty light-grey studio. The person ${action}. Entire body including feet visible at all times. Static locked-off camera, no camera movement, no cuts.`;+ ? `The person ${action}. ${STAGING} Plain studio background.`+ : `Wide full-body shot of one person wearing a plain grey t-shirt and dark pants in an empty light-grey studio. The person ${action}. ${STAGING}`;// ---- settings ------------------------------------------------------------------const DEFAULTS = {stream: false, source: 'performer', chain: false, duration: 5, resolution: '480P', hq: true, waitHq: false,rootMotion: true, poseModel: 'heavy', smoothing: 0.5, showSkel: true, orientation: 'portrait', performerUrls: {},- character: 'xbot', videoModel: 'h3',+ character: 'xbot', videoModel: 'h3', swap: false, cinematic: false,};const settings = (() => { try { return { ...DEFAULTS, ...JSON.parse(localStorage.getItem('p2r') || '{}') }; } catch { return { ...DEFAULTS }; } })();const save = () => { try { localStorage.setItem('p2r', JSON.stringify(settings)); } catch {} };@@ -84,47 +92,18 @@ async function api(path, body) {}// ---- three.js stage --------------------------------------------------------------const stage = $('#stage');-const renderer = new THREE.WebGLRenderer({ antialias: true });-renderer.setPixelRatio(Math.min(2, devicePixelRatio));-renderer.shadowMap.enabled = true;-renderer.shadowMap.type = THREE.PCFSoftShadowMap;-renderer.outputColorSpace = THREE.SRGBColorSpace;-stage.appendChild(renderer.domElement);--const scene = new THREE.Scene();-scene.background = new THREE.Color(0x15171a);-scene.fog = new THREE.Fog(0x15171a, 8, 22);-const camera = new THREE.PerspectiveCamera(35, 1, 0.05, 100);-camera.position.set(0.6, 1.5, 5.2);-const controls = new OrbitControls(camera, renderer.domElement);-controls.target.set(0, 0.95, 0);-controls.enableDamping = true;--scene.add(new THREE.HemisphereLight(0xdfe6ff, 0x1a1c20, 1.6));-const sun = new THREE.DirectionalLight(0xffffff, 2.2);-sun.position.set(2.5, 5, 3.5); sun.castShadow = true;-sun.shadow.mapSize.set(2048, 2048);-Object.assign(sun.shadow.camera, { left: -3, right: 3, top: 3, bottom: -3, near: 0.5, far: 15 });-scene.add(sun);-const floor = new THREE.Mesh(new THREE.PlaneGeometry(60, 60), new THREE.MeshStandardMaterial({ color: 0x1f2226, roughness: 1 }));-floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);-const grid = new THREE.GridHelper(60, 120, 0x3a3f46, 0x2a2e33); grid.position.y = 0.002; scene.add(grid);--function resize() {- const { clientWidth: w, clientHeight: h } = stage;- renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix();-}-new ResizeObserver(resize).observe(stage);+const stage = createStage($('#stage'));+const { scene } = stage;+// Keep the characters centered in the part of the stage the video panel doesn't cover.+new ResizeObserver(() => { const v = $('#vidwrap'); stage.setInset(v.offsetLeft + v.offsetWidth); }).observe($('#vidwrap'));// ---- character --------------------------------------------------------------------let model = null, rig = null;-async function loadCharacter(src, name = 'X Bot') {- pill('rig', 'loading ' + name, 'busy');+/** Load a Mixamo character: scaled to meters, facing +Z, centered with feet on y=0. */+async function loadModel(src, name) {const isFbx = /\.fbx$/i.test(name);- const loader = isFbx ? new FBXLoader() : new GLTFLoader();- const obj = await loader.loadAsync(src);+ const obj = await (isFbx ? new FBXLoader() : new GLTFLoader()).loadAsync(src);const root = isFbx ? obj : obj.scene;if (isFbx) root.scale.setScalar(0.01); // Mixamo FBX is in centimetersroot.updateMatrixWorld(true);@@ -139,18 +118,61 @@ async function loadCharacter(src, name = 'X Bot') {root.position.y -= box.min.y;root.position.x -= (box.min.x + box.max.x) / 2;root.position.z -= (box.min.z + box.max.z) / 2;- root.name = 'Character';root.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.frustumCulled = false; } });root.updateMatrixWorld(true);+ return root;+}++async function loadCharacter(src, name = 'X Bot') {+ pill('rig', 'loading ' + name, 'busy');+ const root = await loadModel(src, name);+ root.name = 'Character';const newRig = new Rig(root);- if (model) scene.remove(model);- scene.add(root); model = root; rig = newRig;+ if (model) { scene.remove(model); stage.removeContactShadow(model); }+ scene.add(root); stage.contactShadow(root); model = root; rig = newRig;// Takes store bone-order-specific data; re-bake HQ data for the new skeleton.for (const t of takes) { t.live = new Track(rig.order.length); t.liveDone = false; if (t.hqRaw) t.hq = bakeSmpl(t.hqRaw); }liveState ||= { hip0: null, baseY: null, mpp: null, scale: null };liveSnap = null; switchFrom = null;pill('rig', name, 'ok');log(`character: ${name} (${rig.order.length} bones, ${rig.height.toFixed(2)} m)`);+ resetCast();+}++// ---- character swap: one character at a time, the next one takes over on every loop -------------+// The selected character stays the hidden "driver" that takes are baked for; whichever character+// is on stage copies its pose each frame, so swapping never needs a re-bake.+const cast = {}; // key → { model, rig } for the non-driver characters, loaded on demand+let onStage = null; // key of the character currently visible (null = the driver itself)++function resetCast() {+ for (const k of Object.keys(cast)) { scene.remove(cast[k].model); stage.removeContactShadow(cast[k].model); delete cast[k]; }+ onStage = null;+ if (model) model.visible = true;+}++async function swapCharacter() {+ const keys = Object.keys(CHARACTERS);+ const shown = onStage || settings.character;+ const next = keys[(keys.indexOf(shown) + 1) % keys.length];+ if (next === settings.character) { showOnStage(null); return; }+ if (!cast[next]) {+ const m = await loadModel(CHARACTERS[next].url, CHARACTERS[next].name);+ if (cast[next]) return;+ m.visible = false; scene.add(m);+ cast[next] = { model: m, rig: new Rig(m) };+ }+ showOnStage(next);+}++function showOnStage(key) {+ if (onStage && cast[onStage]) { cast[onStage].model.visible = false; stage.removeContactShadow(cast[onStage].model); }+ onStage = key;+ model.visible = !key;+ stage.removeContactShadow(model);+ if (key) { cast[key].model.visible = true; stage.contactShadow(cast[key].model); }+ else stage.contactShadow(model);+ pill('rig', key ? CHARACTERS[key].name : (CHARACTERS[settings.character]?.name || 'character'), 'ok');}// ---- MediaPipe ---------------------------------------------------------------------@@ -432,6 +454,7 @@ function playTake(take) {}video.addEventListener('ended', () => {+ if (settings.swap && rig) swapCharacter().catch((e) => log('swap failed: ' + e.message, 'err'));if (current && !current.liveDone) {current.liveDone = current.live.length > 3;log(`#${current.id} live pass: ${current.live.length} frames`);@@ -518,7 +541,6 @@ function solveLive(res, t) {// ---- render loop ----------------------------------------------------------------------------const bufA = { q: null, p: new Float32Array(3) }, bufB = { q: null, p: new Float32Array(3) }, bufC = { q: null, p: new Float32Array(3) };-const camTarget = new THREE.Vector3(0, 0.95, 0);let lastRaf = 0;function frame() {@@ -555,13 +577,13 @@ function tick() {const hud = $('#hud-src'); hud.textContent = src; hud.className = 'tag ' + (hq ? 'src-hq' : 'src-live');const buf = settings.stream ? ` · ready ${queue.length} gen ${genBusy} hq ${takes.filter((x) => x.hqStatus === 'running').length}${held ? ' · HOLD' : ''}` : '';$('#hud-time').textContent = `#${current.id} ${t.toFixed(2)}s${buf}`;- // Ease the orbit target toward the character.- camTarget.set(lastRenderedHips.x, 0.95, lastRenderedHips.z);- const delta = camTarget.clone().sub(controls.target).multiplyScalar(0.04);- controls.target.add(delta); camera.position.add(delta);}- controls.update();- renderer.render(scene, camera);+ if (rig) {+ const shown = onStage ? cast[onStage].rig : rig;+ if (shown !== rig) shown.copyPoseFrom(rig);+ stage.placeContactShadow(shown.model, shown.hipsWorld(), shown.floorY, shown.height);+ }+ stage.update(rig ? lastRenderedHips : null);}// ---- export --------------------------------------------------------------------------------@@ -574,6 +596,9 @@ async function exportTake(take) {const a = document.createElement('a');a.href = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));a.download = name + '.glb'; a.click();+ // Also keep a copy in ./takes (with the source clip URL) for tools/render_blender.py.+ const q = new URLSearchParams({ name, prompt: take.prompt, ...(take.videoUrl?.startsWith('http') ? { source: take.videoUrl } : {}) });+ fetch('/api/takes?' + q, { method: 'POST', body: glb }).then((r) => r.ok && log(`saved takes/${name}.glb`, 'ok')).catch(() => {});setTimeout(() => URL.revokeObjectURL(a.href), 5000);log(`exported ${name}.glb`, 'ok');}@@ -587,6 +612,8 @@ bindSetting('videoModel', 'value', (m) => {const d = $('#duration'); d.min = m === 'flux3' ? 5 : 2; // FLUX 3 Max: 5–20sif (settings.duration < d.min) { settings.duration = Number(d.min); d.value = d.min; $('#duration-v').textContent = d.min + 's'; save(); }});+bindSetting('swap', 'checked', (on) => { if (!on && model) showOnStage(null); });+bindSetting('cinematic', 'checked', (on) => stage.setCinematic(on));bindSetting('character', 'value', (c) => { if (rig && CHARACTERS[c]) loadCharacter(CHARACTERS[c].url, CHARACTERS[c].name).catch((e) => log('character failed: ' + e.message, 'err')); });bindSetting('duration', 'value', (v) => ($('#duration-v').textContent = v + 's'));bindSetting('hq', 'checked'); bindSetting('waitHq', 'checked'); bindSetting('rootMotion', 'checked');@@ -634,7 +661,6 @@ window.p2r = {};// ---- boot ---------------------------------------------------------------------------------------resize();frame();const startChar = CHARACTERS[settings.character] || CHARACTERS.xbot;loadCharacter(startChar.url, startChar.name).catch((e) => { log('character failed: ' + e.message, 'err'); pill('rig', 'character failed', 'bad'); });diff --git a/public/index.html b/public/index.htmlindex 764bf84..583c389 100644--- a/public/index.html+++ b/public/index.html@@ -133,6 +133,8 @@<label class="title">Character</label><div class="row"><span>Rig</span><select id="character"><option value="xbot">X Bot</option><option value="michelle">Michelle</option><option value="soldier">Soldier</option></select></div>+ <label class="check"><input type="checkbox" id="swap" /><span>Swap character every loop<small>X Bot → Michelle → Soldier, cutting on each loop (or each new clip in Stream mode).</small></span></label>+ <label class="check"><input type="checkbox" id="cinematic" /><span>Cinematic camera<small>Slow arc and push-in around the performer. Drag to take over; it resumes after a few seconds.</small></span></label><div class="row"><button class="btn" id="btn-char">Load Mixamo file…</button><button class="btn" id="btn-vid">Use a video file…</button>diff --git a/public/retarget.js b/public/retarget.jsindex f3cd7a3..b133944 100644--- a/public/retarget.js+++ b/public/retarget.js@@ -149,6 +149,20 @@ export class Rig {this.setHipsWorld(_v2.fromArray(s.p));}+ /**+ * Mirror another Mixamo rig's current pose (crowd mode): each bone gets the same world-space+ * rotation relative to its own rest pose; the hips path is scaled by leg length.+ */+ copyPoseFrom(src) {+ const d = src.hipsWorld(_v2).sub(src.rest.Hips.wp).multiplyScalar(this.legLength / src.legLength);+ for (const name of this.order) {+ if (!src.bones[name]) continue;+ const delta = src.bones[name].getWorldQuaternion(new Q()).multiply(_q2.copy(src.rest[name].wq).invert());+ this.setWorldQuat(name, delta.multiply(this.rest[name].wq));+ }+ this.setHipsWorld(this.rest.Hips.wp.clone().add(d));+ }+// ---- source A: MediaPipe world landmarks -----------------------------------/*** `lm` = 33 THREE.Vector3 in three.js space (x = subject's left, y up, z toward camera),diff --git a/public/stage.js b/public/stage.jsnew file mode 100644index 0000000..14777b3--- /dev/null+++ b/public/stage.js@@ -0,0 +1,167 @@+// The 3D stage: studio lighting, reflective floor, contact shadows, cinematic camera.+import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { Reflector } from 'three/addons/objects/Reflector.js';++const FLOOR_COLOR = 0x15171b;+const FOG_COLOR = 0x111216;++function gradientTexture(top, bottom) {+ const c = document.createElement('canvas'); c.width = 4; c.height = 512;+ const g = c.getContext('2d');+ const grad = g.createLinearGradient(0, 0, 0, 512);+ grad.addColorStop(0, top); grad.addColorStop(0.62, bottom); grad.addColorStop(1, bottom);+ g.fillStyle = grad; g.fillRect(0, 0, 4, 512);+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;+ return t;+}++function blobTexture() {+ const c = document.createElement('canvas'); c.width = c.height = 128;+ const g = c.getContext('2d');+ const grad = g.createRadialGradient(64, 64, 0, 64, 64, 64);+ grad.addColorStop(0, 'rgba(0,0,0,0.85)'); grad.addColorStop(0.45, 'rgba(0,0,0,0.45)'); grad.addColorStop(1, 'rgba(0,0,0,0)');+ g.fillStyle = grad; g.fillRect(0, 0, 128, 128);+ return new THREE.CanvasTexture(c);+}++export function createStage(container) {+ const renderer = new THREE.WebGLRenderer({ antialias: true });+ renderer.setPixelRatio(Math.min(2, devicePixelRatio));+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ container.appendChild(renderer.domElement);++ const scene = new THREE.Scene();+ scene.background = gradientTexture('#262a32', '#111216');+ scene.fog = new THREE.Fog(FOG_COLOR, 9, 26);+ // Soft studio reflections on the characters' materials.+ const pmrem = new THREE.PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ scene.environmentIntensity = 0.45;++ const camera = new THREE.PerspectiveCamera(32, 1, 0.05, 100);+ camera.position.set(0.4, 1.45, 5.4);+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.target.set(0, 0.95, 0);+ controls.enableDamping = true;+ controls.maxPolarAngle = Math.PI * 0.495; // stay above the floor++ // Lights: warm key with soft shadows, cool rim from behind, low fill.+ scene.add(new THREE.HemisphereLight(0xdfe6ff, 0x16181c, 0.55));+ const key = new THREE.DirectionalLight(0xfff1e0, 2.6);+ key.position.set(-2.8, 5.5, 4.2); key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048);+ key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02;+ Object.assign(key.shadow.camera, { left: -6, right: 6, top: 6, bottom: -6, near: 0.5, far: 20 });+ scene.add(key);+ const rim = new THREE.DirectionalLight(0x8fb8ff, 2.2);+ rim.position.set(3.5, 4, -4.5);+ scene.add(rim);+ const fill = new THREE.DirectionalLight(0xffffff, 0.35);+ fill.position.set(3, 1.5, 4);+ scene.add(fill);++ // Floor: a mirror underneath a mostly-opaque matte surface → a subtle, soft reflection.+ const mirror = new Reflector(new THREE.CircleGeometry(40, 64), {+ color: 0x6f747c,+ textureWidth: Math.round(container.clientWidth * renderer.getPixelRatio() * 0.5) || 1024,+ textureHeight: Math.round(container.clientHeight * renderer.getPixelRatio() * 0.5) || 1024,+ });+ mirror.rotation.x = -Math.PI / 2; mirror.position.y = -0.001;+ scene.add(mirror);+ const floor = new THREE.Mesh(+ new THREE.CircleGeometry(40, 64),+ new THREE.MeshStandardMaterial({ color: FLOOR_COLOR, roughness: 0.9, metalness: 0, transparent: true, opacity: 0.9 }),+ );+ floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true;+ scene.add(floor);+ const grid = new THREE.GridHelper(40, 80, 0x3a3f47, 0x262a30);+ grid.material.transparent = true; grid.material.opacity = 0.35; grid.position.y = 0.002;+ scene.add(grid);++ // Contact shadows: a soft dark blob under each character's hips.+ const blobTex = blobTexture();+ const blobs = new Map();+ function contactShadow(model) {+ const m = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: blobTex, transparent: true, depthWrite: false, opacity: 0.8 }));+ m.rotation.x = -Math.PI / 2; m.position.y = 0.004; m.renderOrder = 1;+ scene.add(m); blobs.set(model, m);+ return m;+ }+ function removeContactShadow(model) { const m = blobs.get(model); if (m) { scene.remove(m); blobs.delete(model); } }+ /** hips: world position; floorY: character's floor; size: character height. */+ function placeContactShadow(model, hips, floorY, size) {+ const m = blobs.get(model); if (!m) return;+ const lift = Math.max(0, hips.y - floorY - size * 0.52); // > 0 while airborne+ const k = Math.max(0.25, 1 - lift * 1.6);+ m.position.set(hips.x, floorY + 0.004, hips.z);+ m.scale.setScalar(size * 0.55 * (0.8 + 0.2 * k));+ m.material.opacity = 0.8 * k;+ }++ // Camera: follows a focus point; optional slow cinematic arc + push-in.+ const state = { cinematic: false, width: 1.4, inset: 0, pausedUntil: 0, t0: performance.now(), focus: new THREE.Vector3(0, 0.95, 0) };+ controls.addEventListener('start', () => { state.pausedUntil = performance.now() + 6000; });+ /** Distance that fits a ~2.1m-tall group `state.width` meters wide into the visible area. */+ const baseDistance = () => {+ const w = container.clientWidth - state.inset, h = container.clientHeight || 1;+ const vHalf = THREE.MathUtils.degToRad(camera.fov / 2);+ const hHalf = Math.atan(Math.tan(vHalf) * Math.max(0.3, w / h));+ return Math.max(4.6, 1.2 / Math.tan(vHalf), (state.width / 2 + 0.5) / Math.tan(hHalf));+ };+ // Shift the projection so the action is centered in the area not covered by the video panel.+ function applyInset() {+ // filmOffset shifts the frustum by filmOffset / (filmWidth · aspect · 2·tan(fov/2)) of its width.+ const w = container.clientWidth || 1;+ const f = state.inset / 2 / w;+ camera.filmOffset = -f * camera.getFilmWidth() * camera.aspect * 2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));+ camera.updateProjectionMatrix();+ }+ function reframe() { // one-off move to the right distance (doesn't fight the user afterwards)+ if (state.cinematic) return;+ const dir = camera.position.clone().sub(controls.target).normalize();+ camera.position.copy(controls.target).addScaledVector(dir, baseDistance());+ }+ function fitFog() { const d = baseDistance(); scene.fog.near = d + 3; scene.fog.far = d + 20; }++ function update(focus) {+ if (focus) state.focus.lerp(new THREE.Vector3(focus.x, 0.95, focus.z), 0.04);+ const now = performance.now();+ if (state.cinematic && now > state.pausedUntil) {+ const t = (now - state.t0) / 1000;+ const az = 0.5 * Math.sin((t / 26) * Math.PI * 2); // ±29° arc around the front+ const dist = baseDistance() * (0.86 + 0.14 * Math.cos((t / 19) * Math.PI * 2)); // slow push-in / pull-out+ const h = 1.15 + 0.3 * Math.sin((t / 31) * Math.PI * 2);+ const want = new THREE.Vector3(state.focus.x + Math.sin(az) * dist, h, state.focus.z + Math.cos(az) * dist);+ camera.position.lerp(want, 0.03);+ controls.target.lerp(state.focus, 0.05);+ } else {+ const delta = state.focus.clone().sub(controls.target).multiplyScalar(0.04);+ controls.target.add(delta); camera.position.add(delta);+ }+ controls.update();+ renderer.render(scene, camera);+ }++ function resize() {+ const { clientWidth: w, clientHeight: h } = container;+ renderer.setSize(w, h); camera.aspect = w / h; applyInset();+ mirror.getRenderTarget().setSize(Math.round(w * renderer.getPixelRatio() * 0.5), Math.round(h * renderer.getPixelRatio() * 0.5));+ }+ new ResizeObserver(resize).observe(container);+ resize();++ return {+ renderer, scene, camera, controls, update, contactShadow, removeContactShadow, placeContactShadow,+ setCinematic(on) { state.cinematic = on; state.t0 = performance.now(); },+ /** Width in meters of what should stay in frame (solo ≈ 1.4, crowd wider). */+ setFraming(widthMeters) { state.width = widthMeters; reframe(); fitFog(); },+ /** Pixels on the left covered by the video panel. */+ setInset(px) { if (Math.abs(px - state.inset) > 2) { state.inset = px; applyInset(); reframe(); fitFog(); } },+ };+}diff --git a/server.mjs b/server.mjsindex a6be96e..2a94f4f 100644--- a/server.mjs+++ b/server.mjs@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url';const ROOT = path.dirname(fileURLToPath(import.meta.url));const PUBLIC = path.join(ROOT, 'public');+const TAKES = path.join(ROOT, 'takes'); // exported takes for tools/render_blender.py// --- .env -------------------------------------------------------------------const envFile = path.join(ROOT, '.env');@@ -112,6 +113,19 @@ const server = http.createServer(async (req, res) => {return send(res, 200, { image_url: out.images?.[0]?.url, elapsed: out._elapsed });}+ // Save an exported take (GLB body, ?name=…&source=<video url>) into ./takes for the Blender renderer.+ if (req.method === 'POST' && url.pathname === '/api/takes') {+ const name = (url.searchParams.get('name') || 'take').replace(/[^a-z0-9_-]+/gi, '_').slice(0, 80);+ const chunks = []; let size = 0;+ for await (const c of req) { size += c.length; if (size > 100e6) throw Object.assign(new Error('take too large'), { status: 413 }); chunks.push(c); }+ fs.mkdirSync(TAKES, { recursive: true });+ fs.writeFileSync(path.join(TAKES, name + '.glb'), Buffer.concat(chunks));+ const meta = { name, source: url.searchParams.get('source') || null, prompt: url.searchParams.get('prompt') || '', saved: new Date().toISOString() };+ fs.writeFileSync(path.join(TAKES, name + '.json'), JSON.stringify(meta, null, 2));+ console.log(`[take] saved takes/${name}.glb`);+ return send(res, 200, { path: `takes/${name}.glb` });+ }+// HQ pass: forward to the local GVHMR worker (hq/worker.py).if (url.pathname === '/api/hq/health') {try {diff --git a/tools/render_blender.py b/tools/render_blender.pynew file mode 100644index 0000000..f41a28c--- /dev/null+++ b/tools/render_blender.py@@ -0,0 +1,277 @@+"""Render an exported Prompt2Rig take (.glb) as a polished clip with Blender — no UI needed.++ blender -b -P tools/render_blender.py -- takes/<take>.glb [more.glb ...] [options]++Options+ --out PATH output .mp4 (default: renders/<take>.mp4)+ --res WxH resolution (default 1080x1920 portrait; e.g. 1920x1080)+ --samples N EEVEE samples (default 64)+ --orbit DEG camera arc across the clip (default 40)+ --loops N play the animation N times (default 1)+ --side-by-side also write <out>_compare.mp4: source clip | render (needs ffmpeg + the take's .json)+ --preview quarter resolution, 8 samples — fast look-dev++Several .glb files are placed side by side (e.g. the same take exported for different characters).+"""++from __future__ import annotations++import argparse+import json+import math+import os+import shutil+import subprocess+import sys++import bpy+from mathutils import Vector++FPS = 30+++def parse_args():+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+ ap = argparse.ArgumentParser(prog="render_blender.py")+ ap.add_argument("glbs", nargs="+")+ ap.add_argument("--out")+ ap.add_argument("--res", default="1080x1920")+ ap.add_argument("--samples", type=int, default=64)+ ap.add_argument("--orbit", type=float, default=40.0)+ ap.add_argument("--loops", type=int, default=1)+ ap.add_argument("--side-by-side", action="store_true")+ ap.add_argument("--preview", action="store_true")+ return ap.parse_args(argv)+++def iter_fcurves(action):+ """F-curves of an action — Blender 4.4+ keeps them in layers/strips/channelbags."""+ if hasattr(action, "layers") and action.layers:+ for layer in action.layers:+ for strip in layer.strips:+ for bag in strip.channelbags:+ yield from bag.fcurves+ elif hasattr(action, "fcurves"):+ yield from action.fcurves+++# ---- scene -------------------------------------------------------------------------------+def reset_scene():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ scene.render.fps = FPS+ return scene+++def import_character(path: str, x: float):+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=os.path.abspath(path))+ new = [o for o in bpy.data.objects if o not in before]+ arm = next(o for o in new if o.type == "ARMATURE")+ for o in new:+ if o.parent is None:+ o.location.x += x+ for o in new: # glTF materials can come in with backface culling / blend modes we don't want+ if o.type == "MESH":+ for slot in o.material_slots:+ if slot.material:+ slot.material.use_backface_culling = False+ action = arm.animation_data.action if arm.animation_data else None+ end = int(math.ceil(action.frame_range[1])) if action else 1+ hips = next((b.name for b in arm.pose.bones if b.name.lower().endswith("hips")), None)+ return arm, hips, end+++def make_material(name, color, roughness, specular=0.5):+ m = bpy.data.materials.new(name)+ m.use_nodes = True+ bsdf = m.node_tree.nodes["Principled BSDF"]+ bsdf.inputs["Base Color"].default_value = (*color, 1)+ bsdf.inputs["Roughness"].default_value = roughness+ if "Specular IOR Level" in bsdf.inputs:+ bsdf.inputs["Specular IOR Level"].default_value = specular+ return m+++def build_cyclorama():+ """Seamless studio floor curving up into a back wall (no visible horizon)."""+ import bmesh++ # (y, z) profile: flat floor → quarter-circle cove (r = 4 m) → vertical wall.+ cove = [(6.0 + 4 * math.sin(a), 4 - 4 * math.cos(a)) for a in (i * math.pi / 24 for i in range(13))]+ profile = [(-40.0, 0.0)] + cove + [(10.0, 30.0)]+ mesh = bpy.data.meshes.new("Cyc")+ bm = bmesh.new()+ rows = []+ for y, z in profile:+ rows.append((bm.verts.new((-40, y, z)), bm.verts.new((40, y, z))))+ for (a0, a1), (b0, b1) in zip(rows, rows[1:]):+ bm.faces.new((a0, a1, b1, b0))+ bm.to_mesh(mesh); bm.free()+ for p in mesh.polygons:+ p.use_smooth = True+ obj = bpy.data.objects.new("Cyc", mesh)+ bpy.context.collection.objects.link(obj)+ obj.data.materials.append(make_material("Studio", (0.022, 0.024, 0.028), 0.28, 0.6))+ return obj+++def add_area_light(name, loc, target, energy, color, size):+ data = bpy.data.lights.new(name, "AREA")+ data.energy, data.color, data.size = energy, color, size+ obj = bpy.data.objects.new(name, data)+ bpy.context.collection.objects.link(obj)+ obj.location = loc+ obj.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()+ return obj+++def setup_world(scene):+ world = bpy.data.worlds.new("World")+ scene.world = world+ world.use_nodes = True+ nt = world.node_tree+ nt.nodes.clear()+ out = nt.nodes.new("ShaderNodeOutputWorld")+ # Camera sees a near-black studio; reflections/lighting get a dim studio HDRI.+ hdri = nt.nodes.new("ShaderNodeTexEnvironment")+ path = os.path.join(bpy.utils.resource_path("LOCAL"), "datafiles", "studiolights", "world", "studio.exr")+ if os.path.exists(path):+ hdri.image = bpy.data.images.load(path)+ env = nt.nodes.new("ShaderNodeBackground"); env.inputs["Strength"].default_value = 0.35+ dark = nt.nodes.new("ShaderNodeBackground"); dark.inputs["Color"].default_value = (0.012, 0.013, 0.016, 1)+ lp = nt.nodes.new("ShaderNodeLightPath")+ mix = nt.nodes.new("ShaderNodeMixShader")+ nt.links.new(hdri.outputs["Color"], env.inputs["Color"])+ nt.links.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"])+ nt.links.new(env.outputs["Background"], mix.inputs[1])+ nt.links.new(dark.outputs["Background"], mix.inputs[2])+ nt.links.new(mix.outputs["Shader"], out.inputs["Surface"])+++def setup_camera(scene, focus_arm, hips, width, end, orbit_deg, aspect):+ # Focus point follows the lead character's hips horizontally, at chest height.+ focus = bpy.data.objects.new("Focus", None)+ bpy.context.collection.objects.link(focus)+ focus.location = (0, 0, 1.0)+ if focus_arm and hips:+ c = focus.constraints.new("COPY_LOCATION")+ c.target, c.subtarget, c.use_z = focus_arm, hips, False++ pivot = bpy.data.objects.new("Pivot", None)+ bpy.context.collection.objects.link(pivot)+ c = pivot.constraints.new("COPY_LOCATION"); c.target = focus++ cam_data = bpy.data.cameras.new("Camera")+ cam_data.lens = 45+ cam_data.sensor_fit = "VERTICAL"; cam_data.sensor_height = 24+ cam = bpy.data.objects.new("Camera", cam_data)+ bpy.context.collection.objects.link(cam)+ cam.parent = pivot+ scene.camera = cam+ t = cam.constraints.new("TRACK_TO"); t.target = focus; t.track_axis = "TRACK_NEGATIVE_Z"; t.up_axis = "UP_Y"++ # Distance that fits ~2.2 m tall and `width` m wide.+ v_half = math.atan(12 / cam_data.lens)+ h_half = math.atan(math.tan(v_half) * aspect)+ dist = max(1.1 / math.tan(v_half), (width / 2 + 0.35) / math.tan(h_half)) * 0.92+ # glTF +Z (toward the web camera) imports as Blender -Y: the camera sits on -Y.+ for frame, k_az, k_d, z in ((1, -0.5, 1.08, 1.05), (end, 0.5, 0.94, 1.25)):+ pivot.rotation_euler = (0, 0, math.radians(orbit_deg) * k_az)+ cam.location = (0, -dist * k_d, z)+ pivot.keyframe_insert("rotation_euler", frame=frame)+ cam.keyframe_insert("location", frame=frame)+ for obj in (pivot, cam): # smooth ease in/out+ if obj.animation_data and obj.animation_data.action:+ for fc in iter_fcurves(obj.animation_data.action):+ for kp in fc.keyframe_points:+ kp.interpolation = "BEZIER"+++def setup_render(scene, args, out):+ w, h = (int(v) for v in args.res.lower().split("x"))+ scale = 0.25 if args.preview else 1.0+ r = scene.render+ r.engine = "BLENDER_EEVEE"+ r.resolution_x, r.resolution_y = int(w * scale) // 2 * 2, int(h * scale) // 2 * 2+ r.resolution_percentage = 100+ ee = scene.eevee+ ee.taa_render_samples = 8 if args.preview else args.samples+ if hasattr(ee, "use_raytracing"):+ ee.use_raytracing = True+ r.use_motion_blur = False # EEVEE 5.2 crashes (access violation) with motion blur on skinned glTF in -b mode+ scene.view_settings.view_transform = "AgX"+ try:+ scene.view_settings.look = "AgX - Medium High Contrast"+ except TypeError:+ pass+ im = r.image_settings+ if hasattr(im, "media_type"):+ im.media_type = "VIDEO"+ im.file_format = "FFMPEG"+ r.ffmpeg.format = "MPEG4"+ r.ffmpeg.codec = "H264"+ r.ffmpeg.constant_rate_factor = "HIGH"+ r.ffmpeg.ffmpeg_preset = "GOOD"+ r.filepath = out+ return w / h+++def side_by_side(out, glb):+ meta_path = os.path.splitext(glb)[0] + ".json"+ ffmpeg = shutil.which("ffmpeg")+ if not ffmpeg or not os.path.exists(meta_path):+ print("[render] side-by-side skipped (needs ffmpeg and the take's .json)")+ return+ src = json.load(open(meta_path, encoding="utf-8")).get("source")+ if not src:+ print("[render] side-by-side skipped (take has no source clip URL)")+ return+ cmp_out = os.path.splitext(out)[0] + "_compare.mp4"+ flt = ("[0:v]fps=30,scale=-2:1920,setsar=1[a];[1:v]scale=-2:1920,setsar=1[b];"+ "[a][b]hstack=inputs=2,scale=-2:1080[v]")+ subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", src, "-i", out, "-filter_complex", flt,+ "-map", "[v]", "-shortest", "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", cmp_out], check=True)+ print(f"[render] wrote {cmp_out}")+++def main():+ args = parse_args()+ scene = reset_scene()+ lead = None+ n = len(args.glbs)+ spacing = 1.5+ end = 1+ for i, glb in enumerate(args.glbs):+ arm, hips, e = import_character(glb, (i - (n - 1) / 2) * spacing)+ end = max(end, e)+ if i == (n - 1) // 2 or lead is None:+ lead = (arm, hips)+ total = end * max(1, args.loops)+ scene.frame_start, scene.frame_end = 1, total+ if args.loops > 1: # repeat each armature action+ for o in bpy.data.objects:+ if o.type == "ARMATURE" and o.animation_data and o.animation_data.action:+ for fc in iter_fcurves(o.animation_data.action):+ fc.modifiers.new("CYCLES")++ build_cyclorama()+ setup_world(scene)+ # Three-point lighting: warm key, cool rim, soft fill.+ add_area_light("Key", (-3.0, -3.5, 4.5), (0, 0, 1), 900, (1.0, 0.94, 0.86), 3.0)+ add_area_light("Rim", (3.0, 3.0, 3.8), (0, 0, 1.3), 1100, (0.62, 0.76, 1.0), 2.0)+ add_area_light("Fill", (3.5, -4.0, 1.6), (0, 0, 1), 220, (1.0, 1.0, 1.0), 4.0)++ out = os.path.abspath(args.out or os.path.join("renders", os.path.splitext(os.path.basename(args.glbs[0]))[0] + ".mp4"))+ os.makedirs(os.path.dirname(out), exist_ok=True)+ aspect = setup_render(scene, args, out)+ setup_camera(scene, lead[0], lead[1], spacing * (n - 1) + 1.0, total, args.orbit, aspect)++ print(f"[render] {n} character(s), {total} frames @ {FPS}fps → {out}")+ bpy.ops.render.render(animation=True)+ print(f"[render] wrote {out}")+ if args.side_by_side:+ side_by_side(out, args.glbs[0])+++main()