Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Add camera preview and portable Blender motion exports

toyxyz83832a2aa5b3
diff --git a/README.md b/README.md
index 8450936..40da6a6 100644
--- a/README.md
+++ b/README.md
@@ -119,8 +119,10 @@ do not put passwords or account tokens in the agent chat.
- Reconstruct one or several people and preview the body mesh and animation bones.
- Reduce sliding with foot/palm contact correction and editable contact timings.
- Retarget motion to Mixamo FBX, VRM and PMX humanoid characters.
-- Export source animation as FBX; export characters as FBX with or without meshes,
+- Export source animation as FBX or BVH (Generic/Blender or 3ds Max Biped), with an optional leading T-pose; export characters as FBX with or without meshes,
or PMX character motion as VMD for MMD.
+- Export portable Blender projects with source animation, video and saved cameras; MAMMA can include animated body meshes and every camera.
+- Inspect source-video/bone alignment in Camera Preview and display saved cameras in 3D, with optional background rotation refinement for FlowHMR/ExMR.
- Save projects with separate results for each AI model.
- Track webcam or video input in real time with PEAR's experimental body/finger bone preview; tracking and poses may be unstable.
@@ -135,7 +137,7 @@ do not put passwords or account tokens in the agent chat.
enter an approximate **Reference Height (m)**, or import camera calibration.
Click **Reconstruct 3D**.
3. Review the motion, edit contacts if needed and **Apply Correction**.
-4. Export FBX, or import a character, retarget the motion and export it.
+4. Use **File > Export...** to choose FBX, BVH or a portable Blender project, or import a character, retarget the motion and export it.
**PEAR · Live (Experimental)** tracks webcam or video input in real time. Tracking
and pose estimates may be unstable. Click **Start Live Tracking** to attempt camera
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index 2ccc0b1..94b1547 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 11138,
- "sha256": "5f845886d42e36d5efd06e530fa4cac0b95b5f01a1a84664f2f34365a360c6ba"
+ "bytes": 11568,
+ "sha256": "231fed2ace6b009c4d04fd13f1ded21e9e5aa3c78ac6cfab4acb73c9ae89b9ac"
},
{
"path": "RGBMoCap.cmd",
@@ -46,8 +46,8 @@
},
{
"path": "THIRD_PARTY_NOTICES.md",
- "bytes": 9231,
- "sha256": "ec3f55194be2b53f0102914c13f16ae0378f0cef0d0f9cb95defaed7f4786f88"
+ "bytes": 9254,
+ "sha256": "42364b7829e85031e5ff353df02e9dccc7c1e2df841beb3a1aceca86f872153a"
},
{
"path": "app.py",
@@ -96,13 +96,13 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 50399,
- "sha256": "51f0c8cb9df08d176f0d68ded6e78053beb1b22a44e4342af9992dc36f5c338e"
+ "bytes": 58966,
+ "sha256": "4fe9829f4d14e497e44ae81788b50abcf1d0f0ae46d839e5ce60870a8e0903e2"
},
{
"path": "docs/BUILD.md",
- "bytes": 12591,
- "sha256": "74b42d2ecf5ecd565105ec94171aadc016368411a7c7629ffe1a2d99ccd8cdc8"
+ "bytes": 12967,
+ "sha256": "327a6ae33599374f5dc56871246269591f1c6f00c69a774b0e4143b0f689c993"
},
{
"path": "docs/CITATIONS.md",
@@ -111,8 +111,8 @@
},
{
"path": "docs/MAMMA.md",
- "bytes": 25483,
- "sha256": "838d3d7aa5b28c6f56ed7228d5742bedd8b5efc069f77b7774b4377f0e0671d2"
+ "bytes": 25972,
+ "sha256": "1682a83711942a29f64b7ec4b274bb1a6ee07dfb894d8a97e508825163b8326d"
},
{
"path": "docs/MAMMA_AGENT_SETUP.md",
@@ -126,13 +126,13 @@
},
{
"path": "docs/USER_GUIDE.md",
- "bytes": 49858,
- "sha256": "726fc7ec5743fb488819acea02e96ccf66de3709d5f73d77cbfd1048e9ab72aa"
+ "bytes": 59973,
+ "sha256": "ca250fd26156181cd333885dfae50342eb146a72d530d013c173b3dc67d72a39"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 107524,
- "sha256": "18fb8ceb46e30b15eef9a6a9e3d23adf2497118ae87372fa8c1f73e3c41998a7"
+ "bytes": 122164,
+ "sha256": "5b1d16981620860e18f471b4477f87ea987aa31989a7f8d04e03520736b6b7b6"
},
{
"path": "docs/images/exmr-interaction-contact.png",
@@ -156,18 +156,18 @@
},
{
"path": "docs/models/EXMR.md",
- "bytes": 8113,
- "sha256": "fd85fb1db9a879d43829c71445c98b9e715f14aa6aa4284f15577d2872b56baf"
+ "bytes": 9798,
+ "sha256": "63958a376407c3c995c4814d2d8f2e9858fd230d3b31871963eda24ff0a7cde4"
},
{
"path": "docs/models/FLOWHMR.md",
- "bytes": 11720,
- "sha256": "9d246602b7a60009690eb57060cc9c07536004d4ab9b93e45a87b310c1e94d05"
+ "bytes": 13199,
+ "sha256": "96538bc5088537b59d91b42e6668136238adb6e9dc351bb4ddf0a9a4ff19fddb"
},
{
"path": "docs/models/GVHMR.md",
- "bytes": 5915,
- "sha256": "a43b89cde13e9168431177655c9678a37cc74219436e055066b01137276ca09e"
+ "bytes": 5936,
+ "sha256": "3d2d1470a448883d647f582d5a89112715abe26240632ba1168ac7a4e4795ef8"
},
{
"path": "docs/models/PEAR.md",
@@ -176,13 +176,13 @@
},
{
"path": "docs/models/PROMPTHMR.md",
- "bytes": 14194,
- "sha256": "8ba469aba25a20d23514a72371cf9d2e121eecd7b7b41fcfc7a397c65d1ed0c2"
+ "bytes": 14215,
+ "sha256": "037afb02834ac599660e18478b87b247353155551d9929bedc517451db68d60f"
},
{
"path": "docs/models/README.md",
- "bytes": 6444,
- "sha256": "37ef2661ad95de803143316fa350abd7ea155ef9460918b5c1c545e55d3fd102"
+ "bytes": 6628,
+ "sha256": "1fa42963d3f78e788eb3737aa706d5f25e280d91e1357b486fb37fb553be1272"
},
{
"path": "docs/samples/character-retargeting.jpg",
@@ -1069,6 +1069,46 @@
"bytes": 5752,
"sha256": "c9f04c44545987ca88880b2c3a7c68035b6b1a24646c6fd0c7e228958f3d9b7e"
},
+ {
+ "path": "mocap/biped_bvh.py",
+ "bytes": 5055,
+ "sha256": "1f9d9a56bff54d0bc4d4a45ef7c4d5c354ec54eed7a6e40c9fef4977a4ad6771"
+ },
+ {
+ "path": "mocap/blend_export.py",
+ "bytes": 6782,
+ "sha256": "da140bb620221b218d4ab3ed2e75f3405f9290e83b8728a1af52112561cb2af0"
+ },
+ {
+ "path": "mocap/blend_export_scene.py",
+ "bytes": 4389,
+ "sha256": "738daad476e9e7c0b3dfa332ce100633c310c39ee0931c213fa62246da3e0f5b"
+ },
+ {
+ "path": "mocap/blend_export_ui.py",
+ "bytes": 2360,
+ "sha256": "3f0725d99663ab9e4babd99743aa8d38c01f11704dc6dbc8203bef229beaf6d6"
+ },
+ {
+ "path": "mocap/blend_export_worker.py",
+ "bytes": 786,
+ "sha256": "fabadc9c97a005a988917d1a04996f8213e97be8249c89cceead20c8de81e60c"
+ },
+ {
+ "path": "mocap/blend_multicam_export.py",
+ "bytes": 10822,
+ "sha256": "2d0e1894cc3d897ac0865b8927c209a7c730485617a82d947564331e59c721f3"
+ },
+ {
+ "path": "mocap/blend_multicam_scene.py",
+ "bytes": 8452,
+ "sha256": "50d63e244bb98bdfb09abb9a054e5c000865b8463b7192870ebd67896f935123"
+ },
+ {
+ "path": "mocap/blend_support.py",
+ "bytes": 5133,
+ "sha256": "1f4e5da6bc07ca8c453035b4e0f386c4d1f7890c43049a01b3aad4d48dd0abad"
+ },
{
"path": "mocap/bone_gl.py",
"bytes": 1193,
@@ -1076,8 +1116,8 @@
},
{
"path": "mocap/bone_overlay.py",
- "bytes": 7577,
- "sha256": "f8a44514a027637754ba557dc09100ef7bd90c36f3b604ebac9c9388fd2999c0"
+ "bytes": 7635,
+ "sha256": "f6c9c947df0ac7f03f2dc972f705318fdd99ca8bdac604a289819173a498c20d"
},
{
"path": "mocap/bound_mesh_gl.py",
@@ -1099,6 +1139,31 @@
"bytes": 2926,
"sha256": "5735ce813903ef8af41cf5badec055479d4c788912f7735e2d4d63e2917dd701"
},
+ {
+ "path": "mocap/camera_background.py",
+ "bytes": 8801,
+ "sha256": "6410739e086304e5f74f9e6efa8e6b8359e1494ad784c4106d2121fa88a431af"
+ },
+ {
+ "path": "mocap/camera_background_worker.py",
+ "bytes": 8683,
+ "sha256": "31a8a0162d1b992fdb109297bbe09c45096d093c9237291445344ff1007bb9b9"
+ },
+ {
+ "path": "mocap/camera_reference.py",
+ "bytes": 5003,
+ "sha256": "5fe1ee141e1120b7ce56f6f7b5f470d3a08f59b86e584fc404df832d0b87956f"
+ },
+ {
+ "path": "mocap/camera_tracks.py",
+ "bytes": 13087,
+ "sha256": "b71fd476a02449f2676e0aa404eba12949873f4ef2d81bb22c3783231e2c26e4"
+ },
+ {
+ "path": "mocap/camera_ui.py",
+ "bytes": 15410,
+ "sha256": "290e2bc811d6530d33f9250bc953408f862000c743586b085c002b78b28f91f4"
+ },
{
"path": "mocap/capture.py",
"bytes": 567,
@@ -1206,8 +1271,8 @@
},
{
"path": "mocap/export_copy.py",
- "bytes": 2908,
- "sha256": "08c712ae48c413cf61915aecf5b5c427061d31bf545b8be7fc855e3204e52d8b"
+ "bytes": 3907,
+ "sha256": "2135999f0dcf15dde96e68d05147e4cfe6d550c2faeccb815634ccf8567db016"
},
{
"path": "mocap/fbx_bind.py",
@@ -1216,13 +1281,13 @@
},
{
"path": "mocap/fbx_export.py",
- "bytes": 3668,
- "sha256": "53dd4895d3057b5fc1f4c5b5daf721b70002591cef2a797c1d44a30699d8ffce"
+ "bytes": 3713,
+ "sha256": "2c091f3859ab09798c2f07be3b4751176d8fbf6de7664452873d630b3f162949"
},
{
"path": "mocap/fbx_writer.py",
- "bytes": 10602,
- "sha256": "95da111667b562ee0a2926e9c045db44c78e64e3172eeddc3e54712c6a8e2374"
+ "bytes": 11097,
+ "sha256": "3bcececf7d0f5696927a465ffe866389611f6cf0d2dea41aae58d9bf695a229d"
},
{
"path": "mocap/floor_overlay.py",
@@ -1301,8 +1366,8 @@
},
{
"path": "mocap/gui.py",
- "bytes": 102216,
- "sha256": "725feca92477a634341ae6a8f406505b242004693464a8693c49911ab98c25ed"
+ "bytes": 105342,
+ "sha256": "afd459dc23ccefd56a0a3587b7208d55062fe7ad0887c32b1b953e2d58fce93a"
},
{
"path": "mocap/gvhmr_attention.py",
@@ -1436,8 +1501,8 @@
},
{
"path": "mocap/model_guide.py",
- "bytes": 11486,
- "sha256": "a0e2adc9404ef05171bbafa88558aa3b851c75404ab6ef5e60163cd84581742f"
+ "bytes": 12047,
+ "sha256": "ff25269540fb7a571f23a9e9aba2d01ce28820cfeaef88bb4f3a54ad27f2a4ef"
},
{
"path": "mocap/model_session.py",
@@ -1621,13 +1686,13 @@
},
{
"path": "mocap/people_ui.py",
- "bytes": 38409,
- "sha256": "b7adcc7fe5f28593bdf3dabc09aff7212e75a9e669742e50e2d8811ac8caab64"
+ "bytes": 38557,
+ "sha256": "c96973b19d2ffa8052be89f7ac24727d0c7d949761ebc2e5e3d21fe9cbca3e77"
},
{
"path": "mocap/person_names.py",
- "bytes": 1227,
- "sha256": "028ec9c02f9ec78d8a1af36cd6fe7fdb145006e994452733070932add2aaef3a"
+ "bytes": 1334,
+ "sha256": "aa9a664801549223c41b9b17cab6e87b6372b7e6228712d9e791f6b7f2bf78f2"
},
{
"path": "mocap/person_tracking.py",
@@ -1686,8 +1751,8 @@
},
{
"path": "mocap/project_workspace_ui.py",
- "bytes": 10053,
- "sha256": "9763cff6b9940a69fd93f043a726f9b8384375951e4830877ce5f9507b37f8bb"
+ "bytes": 10189,
+ "sha256": "0577f32e583c3667d6ebb638b7687045d0f487870d2f5abc1875b83ce4d4de64"
},
{
"path": "mocap/prompthmr_manager.py",
@@ -1881,8 +1946,8 @@
},
{
"path": "mocap/scene_export.py",
- "bytes": 5457,
- "sha256": "e33832d06d29343e954de7ea6aeb142ec86a40547a316055784536ad27db7b80"
+ "bytes": 5994,
+ "sha256": "d28be38ca2ff85ae9ea2fdbf40e04b74319096f43b6fc7ac39a155657b4c194c"
},
{
"path": "mocap/scene_floor.py",
@@ -1904,6 +1969,16 @@
"bytes": 4417,
"sha256": "8a46d9ba006cc897315e0229ea2fb4bf87fdb26bf549429836d1ed25d1f45578"
},
+ {
+ "path": "mocap/source_export_dialog.py",
+ "bytes": 5586,
+ "sha256": "94ed6f290981573b37f64282622337dc421fde69c49a6ca15e1f478c67375aae"
+ },
+ {
+ "path": "mocap/source_export_worker.py",
+ "bytes": 629,
+ "sha256": "99097de66de5b1bbde0c2b5ccf719e038fed507db5f53842f94e73cdcd4b37e9"
+ },
{
"path": "mocap/source_pose_fit.py",
"bytes": 18801,
@@ -1941,8 +2016,8 @@
},
{
"path": "mocap/theme.py",
- "bytes": 4369,
- "sha256": "d13299c3842487bb6a028a69e32127b5f28e8702baff135749dbdb7d9707710b"
+ "bytes": 4737,
+ "sha256": "372ba64c2a3464d80ea7d280d5abca61a0031e92ec8498b93df7ef8d166971a3"
},
{
"path": "mocap/timeline.py",
@@ -1981,13 +2056,13 @@
},
{
"path": "mocap/viewer.py",
- "bytes": 11271,
- "sha256": "b12b101f208ce6fbf26aa2bd0f04fd9495aa3917565b1c07c3783d1fdc0910a1"
+ "bytes": 11435,
+ "sha256": "d105e1f8b794442e808aa8a9c5991cb394312827bb5245fb90743d4f2c179096"
},
{
"path": "mocap/viewport.py",
- "bytes": 53337,
- "sha256": "645166692f27f2500b8d3341341c90386311ae0214d21e30ae64a34e4f7e1613"
+ "bytes": 54282,
+ "sha256": "6d1d5b1a4407561b636dc61ffe3f31ebb601d2e13f638ef2e6a4c2e8d15a7d97"
},
{
"path": "mocap/worker.py",
@@ -1996,13 +2071,13 @@
},
{
"path": "mocap/worker_progress.py",
- "bytes": 2327,
- "sha256": "e939e422806d59ed7d68d8444f556740a0e2f75da0e36a564e9c2ba552785f6b"
+ "bytes": 2836,
+ "sha256": "e98a7df6d9396ee5d8ef9411b76cf899497f6c873955812b18b7439376da2e0d"
},
{
"path": "mocap/workspace_ui.py",
- "bytes": 36206,
- "sha256": "95bb0d45ab7ab5dd3b3b2e561ca09e8b490b323eea677f1d094709a7065f9b02"
+ "bytes": 37546,
+ "sha256": "48d421c6fa7ffdda62ae5bd629b83a620fd39255cf1fc64d8871811b43dd2b2c"
},
{
"path": "native_compat/LICENSE",
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 20f0070..38d0241 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -7,7 +7,7 @@ retained license files and provider agreements contain the full terms.
## AI tools and models
-Character import and baking use a separate, unmodified Blender 4.5 LTS runtime
+Character import, baking and portable scene export use a separate, unmodified Blender 4.5 LTS runtime
(GPL; bundled license and source information in `runtime_character`). The scoped
FBX sampler in `mocap/retarget/selective_fbx.py` retains Blender's GPL terms.
The VRM add-on, mmd_tools and OpenCC retain their own notices under
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 405361a..65c6697 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -185,7 +185,7 @@ test a new native module, or use cached inference as evidence of a new build.
3. Choose camera and processing settings, then **Reconstruct 3D**. Processing runs on a 30 fps working clip, without changing the original video. Progress and cancellation are in the app. **Prepare Preview** rebuilds previews from existing motion without rerunning inference.
4. Review motion and contacts. **Enable Correction** selects corrected output; Foot defaults on and Hand off for new work. Flat Ground uses a common floor; Multi Level retains inferred contact heights and does not reconstruct terrain. Inspect automatic contacts; hand contacts represent support, not hanging/object tracking.
5. Edit L/R foot and hand intervals on the timeline, then **Apply Correction**. Pending changes are not applied until then; stale corrected export is blocked. Applying also refreshes linked retargeted characters. Correction and preview do not require fresh AI inference.
-6. **File > Export FBX** exports displayed applied source-person motion. Multiple checked people/takes produce separate named files. Source FBX uses a 52-bone Hips-root hierarchy; BVH files may exist internally but are not the public export option.
+6. **File > Export...** opens FBX/BVH/Blender format selection, the BVH-only Generic/Blender (default) or 3ds Max Biped profile, and the default-off **Add T-pose before motion** option. Multiple checked people/takes produce separate named files. Source skeleton exports use the committed 52-bone Hips hierarchy; the Biped profile renames joints in the exported copy. Optional T-pose export adds one reference frame without editing the cached motion or contacts; original motion shifts by one frame. Blender creates portable video/camera bundles; MAMMA additionally offers whole-scene PC2 bodies and every calibrated camera without a T-pose. Character exports keep their separate FBX/VMD dialog.
See [the full workflow and controls](USER_GUIDE.md#start-here). Do not confuse viewport toggles, automatic detection and applied motion corrections. No general scene geometry or collision reconstruction is implied.
@@ -198,6 +198,123 @@ notices. Existing saved previews are not automatically replaced; use Apply
Correction to recompute without inference. See the v9 measurements and limits
in [validation](VALIDATION.md#contact-correction-v9-coherent-root-and-swing-transitions-2026-10-30).
+### Saved camera display and source export implementation
+
+`mocap/camera_tracks.py` adapts committed camera receipts without inference or
+body-based camera refitting. Single-person FlowHMR may have no
+`scene_camera.json`; use its validated `flow_world.json` basis/height and native
+`flow_camera.npz` without creating a scene receipt or fitting the corrected pose. MAMMA native Z-up calibration is transported to the
+app's Y-up world. FlowHMR/ExMR use saved rotation tracks. Flow gizmos additionally display
+unscaled VGGT displacement; moving-camera ExMR gizmos use estimated displacement
+from ORIGINAL paired world/camera root positions, never corrected poses.
+Motion x defaults to 1, with 0 retaining a fixed center. Video overlay projection
+remains unchanged when this display scale changes. MAMMA/GVHMR remain fixed. Other models expose their saved reference camera only. Do not interpret
+an extrinsic translation vector as the camera center: use `-R.T @ t`.
+
+Single-person ExMR/GVHMR may also have no shared-scene camera receipt.
+`mocap/camera_reference.py` reads the original paired global/camera parameters
+in a cancellable shared-runtime CPU subprocess, with weights-only memory-mapped
+tensor loading. It derives the shape-dependent pelvis pivot from the committed
+original joint cache and never fits to corrected bodies. Camera references are
+kept in a maximum-eight-entry in-memory loader cache, validated against original
+source stamps. Do not import Torch into the editor, write scene/floor receipts,
+run inference or change motion to display a missing camera.
+
+`mocap/camera_ui.py` owns one coalescing camera loader and a Camera Preview canvas
+sharing the existing source QImage. Its video paint callback also projects the
+reconstructed skeleton into the left video view when **Overlays** is on,
+independently of the right Bone Overlay/Camera switches. Keep image, camera and actor skeletons paired
+at frame delivery, including camera switches and rapid seeks. Do not load camera
+files in painting, add a decoder, run Torch in the GUI or alter source camera
+receipts, floor or poses when a display checkbox changes. Camera gizmos/path samples are bounded;
+missing/stale inputs must be visible. Camera Preview is disabled for PEAR.
+
+FlowHMR/ExMR's default-off **Refine Camera Rotation** is an explicit exception
+for derived camera display matrices, not source processing. `camera_background.py`
+adapts PR #18's masked first-frame feature tracking, held-out validation, 2-degree
+limit and sampled interpolation. Failed/rejected observations retain the saved
+rotation, and static-camera results skip the operation. Preserve its acceptance
+thresholds rather than forcing a correction when texture or parallax is unsuitable.
+
+`camera_background_worker.py` uses the existing shared runtime in an isolated
+CPU-only process; `worker_progress.py` routes the stage before inference/cache
+fingerprinting. One coalescing camera loader owns it, cancels/reaps it on toggle,
+replacement or close, and never imports Torch into the GUI. Windows progress is
+read from a bounded, atomically replaced transient file at no more than 5 Hz plus
+phase/final updates. Opaque startup remains active with elapsed time. Temporary
+input/output files live under `cache/camera_background/job-*` and are cleaned
+when the request ends; stale directories after an abrupt application termination
+are disposable with the app closed.
+
+The session refinement cache is limited to four entries and 32 MiB of changed
+matrices, validated against input stamps and the camera/core/worker code digest.
+Unchanged results do not store another matrix copy. Matrix payloads are limited
+to 32 MiB, reports to 1 MiB, captured logs to 512 KiB, fitting samples to 600 and
+worker runtime to 180 seconds. Known actors must have usable tracking boxes.
+Temporary preparation can use additional bounded memory beyond the cache limit.
+No new model/runtime packages, inference signatures, source camera receipts,
+source poses, contacts or FBX/BVH animation may change. Checkbox state belongs
+only in workspace view metadata (`camera_background`). Test accepted and rejected
+cases, exact off restoration, cache invalidation, cancellation, source preservation
+and frame/image/camera pairing separately.
+
+`mocap/source_export_dialog.py` supplies source export options.
+`biped_bvh.py` adapts PR #18's Character Studio naming and uniform ZXY
+conversion for all 52 joints, including fingers. `bvh_profile` propagates through
+every person/take export request; reject unknown profiles. Generic output remains
+a byte copy when no placement/T-pose preparation is needed. Biped uses bounded
+128-frame batches; only placement/T-pose preparation needs a temporary intermediate
+file, which is closed on success/error/cancellation. Preserve original offsets,
+units, timing, physical keyed rotations and source caches. Uniform Euler order can
+change fractional interpolation; do not claim identical between-key motion or
+verified 3ds Max behavior from the Blender/numerical checks alone.
+
+`source_export_worker.py` routes BVH saves through the cancellable worker without
+changing AI worker/cache fingerprints. Keep selected-result, pending contact and
+shared-scene guards, generation checks and atomic destination replacement in
+`fbx_export.py`/`export_copy.py`. Unchecked FBX output must remain identical.
+The optional leading pose is animation, not a replacement bind pose; validate
+both original-frame and fractional-frame suffix poses in Blender after changes.
+
+### Portable Blender export implementation
+
+`blend_export_ui.py` constructs requests and selects new, collision-free bundle
+folders. `blend_export_worker.py` routes `save_blend`/`save_blend_scene` through
+`worker_progress.py` before inference fingerprinting. Keep the existing runtime
+registry and inference worker untouched. General bundles in `blend_export.py`
+reuse `camera_tracks.load` and the isolated original-reference loader; never
+re-estimate the camera from a corrected body. Export only the requested take
+interval, transport the skeleton once through its existing shared placement, and
+use cameras already in that common world without applying the placement twice.
+Optional camera tracking, movement scale and background refinement affect only
+exported cameras. T-pose shifts both motion and video by one frame.
+
+`blend_multicam_export.py` adapts PR #18's full-scene pipeline: current checked
+MAMMA people/takes, full selected SMPL-X LBS surfaces streamed one frame at a
+time into PC2, source skeleton FBX, saved fixed calibration and working videos.
+`blend_multicam_scene.py` builds an overview plus per-camera linked scenes.
+Preserve half-open take visibility and the original shared timeline. Body meshes
+use caches, not armature deformation. Keep model-derived asset inputs private;
+do not distribute body files or model assets with application source. Only the
+user-requested animated scene is exported. Registered assets retain their terms.
+
+The builders `blend_export_scene.py`/`blend_multicam_scene.py` run only in the
+existing Blender 4.5 runtime, with autoexec disabled and bounded CPU threads.
+They install no frame handlers/scripts. Movies and PC2 use relative paths; test
+relocation including Unicode folders. Verify imported bone matrices, actual
+PC2 evaluated vertices, camera projection (including unequal fx/fy and shifted
+principal point), frame timing and object-transform key exclusion.
+
+`blend_support.py` owns exclusive sibling staging directories, bounded video
+copying and log reads, free-space checks, progress forwarding, and native-process
+termination on errors/cancellation. Remove only exact owned staging paths with
+the matching request marker; never remove completed bundles or existing user
+folders. GUI cancellation terminates the worker tree and cleans its known staging
+directory. Revalidate source/stat/generation/scene receipts before publishing.
+MAMMA currently bounds the common trim to 1800 frames/eight people; geometry
+baking must not accumulate whole mesh sequences in RAM. No new inference,
+runtime dependency, source motion or contact change is part of export.
+
## Character retargeting and export
- **File > Import Character...** accepts Mixamo-style FBX, VRM and PMX, and adds the character in rest pose below people. Up to eight characters per project are supported.
diff --git a/docs/BUILD.md b/docs/BUILD.md
index ce3fcbe..913d6c8 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -70,7 +70,9 @@ checking existing models.
| Contact correction | `mocap/correction.py`, `contact_trajectory.py`, `contact_pose_plan.py`, `contact_arm_plan.py` |
| Skeleton and surface fitting | `mocap/source_animation.py`, `source_surface.py`, `surface_roll.py` |
| Preview and playback | `mocap/viewport.py`, `preview_data.py`, `playback.py`, `video_preview.py` |
-| FBX | `mocap/fbx_export.py`, `fbx_bind.py`, `fbx_writer.py`, `scene_export.py` |
+| Source export | `mocap/source_export_dialog.py`, `fbx_export.py`, `fbx_writer.py`, `scene_export.py`, `export_copy.py`, `biped_bvh.py` |
+| Blender bundles | `mocap/blend_export.py`, `blend_multicam_export.py`, `blend_export_worker.py`, `blend_support.py`, `blend_export_scene.py`, `blend_multicam_scene.py` |
+| Camera preview/overlay | `mocap/camera_tracks.py`, `camera_ui.py`, `camera_reference.py`, `camera_background.py`, `camera_background_worker.py` |
| Git setup/update | `install.cmd`, `update.cmd`, `tools/git_bootstrap.ps1`, `tools/git_managed_install.py`, `tools/git_update.py`, `installer/runtime-lock.json` |
Run `app.py` from `.venv` while editing. Worker changes are loaded by their own
diff --git a/docs/MAMMA.md b/docs/MAMMA.md
index 7397440..5fd45c3 100644
--- a/docs/MAMMA.md
+++ b/docs/MAMMA.md
@@ -176,7 +176,13 @@ every clip fits memory; the full 60-second limit has not been validated.
do not need new MAMMA inference. Foot correction is on and hand correction is
off by default; enable **Hand** when palm support is needed. The viewport
**Lock** checkbox only shows or hides contact markers.
-6. Use **File > Export FBX** for the displayed, applied motion. It uses the
+6. Use **File > Export...** for the displayed, applied motion. Choose FBX or BVH
+ for skeleton animation, or Blender for a portable project. Blender also offers
+ **MAMMA whole scene: body meshes and all cameras** for checked people, baked
+ PC2 surfaces, reference skeletons and every synchronized camera/video.
+ Whole-scene export preserves the common timeline without an added T-pose;
+ keep its `videos/` and `meshes/` folders beside the `.blend`. See
+ [portable Blender export](USER_GUIDE.md#portable-blender-projects). Skeleton export uses the
existing 52-bone source-export convention. Use **File > Save Project As** to
keep a named copy; reopen its `project.json` with **File > Open Project**.
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 0043371..12d1c97 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -260,7 +260,7 @@ For ExMR, FlowHMR and GVHMR:
who to reconstruct. MAMMA/PromptHMR track people during reconstruction.
5. Click **Reconstruct 3D**. Review the video, mesh and **Bone Overlay** together.
6. Adjust correction settings or contact timings, then click **Apply Correction**.
-7. **File → Export FBX** saves the displayed, applied animation.
+7. **File → Export...** saves the displayed, applied animation.
For synchronized multi-camera capture, select MAMMA before opening videos and
follow the [MAMMA workflow](MAMMA.md#reconstruct-and-export). It detects people
@@ -322,7 +322,7 @@ opening a project restores its saved model. **Prepare Preview**, below
| **PromptHMR** | Can improve relative placement and interactions between multiple people in one fixed-camera video. Overall motion quality was lower than ExMR in our subjective tests; contacts and depth can still be wrong. Separate setup. | No finger tracking; fixed neutral pose. |
| **PEAR** | Live single-person bone preview from a webcam or video. Lightweight live foot lock; no offline correction, recording, retargeting or export. | Included. |
-The five offline models support contact correction, a 52-bone overlay and FBX export.
+The five offline models support contact correction, a 52-bone overlay, FBX/BVH export and portable Blender bundles.
ExMR/FlowHMR/GVHMR use **Find person** for explicit people selection; MAMMA
and PromptHMR track people during reconstruction. The viewport shows the selected
source mesh: SMPL-X for ExMR/GVHMR/MAMMA/PromptHMR,
@@ -484,6 +484,7 @@ selected result is missing, reconstruct it; the app reports it as unavailable.
| Setting | Function and when to use it |
| --- | --- |
+| **FlowHMR / ExMR → Refine Camera Rotation** | Optional background refinement of the saved moving-camera display track. Default off. Validates small rotation corrections; unreliable samples retain the original. No motion re-inference. |
| **ExMR → Camera** | Static Camera for a camera that stays still without zooming; Moving Camera / SimpleVO when it moves. |
| **ExMR → Smooth Motion** | Reduce small changes between frames. Off keeps the unsmoothed result. |
| **FlowHMR → Fast SAM** | Speed up body/hand image processing with the same model files. Small numerical differences can affect motion and automatic contacts. |
@@ -606,16 +607,44 @@ depth and contacts between people are estimates; collision avoidance is not prov
## FBX and Blender
-**File → Export FBX** follows the displayed, applied result. Each checked
+**File → Export...** opens source-motion options: choose **FBX (.fbx)**,
+**BVH (.bvh)** or **Blender project + video (.blend)**. The optional
+**Add T-pose before motion** defaults off.
+For BVH, choose **Generic / Blender** (default) or **3ds Max Biped** in the
+**BVH profile** list.
+The selected, applied result is exported. Each checked
person/take gets a separate named file and rig; duplicate filenames get suffixes.
People exports use the viewport's shared placement. Takes retain their own frame
counts; align their start times when combining different source intervals.
Source-person exports use a 52-bone hierarchy with **Hips** as root and plain
-anatomical names. It retains
+anatomical names by default. The Biped profile renames exported joints as described
+below. It retains
actor lengths, SMPL-neutral curved limbs/feet, calibrated rest axes and straight
-open fingers. FBX stores rest transforms separately; no T-pose frame is inserted.
-BVH is internal compatibility data only.
+open fingers. FBX stores rest transforms separately. With the T-pose option off,
+no extra frame is inserted. When enabled, one reference animation frame is placed
+before the original motion, at its initial root position; original frames shift
+by one and retain their poses, frame rate and intervals. The option does not
+replace the bind pose or edit project motion/contact timings.
+
+BVH uses the same 52-bone hierarchy, metre units and Y up, including finger bones
+and terminal tips. Import into Blender with **Scale 1 / Forward -Z / Up Y**.
+The **3ds Max Biped** profile follows the PR #18 conversion: it uses Character
+Studio names (for example, Spine becomes Chest and LeftArm becomes LeftShoulder)
+and uniform **ZXY** rotation channels. All 52 joints, fingers, offsets, terminal
+tips and keyed poses are retained, with no unit conversion or source-cache edits.
+Changing Euler order can change interpolation between keys. Use Generic/Blender
+when preserving the existing channel encoding is important. The optional leading
+T-pose works with either profile and retains the first motion frame's root position.
+
+In 3ds Max, create a Biped and load the file through **Motion > Motion Capture**.
+See [Autodesk's BVH import steps](https://download.autodesk.com/global/docs/motionbuilder2014/en_us/files/Importing_Importing_.bvh_files_into_3ds_Max.htm).
+This compatibility profile was checked numerically and imported in Blender;
+3ds Max itself was not available for validation. Biped's own retargeting and limb
+constraints may affect the result.
+
+BVH cannot store FBX Pre/PostRotation or arbitrary rest-bone roll; the rest axes
+can consequently look different. Use FBX when explicit rest transforms are needed.
**Export Character...** preserves the imported target character's own hierarchy
and original rest pose; it does not replace them with the 52-bone source rig.
@@ -628,6 +657,127 @@ The first frame in **Pose Position** shows animation, which can differ from rest
Use the character workflow above for supported humanoids, or retarget the source
FBX in your animation software.
+### Portable Blender projects
+
+Choose **Blender project + video (.blend)** in **File > Export...**, then choose
+an output filename. The exporter creates a **new subfolder** containing the
+`.blend`, `video.mp4`, `camera_report.json` and instructions. Existing folders are
+retained; a numbered folder is chosen when needed. For several checked people
+or takes, each gets its own portable folder. The selected applied motion and
+shared placement are preserved. Original inference, project files, contacts and
+camera receipts are not rewritten; stale results remain blocked.
+
+Open the `.blend` in Blender 4.5 or newer. **Numpad 0** enters the source-camera
+view and **Space** plays. The skeleton is editable; its object has no animated
+transform. The synchronized source video is a viewport camera background, not
+a render background. Move the **whole folder**, keeping the video beside the
+project. The app uses its existing Blender runtime to build the bundle; no
+additional runtime or AI inference is needed.
+
+**Export saved camera tracking** defaults on. FlowHMR/ExMR can use the saved
+rotation and approximate movement estimate. **Camera movement scale** defaults
+to the current display scale; 0 fixes the center. **Refine Camera Rotation**
+starts with the corresponding sidebar setting and exports only validated
+background corrections. Disabling tracking exports the first saved camera as a
+fixed camera. These choices affect only the exported camera, never body motion.
+Movement scale and reconstruction error can prevent exact video alignment; this
+is not measured camera calibration. The export report records the choices.
+An optional T-pose adds one animation frame and delays the video/camera timeline
+by one to keep the original motion and video paired.
+
+### MAMMA whole-scene Blender projects
+
+When MAMMA is selected, the Blender format also shows **MAMMA whole scene: body
+meshes and all cameras**. Check it to export checked people and their visible
+takes together, all saved calibrated cameras, synchronized video panels, and a
+separate camera-view scene for each camera. The original common timeline is
+retained; the T-pose option is unavailable for this export.
+
+Body surfaces are baked **PC2 mesh caches**, including the selected applied
+correction. Reference armatures are separate editable skeletons; they are **not
+deformation rigs** for the meshes. Keep the `.blend`, `videos/` and `meshes/`
+together. Changing a reference skeleton does not deform its cached body.
+The presentation floor/lights are aids, not reconstructed scene geometry.
+Camera backgrounds are viewport references; the overview's video panels are
+image-textured geometry. Each camera scene excludes those panels.
+
+This mode needs the saved MAMMA inference/calibration, matching undistorted
+working videos and current body-mesh/skeleton previews. Use Apply Correction or
+Prepare Preview if requested; export does not rerun MAMMA. Nonzero distortion
+or unsupported camera skew is rejected rather than silently exported incorrectly.
+PC2 disk usage is about **120 KiB per frame per person** (10,475 vertices),
+in addition to videos, skeleton animation and the Blender file. Copies and
+mesh baking run outside the GUI with visible activity/progress and cancellation.
+
+## Saved cameras and Camera Preview
+
+For reconstructed offline motion, **Overlays** above the left video preview also
+shows the reconstructed skeleton projected through the selected saved camera.
+It defaults on and is independent of the right viewport's **Bone Overlay** and
+**Camera** switches. MAMMA projects all visible people into the selected camera
+thumbnail. No new reconstruction or Camera Preview selection is needed to enable it.
+
+For a separate alignment view, choose **Camera Preview** in the 3D viewport's
+view selector. It shows the current source video with the displayed source
+skeleton projected through the saved camera. **Bone Overlay** controls the bones.
+Playback and seeking share the existing decoded video frame; no second video
+is decoded. For MAMMA, select a camera thumbnail to inspect that view. Middle-drag
+and wheel pan/zoom the preview; **Frame All** restores its image framing. Choosing
+a normal view returns to the 3D scene.
+
+Enable **Camera** below the 3D viewport to show saved cameras as wire frustums
+with an image-top triangle. This switch defaults off and affects display only.
+It does not recalibrate cameras, alter motion/correction or reframe the 3D view.
+Camera motion follows the source timeline; available displacement paths are
+bounded display samples. Saved cameras can be outside the current 3D framing;
+zoom out or orbit to inspect them.
+
+- MAMMA displays all saved fixed camera calibrations in the fitted shared world.
+- FlowHMR displays saved rotation and the estimated VGGT displacement path.
+ Its displacement has no measured metric scale, so the path is approximate.
+- ExMR in Moving Camera mode can estimate camera displacement from the original
+ paired world/camera root positions. This includes inference error and is not a
+ measured camera trajectory. Static Camera mode retains a fixed position.
+- When **Camera** is enabled in the ordinary 3D view, **Motion x** controls the
+ estimated movement display: 1 uses the estimate, 0 keeps the camera center fixed.
+ The default is 1. This affects camera gizmos and their path only; source video
+ overlays keep the calibrated projection and exports/motion remain unchanged.
+ ExMR movement requires a reference take covering the complete video; otherwise
+ the app shows rotation only with a notice.
+- Other offline results display their committed reference camera when available;
+ this does not imply a complete moving-camera reconstruction.
+
+FlowHMR and ExMR offer **Refine Camera Rotation** below their camera setting.
+It defaults off. When enabled, the app optionally post-processes saved moving-camera
+rotation using background features, following PR #18. It excludes known actor boxes,
+validates against held-out matches, accepts corrections up to 2 degrees, and
+interpolates corrections between sampled frames. Rejected samples retain the
+original rotation. This can help small camera errors but may do nothing when
+background texture/matching is poor or camera motion is large. Static-camera
+results are skipped.
+
+The operation runs on the CPU when saved cameras are needed for an enabled video
+overlay, Camera Preview or camera gizmo. Progress and elapsed time are visible;
+the accepted count and processing time appear in Console/CMD. Disabling the option
+restores the original saved camera immediately through the background loader.
+Validated results are reused within the session while input stamps remain current.
+The checkbox is kept in workspace view settings when the workspace is saved.
+No extra models, packages or runtime installation are required.
+
+Refinement affects the video bone overlay, Camera Preview and displayed camera
+orientation only. Camera centers/movement scale, original camera files, source
+poses, contact correction and FBX/BVH animation remain unchanged. With the option
+off, FlowHMR retains its saved VGGT-Omega tracking and ExMR its saved SimpleVO
+tracking without this additional operation. Failures keep the original camera
+and display a notice.
+
+The preview uses the saved calibration (or its optional display-only background
+rotation refinement), without fitting cameras to corrected bodies. Correction can intentionally move bones away from the video. Inference,
+calibration and body-fit errors remain visible. Calibrations with lens distortion
+currently use a pinhole overlay and show a limitation warning. Missing/stale
+camera data shows a notice; prepare the selected preview instead of substituting
+another result. Camera Preview is unavailable in PEAR live mode.
+
## Development and license
See [Build from source](BUILD.md) for environment setup, editing and release builds.
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index a0344c1..f0ca264 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -1629,3 +1629,231 @@ still blocked Start, and all five Model Manager rows remained available with
alignment rows marked optional. Console/CMD routing, alignment failures, retry
and Stop regression checks were repeated. This does not make alignment optional
for calibrated fusion or live foot locking, and is not a new inference benchmark.
+
+
+## Saved camera inspection and source export options (2026-11-02)
+
+Selected PR #18 ideas were adapted locally, without merging its other changes.
+Original inference, contact correction, runtime profiles and model calculations
+were not changed.
+
+- The default-off Camera display and Camera Preview were exercised with four
+ real MAMMA calibrations. Real FlowHMR (235 frames) and ExMR (32 frames) saved
+ rotation tracks loaded. Nonidentity rotation/translation fixtures checked
+ camera-center and image-corner projection conventions. Camera toggles retained
+ the existing viewer eye/basis. Camera painting performed no camera metadata I/O.
+- A four-second, 120-request decoded-video test shared its source image with the
+ camera canvas: 121 deliveries including initial presentation, zero mixed frame
+ pairs. Delivery interval median/p95/maximum was 31.64/47.11/48.00 ms. Rapid seeks
+ retained the latest request; camera switching retained a complete frame pair.
+ This short offscreen test is not a general playback or GPU FPS guarantee.
+- Sixty temporary camera-loader start/cancel/close cycles had 459-460 process
+ handles. RSS warmed from 183.61 to 191.21 MiB and stabilized in later samples.
+ Loader/decoder threads stopped at close. This does not establish indefinite
+ leak freedom or replace long interactive testing.
+- Unchecked FBX writer output matched the previous writer byte for byte for a
+ real three-frame fixture. Blender 4.5 imports checked integer and quarter-frame
+ suffix samples with and without the leading T-pose: maximum position/matrix
+ differences were zero. The FBX and BVH reference-pose relative joint positions
+ differed by less than 0.001 mm. The actual BVH worker saved both option states;
+ unchecked BVH matched the committed source bytes. Original frame count/FPS and
+ channels were retained after the optional prefix, and unavailable source
+ export remained blocked before opening options.
+
+Camera display is calibration inspection, not camera re-estimation. Flow VO
+translation is unscaled and defaults off; ExMR has rotation only; other offline
+models may expose only a reference camera. Distorted calibration uses a pinhole
+overlay with a warning. No fresh AI inference or clean-Windows installation was
+claimed for these display/export-only changes. Private inputs, test scripts and
+outputs remain outside the public checkout.
+
+
+### Left video overlay follow-up (2026-11-02)
+
+The first integration exposed projected bones only in the right Camera Preview.
+The left video's existing Overlays switch now also paints the reconstructed
+skeleton through the saved camera. A real four-camera/two-person MAMMA fixture
+checked automatic camera loading in the ordinary Perspective view, both actors,
+Overlays off/on, independence from the right Bone Overlay/Camera switches,
+latest seek pairs and immediate visibility changes while paused. It shares the
+same decoded image and frozen camera/pose pair; no second decoder was created.
+
+
+### Single-person FlowHMR camera compatibility (2026-11-02)
+
+Single-person FlowHMR projects do not necessarily publish the multi-person
+scene_camera.json receipt. Camera display now reuses the validated native camera
+track and committed placement basis/height in memory. A real 2,267-frame single
+project loaded in 0.020 seconds; sampled camera centers retained the saved
+height and the basis matched the existing shared-camera calculation. The
+corrected-source video overlay loaded successfully. Original project file sizes
+and timestamps stayed unchanged; no inference or new scene receipt was needed.
+Missing camera inputs are reported as a concise notice instead of a raw Windows
+file/path error. Existing four-camera MAMMA and saved FlowHMR/ExMR camera tests
+remain separate regressions.
+
+
+### Single-person ExMR/GVHMR camera compatibility (2026-11-02)
+
+Both workflows can omit the shared-scene camera receipt. An isolated CPU reader
+now derives the display reference from the original paired global/camera motion
+and registered pelvis pivot represented by the committed original joints. It
+reads only the first joint from the NPZ stream and memory-maps tensor storage;
+no body model load, inference, correction or project-file writes are needed.
+
+A real single-person ExMR project loaded 267 camera rotations, including about
+45 degrees of relative rotation. Sampled source times matched the saved SimpleVO
+rotation track. A single-person GVHMR project loaded its reference camera.
+Both displayed corrected-source video overlays and camera-gizmo data, passed
+seek checks, and rejected deliberately stale in-memory reference stamps.
+Original project file sizes/timestamps were unchanged. First reference loads
+were 2.20/2.19 seconds (ExMR/GVHMR); reused loads were 4.84/3.66 ms on the test PC.
+The editor did not import Torch. Cancelling a starting reference process and
+closing its loader took 60 ms and left no reference child process running.
+These are short local checks, not universal latency or indefinite leak claims.
+
+
+### Approximate camera movement visualization (2026-11-02)
+
+Camera gizmos now use estimated movement by default (Motion x = 1), separately
+from the saved video-overlay projection. FlowHMR uses its existing VGGT relative
+camera-center displacement. Moving-camera ExMR derives displacement from the
+original paired world/camera roots and saved camera rotations in the isolated
+CPU reader; it does not use corrected motion or rerun visual odometry/inference.
+ExMR shared scenes use the scene's fixed anchor take, not the currently selected
+person. Incomplete anchor coverage falls back to rotation only with a notice.
+
+A real 267-frame moving-camera ExMR sample produced a nonzero estimated path
+(maximum displacement 13.61 inferred metres, not ground truth); sampled times
+and camera-center sign/scale checks passed. A private static-policy fixture
+retained a fixed camera center. A real 2,267-frame Flow cache had a small nonzero
+VGGT displacement (maximum 0.000912 relative units). These values establish
+that the stored estimates were displayed, not trajectory accuracy.
+All four MAMMA cameras and the current GVHMR reference remained fixed. A known
+nonidentity camera fixture validated displacement direction and scaling.
+GUI tests confirmed that changing Motion x leaves the video-overlay camera
+matrix unchanged, and that the movement control is hidden for fixed references.
+The existing single-person overlay/seek, stale-reference, CPU cancellation and
+original-project preservation checks also passed. No new model/runtime or
+inference is required. Monocular scale and body-motion prediction errors remain.
+
+### Leading reference frame placement
+
+The optional leading T-pose follows PR #18: it uses the original first motion
+frame's root position, including shared-scene placement; it does not recenter
+the animation. The default remains off. Blender 4.5 imports were checked for a
+real source sample, a nonidentity scene transform and a one-frame clip. The
+reference root matched the first original root exactly. Original suffix poses
+(including quarter-frame samples) differed by less than 0.001 mm in position
+and 0.000001 in matrix entries; rest matrices were unchanged, and no armature
+object transform channels were added. Unchecked FBX output remained byte-identical
+to the previous writer. BVH suffix channels retained the original motion.
+
+### BVH export profiles (2026-11-02)
+
+Added a BVH-only Generic/Blender (default) or 3ds Max Biped selector, adapted
+from PR #18. The Biped copy uses Character Studio names and uniform ZXY channels;
+source inference, correction, previews and existing files are unchanged.
+
+- Full existing MAMMA/FlowHMR/ExMR/GVHMR samples (493/2267/267/267 frames)
+ retained 52 joints, hierarchy offsets, terminal offsets, root translations and
+ timing. Maximum keyed local rotation difference was below 2e-11 radians.
+ Conversion took approximately 0.15-1.23 seconds on the test PC; this excludes
+ application startup and destination I/O and is not a universal speed claim.
+- Blender 4.5 imports at sampled keyed frames differed by at most 0.012 mm in
+ heads/tails and 0.000029 in rotation-matrix entries. The numerical double-precision
+ conversion is tighter than Blender's single-precision animation storage.
+- Sampled original-motion half-frames differed by up to 5.62 mm and 1.18 degrees
+ because the Euler encoding changes. The synthetic interval from the optional
+ T-pose to original frame one showed larger interpolation differences (104.73 mm,
+ 18.63 degrees). No keyed pose was altered. Prefer Generic/Blender when preserving
+ the existing channel interpolation is needed.
+- Verified all-person request propagation, profile visibility/default, shared
+ placement with leading T-pose, gimbal/branch-cut sequences crossing bounded
+ blocks, and the cancellable BVH save entry. Default Generic output remained
+ byte-identical. Unknown profiles, invalid data and cancellation retained existing
+ destinations and removed staged partial files; original source stamps stayed fixed.
+- 3ds Max was not installed. Actual Biped loading/retargeting remains unverified;
+ Blender import is not a substitute for that application test.
+
+### Optional background camera rotation refinement (2026-11-02)
+
+Added default-off FlowHMR/ExMR controls for PR #18-derived camera display
+post-processing. Existing source tracking, poses, contacts and animation export
+remain unchanged; Static Camera is skipped. No AI inference or additional runtime
+installation is introduced.
+
+- An isolated textured-scene fixture with a known 1.1-degree rotation accepted
+ 15/15 samples and ended with approximately 0.0042-degree rotation error. Camera
+ centers and input matrices were unchanged. This is an implementation fixture,
+ not a real-scene accuracy benchmark.
+- On an existing 267-frame moving-camera clip, the adaptation matched the PR
+ implementation exactly: all 45 samples were rejected and the original track
+ was retained. The GUI reported 0/45; off restored the original matrices exactly,
+ and re-enabling reused the validated session result.
+- Verified dependency invalidation, static skip, Unicode working paths, malformed
+ legacy view preferences, optional-worker failure fallback, temporary-file cleanup
+ and termination after observed fit progress (6/106 samples; approximately 0.013s
+ from cancellation to child reaping on this PC).
+- During the real-clip toggle test, 120 distinct frames were delivered with median
+ 33.1ms, p95 37.4ms and maximum 38.7ms intervals. Image/camera/pose mixed pairs: zero.
+ Frame and orbit/pan state were retained; original project stamps were unchanged.
+ A separate short UI heartbeat test had a maximum gap around 12.1ms. These short
+ checks do not guarantee universal playback speed or long-run leak freedom.
+- Existing ExMR/GVHMR camera overlay and seek checks and the 2267-frame FlowHMR
+ saved-camera regression passed with refinement off. Console output and the
+ command-window mirror included the refinement result and cache reuse.
+
+### Portable Blender and MAMMA scene export (2026-11-02)
+
+Added `.blend` to source export with PR #18-derived portable video/camera
+bundles and a MAMMA-only whole-scene option. Camera tracking, approximate
+movement scale and optional background refinement affect cameras only. Whole
+MAMMA scenes retain the original common timeline and reject inserted T-poses.
+
+- Exported an existing 174-frame ExMR take, a 510-frame FlowHMR take with a
+ leading T-pose and saved moving camera, a 267-frame GVHMR original and a
+ PromptHMR original in its shared scene. All worker saves completed; existing
+ source files were retained. No model inference or clean installation was run.
+- Exported a corrected MAMMA scene with two people, four cameras and 493 frames.
+ The existing working videos, full body surfaces and reference skeletons were
+ used. Moved the ExMR/FlowHMR/MAMMA bundle folders into accented/Korean paths
+ and reopened them in Blender 4.5. Relative movie and PC2 references resolved.
+- At original frames 0, 80 and the last frame, imported skeleton head errors
+ were at most 0.0048 mm; general bundle bone matrices matched a direct FBX
+ import within 1e-6. MAMMA evaluated PC2 surfaces matched the independently
+ evaluated selected cache at those frames. Armature object transforms had no
+ animation keys; whole-scene visibility keys are separate timeline controls.
+- All four MAMMA camera matrices and render aspects were checked. Pinhole
+ projection differences were below 0.0046 px in the tested points. A separate
+ unequal-focal-length/off-center fixture was below 0.00015 px. These verify
+ serialization/projection, not absolute camera-estimation accuracy.
+- On this PC, the initial worker builds took about 7.4s ExMR, 5.1s FlowHMR
+ and 6.6s for the MAMMA scene; sampled worker-tree peak RSS was about
+ 441/257/373 MiB respectively. These short-case observations are not general
+ speed or memory guarantees. Output size grows with videos and PC2 frames.
+- Checked existing-destination retention, failed-build cleanup, stale selection
+ rejection and cancellation while a real Blender child was active. The child
+ was reaped and owned staging directories removed; source project stamps were
+ unchanged. GUI option scoping, default FBX options, MAMMA T-pose exclusion
+ and compact dialog text layout passed. Existing FBX golden bytes, BVH
+ original-frame suffix and camera/video sharing checks still passed.
+
+### Export/camera release review (2026-11-02)
+
+The final review additionally tested a delayed MAMMA take (visible on frames
+5 through 84, hidden at 4 and 85), with a person named identically to a camera.
+Camera-view scenes now keep direct camera-object references instead of looking
+them up by potentially colliding Blender names. Half-open visibility and PC2
+offsets passed; sampled surface error was zero and the reference-skeleton head
+error stayed below 0.0039 mm. Export controls/help and every offline model guide
+were updated to FBX/BVH/Blender terminology.
+
+The 120-frame decoded-playback regression found no mixed frame/camera pairs;
+observed intervals were median 31.5 ms, p95 47.0 ms and maximum 49.9 ms. Sixty
+loader open/close cycles settled at about 192 MiB RSS after initialization,
+with 467 to 468 handles observed. These bounded tests are not a long-duration
+leak guarantee or a universal frame-rate claim. The known-rotation background
+fixture, original PR equivalence, off restoration, cache invalidation and
+worker cancellation checks also passed. Runtime locks, installer scripts,
+AI worker and source-correction implementation stayed unchanged.
diff --git a/docs/models/EXMR.md b/docs/models/EXMR.md
index d708cf0..9ebe7e5 100644
--- a/docs/models/EXMR.md
+++ b/docs/models/EXMR.md
@@ -59,7 +59,7 @@ Camera and smoothing changes take effect on **Reconstruct 3D**, not on
3. Prepare models, choose camera settings and run **Reconstruct 3D**.
4. Review the original and corrected motion. Edit foot/palm support intervals
and **Apply Correction** when needed. This reuses inference results.
-5. Use **File > Export FBX** for the displayed applied source motion, or
+5. Use **File > Export...** (FBX, BVH or Blender) for the displayed applied source motion, or
[import and retarget a character](../USER_GUIDE.md#character-retargeting).
Processing uses a 30 fps working clip and preserves the source video. Saved
@@ -134,3 +134,32 @@ Please also credit FootMR and the original GVHMR work.
year = {2026},
}
```
+
+
+### Camera display
+
+The viewport Camera switch can show estimated movement for Moving Camera mode.
+Camera rotation comes from the stored SimpleVO track; approximate displacement
+is derived from the ORIGINAL paired world/camera body-root predictions, without
+rerunning inference. Body prediction errors can appear as camera movement.
+Static Camera retains a fixed position. Motion x controls the gizmo/path distance
+scale (default 1; 0 fixes the center), independently of the video overlay and
+exported animation. A full-video reference take is required for displacement;
+otherwise a notice identifies rotation-only display.
+
+
+### Optional background camera rotation refinement
+
+**Refine Camera Rotation** is a default-off checkbox below the camera setting.
+It uses PR #18's background-feature method to validate corrections of up to
+2 degrees to the saved moving-camera rotation. It masks known actors and keeps
+unreliable samples unchanged; static-camera results are skipped. Fast movement,
+parallax or sparse/blurred backgrounds may prevent any correction from being accepted.
+
+This is CPU post-processing for video bone overlays, Camera Preview and camera
+gizmos. It runs when a camera display is needed and does not rerun motion inference
+or modify original tracking files, camera centers, motion/contact results or
+FBX/BVH animation. Off restores the original saved camera path. Workspace view
+settings preserve the checkbox; verified session results can be reused. No extra
+runtime/models are needed. Progress, accepted counts and time are reported in the
+app/Console/CMD. See [the camera preview guide](../USER_GUIDE.md#saved-cameras-and-camera-preview).
diff --git a/docs/models/FLOWHMR.md b/docs/models/FLOWHMR.md
index a58576d..7ebf745 100644
--- a/docs/models/FLOWHMR.md
+++ b/docs/models/FLOWHMR.md
@@ -75,7 +75,7 @@ used another 2.13 GiB of allocated VRAM. These are one-PC observations.
3. Prepare the required files and choose the camera option, then **Reconstruct 3D**.
4. Review contact correction, edit timings and **Apply Correction** if needed.
Original motion is retained; applying contact changes does not rerun FlowHMR.
-5. Use **File > Export FBX** for the displayed applied motion, or
+5. Use **File > Export...** (FBX, BVH or Blender) for the displayed applied motion, or
[retarget an imported character](../USER_GUIDE.md#character-retargeting).
The working clip is 30 fps; the source video is preserved. The app supports up
@@ -168,3 +168,29 @@ package profiles and model files are retained. Valid feature caches remain usabl
## Citation
[FlowHMR paper](https://arxiv.org/abs/2610.03691) · [Research citations and BibTeX](../CITATIONS.md#flowhmr)
+
+
+### Camera display
+
+The viewport Camera switch shows stored camera rotation and the estimated VGGT
+movement path. Displacement is not metrically calibrated; it is a rough visual
+guide. Motion x adjusts the displayed displacement scale (default 1; 0 fixes the
+camera center). This controls camera gizmos/path only. Video overlays retain
+their saved calibrated projection, and animation/correction/export are unchanged.
+
+
+### Optional background camera rotation refinement
+
+**Refine Camera Rotation** is a default-off checkbox below the camera setting.
+It uses PR #18's background-feature method to validate corrections of up to
+2 degrees to the saved moving-camera rotation. It masks known actors and keeps
+unreliable samples unchanged; static-camera results are skipped. Fast movement,
+parallax or sparse/blurred backgrounds may prevent any correction from being accepted.
+
+This is CPU post-processing for video bone overlays, Camera Preview and camera
+gizmos. It runs when a camera display is needed and does not rerun motion inference
+or modify original tracking files, camera centers, motion/contact results or
+FBX/BVH animation. Off restores the original saved camera path. Workspace view
+settings preserve the checkbox; verified session results can be reused. No extra
+runtime/models are needed. Progress, accepted counts and time are reported in the
+app/Console/CMD. See [the camera preview guide](../USER_GUIDE.md#saved-cameras-and-camera-preview).
diff --git a/docs/models/GVHMR.md b/docs/models/GVHMR.md
index 9675cd1..c08c4c3 100644
--- a/docs/models/GVHMR.md
+++ b/docs/models/GVHMR.md
@@ -56,7 +56,7 @@ Existing projects retain their saved selections.
3. Prepare models for enabled add-ons and run **Reconstruct 3D**.
4. Review the selected result and correction. Foot contacts and palm support
are edited on the timeline; **Apply Correction** reuses inferred motion.
-5. **File > Export FBX** follows the displayed applied result, including its
+5. **File > Export...** (FBX, BVH or Blender) follows the displayed applied result, including its
enabled add-ons. [Character retargeting](../USER_GUIDE.md#character-retargeting)
uses that source motion and applied contact timings.
diff --git a/docs/models/PROMPTHMR.md b/docs/models/PROMPTHMR.md
index 73eb512..00bacec 100644
--- a/docs/models/PROMPTHMR.md
+++ b/docs/models/PROMPTHMR.md
@@ -134,7 +134,7 @@ from an arbitrary machine or edit registration files to mark them Ready.
- Check People rows to show/hide actors and select a row to edit contacts.
**Enable Correction** switches original/corrected motion. **Apply Correction**
does not rerun PromptHMR and refreshes linked characters. Correction may
- intentionally change poses. Export through **File > Export FBX**, or retarget
+ intentionally change poses. Export through **File > Export...** (FBX, BVH or Blender), or retarget
to an imported character.
The working video is sampled at 30 fps. The current adapter accepts **4–1,800
diff --git a/docs/models/README.md b/docs/models/README.md
index d61497b..bce69e8 100644
--- a/docs/models/README.md
+++ b/docs/models/README.md
@@ -55,7 +55,7 @@ MAMMA is a separate multi-view workflow rather than another single-video option.
and license acceptance; Google Drive downloads may need manual import.
4. Open footage, trim, reconstruct and review. Contact correction defaults on;
Foot defaults on and Hand off. Edit contact timings and **Apply Correction**
- without rerunning AI inference. Export the displayed applied motion as FBX.
+ without rerunning AI inference. **File > Export...** offers FBX, BVH or a portable Blender project for the displayed applied motion. MAMMA also offers checked bodies and all cameras in one Blender scene; see [export options](../USER_GUIDE.md#fbx-and-blender).
For PEAR, use **Start Live Tracking** instead of reconstruction. It displays
live bones only; offline contact, project-save, retarget and export steps do not
diff --git a/mocap/biped_bvh.py b/mocap/biped_bvh.py
new file mode 100644
index 0000000..bbeacf3
--- /dev/null
+++ b/mocap/biped_bvh.py
@@ -0,0 +1,88 @@
+"""PR #18-derived Character Studio naming and uniform ZXY export encoding.
+
+Converts only the exported copy; source hierarchy offsets and keyed poses remain.
+"""
+import warnings
+import numpy as np
+from scipy.spatial.transform import Rotation
+
+
+def bone_names():
+ names={'Hips':'Hips','Spine':'Chest','Spine1':'Chest2','Spine2':'Chest3',
+ 'Neck':'Neck','Head':'Head'}
+ for side in ('Left','Right'):
+ for source,target in [('UpLeg','Hip'),('Leg','Knee'),('Foot','Ankle'),
+ ('ToeBase','Toe'),('Shoulder','Collar'),('Arm','Shoulder'),
+ ('ForeArm','Elbow'),('Hand','Wrist')]:
+ names[side+source]=side+target
+ for digit,finger in enumerate(('Thumb','Index','Middle','Ring','Pinky')):
+ for segment in range(1,4):
+ names[f'{side}Hand{finger}{segment}']=f'{side}Finger{digit}'+('' if segment==1 else str(segment-1))
+ return names
+
+
+def convert(inp,out,progress=lambda:None):
+ mapping=bone_names();orders=[];seen=[]
+ for _ in range(4096):
+ line=inp.readline(65537)
+ if not line or len(line)>65536:raise ValueError('Invalid BVH hierarchy')
+ tokens=line.split()
+ if tokens[:1] in ([b'ROOT'],[b'JOINT']):
+ if len(tokens)!=2:raise ValueError('Invalid BVH joint declaration')
+ name=tokens[1].decode('ascii')
+ if name not in mapping:raise ValueError('Unsupported Biped bone: '+name)
+ if name in seen or (not seen and tokens[0]!=b'ROOT') or (seen and tokens[0]==b'ROOT'):
+ raise ValueError('Invalid BVH hierarchy root or duplicate joint')
+ if not seen and name!='Hips':raise ValueError('Expected Hips as BVH root')
+ seen.append(name)
+ line=line.replace(tokens[1],mapping[name].encode('ascii'),1)
+ elif tokens[:1]==[b'OFFSET']:
+ offset=np.asarray(tokens[1:],dtype=float)
+ if offset.shape!=(3,) or not np.isfinite(offset).all():raise ValueError('Invalid BVH offset')
+ elif tokens[:1]==[b'CHANNELS']:
+ if len(tokens)<2:raise ValueError('Invalid BVH channels')
+ count=int(tokens[1]);rot=tokens[5:] if not orders else tokens[2:]
+ if not orders and tokens[2:5]!=[b'Xposition',b'Yposition',b'Zposition']:
+ raise ValueError('Unsupported BVH root translation channels')
+ if count!=(6 if not orders else 3) or sorted(rot)!=[b'Xrotation',b'Yrotation',b'Zrotation']:
+ raise ValueError('Unsupported BVH channels')
+ orders.append(''.join(x[:1].decode('ascii') for x in rot))
+ indent=line[:len(line)-len(line.lstrip())]
+ line=indent+(b'CHANNELS 6 Xposition Yposition Zposition ' if len(orders)==1 else b'CHANNELS 3 ')+b'Zrotation Xrotation Yrotation\n'
+ out.write(line)
+ if line.strip()==b'MOTION':break
+ else:raise ValueError('BVH hierarchy too large')
+ if len(orders)!=52 or len(seen)!=52 or set(seen)!=set(mapping):raise ValueError('Expected complete source skeleton')
+ count_line=inp.readline(256);time_line=inp.readline(256)
+ if not count_line.startswith(b'Frames:') or not time_line.startswith(b'Frame Time:'):raise ValueError('Invalid BVH header')
+ count=int(count_line.split(b':')[1]);step=float(time_line.split(b':')[1])
+ if count<1 or not np.isfinite(step) or step<=0:raise ValueError('Invalid BVH timing')
+ out.write(count_line);out.write(time_line)
+ previous=np.zeros((52,3))
+ for start in range(0,count,128):
+ rows=[]
+ for _ in range(min(128,count-start)):
+ line=inp.readline(65537)
+ if len(line)>65536:raise ValueError('BVH frame too large')
+ fields=line.split()
+ if len(fields)!=159:raise ValueError('Invalid BVH frame')
+ rows.append(np.asarray(fields,dtype=float))
+ values=np.asarray(rows)
+ if not np.isfinite(values).all():raise ValueError('Non-finite BVH motion')
+ for j,order in enumerate(orders):
+ column=slice(3+3*j,6+3*j)
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore',message='Gimbal lock detected')
+ angles=Rotation.from_euler(order,values[:,column],degrees=True).as_euler('ZXY')
+ for index,angle in enumerate(angles):
+ alternative=angle.copy();alternative[0]+=np.pi
+ alternative[1]=np.pi-alternative[1];alternative[2]+=np.pi
+ angle=angle+2*np.pi*np.round((previous[j]-angle)/(2*np.pi))
+ alternative+=2*np.pi*np.round((previous[j]-alternative)/(2*np.pi))
+ angles[index]=angle if np.linalg.norm(angle-previous[j])<=np.linalg.norm(alternative-previous[j]) else alternative
+ previous[j]=angles[index]
+ previous[j]=angles[-1]
+ values[:,column]=np.degrees(angles)
+ for row in values:out.write((' '.join(f'{v:.9f}' for v in row)+'\n').encode('ascii'))
+ progress()
+ if inp.read(1):raise ValueError('Unexpected BVH trailing data')
diff --git a/mocap/blend_export.py b/mocap/blend_export.py
new file mode 100644
index 0000000..ee8177b
--- /dev/null
+++ b/mocap/blend_export.py
@@ -0,0 +1,92 @@
+"""PR #18-derived portable source animation, source video and camera bundles."""
+import json
+from pathlib import Path
+import numpy as np
+from .blend_support import Inputs,Bundle,read,copy_video,build,disk_check
+
+
+def run(request,emit=lambda *a,**k:None):
+ from .motion_tools import selected_export
+ from .scene_export import context
+ from .fbx_export import run as export_fbx
+ from .camera_tracks import load,at
+ from .camera_background_worker import refined,current
+ from .video import probe
+ request=Path(request);bundles=[];checks=[];cache={}
+ try:
+ rows=read(request)
+ if not isinstance(rows,list) or not 1<=len(rows)<=4096:raise ValueError('Invalid Blender export request')
+ folders=set()
+ for row in rows:
+ folder=Path(row['target']).resolve().parent
+ if str(folder).casefold() in folders:raise ValueError('Duplicate Blender bundle destination')
+ folders.add(str(folder).casefold())
+ for row in rows:
+ project=Path(row['project']).resolve();kind=row['kind'];source=Path(row['source']).resolve();inputs=Inputs()
+ if selected_export(project,kind)!=source:raise ValueError('Selected motion changed. Prepare Preview or Apply Correction first.')
+ state=read(inputs.track(project/'project.json'));info=read(inputs.track(project/(kind+'_mixamo.json')))
+ for key in ('asset_file','frames_file'):
+ if Path(info[key]).name!=info[key]:raise ValueError('Invalid committed animation path')
+ inputs.track(project/info[key])
+ inputs.track(source);scene=row.get('scene')
+ if scene is not None and context(scene['root'],project)!=scene:raise ValueError('Shared scene placement changed')
+ group=scene['root'] if scene is not None else None
+ cameras=load(project,group)
+ if row.get('background_refine',False) and row.get('animate_camera',True):
+ cameras=refined(cameras,project,lambda:False,
+ lambda done,total:emit('progress',stage='save_blend',current=done,total=total,message='Refining camera rotation'),cache)
+ for item in cache.values():
+ if not current(item['sources']):raise ValueError('Background camera inputs changed during export')
+ for p,_ in item['sources']:inputs.track(p)
+ if not current(list(cameras['camera_sources'].items())):raise ValueError('Camera sources changed during export')
+ for p in cameras['camera_sources']:inputs.track(p)
+ camera=cameras['cameras'][0];n=int(info['frames']);fps=float(info['fps'])
+ if abs(camera['K'][0,1])>1e-6:raise ValueError('Blender export requires camera intrinsics without skew')
+ if n!=int(state['frames']) or abs(fps-state['fps'])>1e-6:raise ValueError('Video and selected animation timing differ')
+ scale=float(row.get('camera_translation_scale',1.))
+ if not np.isfinite(scale) or not 0<=scale<=100:raise ValueError('Invalid camera movement scale')
+ animate=row.get('animate_camera',True)
+ times=state['start']+np.arange(n)/fps
+ track=[at(camera,t,scale if animate else 0.) for t in times]
+ if any(m is None for m in track):raise ValueError('Saved camera does not cover the selected motion')
+ track=np.asarray(track)
+ if not animate:track[:]=track[0]
+ video=inputs.track(project/'input.mp4');media=probe(video)
+ if (media['frames']!=n or abs(media['fps']-fps)>.001
+ or [media['width'],media['height']]!=list(camera['size'])):
+ raise ValueError('Source video timing or resolution differs from the saved camera')
+ disk_check(Path(row['target']).parent.parent,video.stat().st_size+source.stat().st_size*4)
+ bundle=Bundle(row['target'],request);bundles.append(bundle);work=bundle.work
+ copy_video(video,work/'video.mp4',emit,'save_blend')
+ nested=work/'fbx-request.json';nested.write_text(json.dumps([{**row,'target':str(work/'animation.fbx')}]),encoding='utf-8')
+ export_fbx(nested,emit)
+ np.save(work/'camera.npy',track,allow_pickle=False)
+ job=dict(target=bundle.target.name,frames=n,fps=fps,width=media['width'],height=media['height'],
+ world_to_camera=track[0].tolist(),K=camera['K'].tolist(),prepend_tpose=bool(row.get('prepend_tpose')),
+ camera_track='camera.npy' if animate and not np.array_equal(track,np.broadcast_to(track[0],track.shape)) else None,
+ camera_mode=cameras['note'])
+ (work/'blend-job.json').write_text(json.dumps(job),encoding='utf-8')
+ emit('progress',stage='save_blend',current=0,total=0,message='Building Blender project')
+ build(work,'blend_export_scene.py',emit,'save_blend')
+ report=dict(model=cameras['model'],result=kind,frames=n,fps=fps,video_start_frame=int(job['prepend_tpose']),
+ camera_mode=cameras['note'],camera_warning=cameras.get('warning',''),animate_camera=bool(animate),
+ camera_movement_scale=scale,background_refinement=cameras.get('background_report'),
+ camera_translation='Approximate display estimate, not measured metric camera motion')
+ (work/'camera_report.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
+ (work/'README.txt').write_text('Open '+bundle.target.name+' in Blender 4.5 or newer.\n'
+ 'Keep video.mp4 beside the .blend file when moving this folder.\n'
+ 'Numpad 0: camera view. Space: playback. The video is a viewport background, not a render background.\n'
+ 'The source armature is editable. An optional T-pose is one extra animation frame; the video starts after it.\n'
+ 'Camera movement may include reconstruction error and arbitrary scale; it is not measured calibration.\n'
+ 'See camera_report.json. Source motion and original camera files were not changed.\n',encoding='utf-8')
+ for name in ('animation.fbx','blend-job.json','blender.log','camera.npy'):(work/name).unlink(missing_ok=True)
+ checks.append((inputs,project,kind,source,scene))
+ for inputs,project,kind,source,scene in checks:
+ inputs.verify()
+ if selected_export(project,kind)!=source:raise ValueError('Motion changed during export')
+ if scene is not None and context(scene['root'],project)!=scene:raise ValueError('Scene placement changed during export')
+ for bundle in bundles:bundle.publish()
+ return len(bundles)
+ finally:
+ for bundle in bundles:bundle.close()
+ request.unlink(missing_ok=True)
diff --git a/mocap/blend_export_scene.py b/mocap/blend_export_scene.py
new file mode 100644
index 0000000..746ba13
--- /dev/null
+++ b/mocap/blend_export_scene.py
@@ -0,0 +1,78 @@
+"""PR #18-derived Blender-only builder for a portable camera/video/skeleton scene."""
+import json,sys
+from pathlib import Path
+import bpy
+from mathutils import Matrix
+
+def progress(current,total,message):
+ print('@@BLEND@@'+json.dumps(dict(current=current,total=total,message=message)),flush=True)
+
+folder=Path(sys.argv[sys.argv.index('--')+1])
+job=json.loads((folder/'blend-job.json').read_text(encoding='utf-8'))
+progress(0,0,'Importing source animation')
+bpy.ops.wm.read_factory_settings(use_empty=True)
+bpy.ops.import_scene.fbx(filepath=str(folder/'animation.fbx'),anim_offset=0,
+ automatic_bone_orientation=False,use_prepost_rot=True,ignore_leaf_bones=True)
+scene=bpy.context.scene
+fps=float(job['fps']);scene.render.fps=round(fps);scene.render.fps_base=round(fps)/fps
+scene.render.resolution_x=job['width'];scene.render.resolution_y=job['height'];scene.render.resolution_percentage=100
+start=int(job['prepend_tpose']);scene.frame_start=0;scene.frame_end=job['frames']-1+start
+scene.unit_settings.system='METRIC';scene.unit_settings.scale_length=1
+arms=[o for o in scene.objects if o.type=='ARMATURE']
+if len(arms)!=1:raise ValueError('Expected one exported source armature')
+arm=arms[0];arm.show_in_front=True;arm.data.display_type='OCTAHEDRAL'
+camera=bpy.data.cameras.new('Source video camera');obj=bpy.data.objects.new(camera.name,camera)
+scene.collection.objects.link(obj);scene.camera=obj
+# FBX Y-up world -> Blender Z-up; CV camera (+Z forward, +Y down) -> Blender camera.
+world=Matrix(((1,0,0,0),(0,0,-1,0),(0,1,0,0),(0,0,0,1)))
+cv=Matrix.Diagonal((1,-1,-1,1))
+obj.matrix_world=world@Matrix(job['world_to_camera']).inverted()@cv
+if job.get('camera_track'):
+ import numpy as np
+ track=np.load(folder/job['camera_track'],allow_pickle=False,mmap_mode='r')
+ if track.shape!=(job['frames'],4,4):raise ValueError('Invalid camera track length')
+ obj.rotation_mode='QUATERNION';previous=None
+ for frame in range(job['frames']):
+ if frame%100==0:progress(frame,job['frames'],'Baking camera animation')
+ matrix=world@Matrix(track[frame].tolist()).inverted()@cv
+ location,rotation,scale=matrix.decompose()
+ if previous is not None and rotation.dot(previous)<0:rotation.negate()
+ obj.location=location;obj.rotation_quaternion=rotation;previous=rotation.copy()
+ obj.keyframe_insert(data_path='location',frame=frame+start)
+ obj.keyframe_insert(data_path='rotation_quaternion',frame=frame+start)
+ if frame==0 and start:
+ obj.keyframe_insert(data_path='location',frame=0)
+ obj.keyframe_insert(data_path='rotation_quaternion',frame=0)
+ track._mmap.close()
+ for curve in obj.animation_data.action.fcurves:
+ for key in curve.keyframe_points:key.interpolation='LINEAR'
+k=job['K'];width=job['width'];height=job['height']
+camera.type='PERSP';camera.sensor_fit='HORIZONTAL';camera.sensor_width=36
+camera.lens=k[0][0]*36/width
+ratio=k[0][0]/k[1][1]
+scene.render.pixel_aspect_x=max(1.,1./ratio);scene.render.pixel_aspect_y=max(1.,ratio)
+camera.shift_x=(width/2-k[0][2])/width
+camera.shift_y=(k[1][2]-height/2)*ratio/width
+camera.clip_start=.01;camera.clip_end=10000
+camera.show_background_images=True
+background=camera.background_images.new();background.source='IMAGE'
+clip=bpy.data.images.load(str(folder/'video.mp4'));clip.filepath='//video.mp4'
+background.image=clip
+background.image_user.frame_start=start
+background.image_user.frame_duration=job['frames']
+background.image_user.use_auto_refresh=True
+background.image_user.use_cyclic=False
+background.alpha=1;background.display_depth='BACK';background.frame_method='FIT'
+scene['RGBMoCap video start']=start
+scene['RGBMoCap camera']=job.get('camera_mode','Stored reference camera')
+scene['RGBMoCap video']='Keep video.mp4 next to this Blender project'
+for screen in bpy.data.screens:
+ for area in screen.areas:
+ if area.type=='VIEW_3D':
+ space=area.spaces.active;space.region_3d.view_perspective='CAMERA'
+ space.overlay.show_floor=False;space.overlay.show_axis_x=False;space.overlay.show_axis_y=False
+for item in bpy.context.selected_objects:item.select_set(False)
+arm.select_set(True);bpy.context.view_layer.objects.active=arm
+scene.frame_set(start)
+progress(0,0,'Saving portable Blender project')
+bpy.ops.wm.save_as_mainfile(filepath=str(folder/job['target']),check_existing=False)
diff --git a/mocap/blend_export_ui.py b/mocap/blend_export_ui.py
new file mode 100644
index 0000000..17c82e3
--- /dev/null
+++ b/mocap/blend_export_ui.py
@@ -0,0 +1,41 @@
+"""Small GUI request preparation; all baking/copying runs in a worker."""
+import uuid
+from pathlib import Path
+from PySide6.QtWidgets import QFileDialog
+
+
+def targets(files):
+ used=set();result=[]
+ for project,kind,source,target in files:
+ target=Path(target);folder=target.with_suffix('');number=2
+ while folder.exists() or str(folder.resolve()).casefold() in used:
+ folder=target.parent/(target.stem+'_'+str(number));number+=1
+ used.add(str(folder.resolve()).casefold());result.append((project,kind,source,folder/target.name))
+ return result
+
+
+def export_scene(w):
+ from .storage import atomic_json
+ from .people_store import safe_child
+ from .motion_tools import selected_export
+ from .blend_support import partial,read
+ try:
+ if w.people_root is None or read(w.people_root/'project.json').get('pipeline',{}).get('model')!='mamma':
+ raise ValueError('Open a reconstructed MAMMA people scene first.')
+ people=w.checked_people()
+ if not people:raise ValueError('Check the people to include in the scene.')
+ for person in people:
+ if not person['takes']:raise ValueError(person['name']+': no reconstructed motion.')
+ for take in person['takes']:
+ if selected_export(safe_child(w.people_root,take['project']),w.active_result) is None:
+ raise ValueError(person['name']+': Apply Correction or Prepare Preview for the selected result first.')
+ name,_=QFileDialog.getSaveFileName(w,'Export MAMMA Blender Scene','MAMMA scene.blend','Blender (*.blend)',options=QFileDialog.DontConfirmOverwrite)
+ if not name:return
+ target=Path(name)
+ if target.suffix.lower()!='.blend':target=target.with_suffix('.blend')
+ target=targets([(None,None,None,target)])[0][3]
+ request=w.project/('.scene-export-'+uuid.uuid4().hex+'.json')
+ atomic_json(request,dict(root=str(w.people_root),kind=w.active_result,people=[p['id'] for p in people],target=str(target)))
+ w._motion_export_targets=[str(target)];w._fbx_export_cleanup=(request,[partial(target.parent,request)])
+ w.start_jobs([('save_blend_scene',['--project',str(w.project),'--output',str(request)])])
+ except (OSError,ValueError,KeyError) as error:w.status.setText('MAMMA scene export unavailable: '+str(error))
diff --git a/mocap/blend_export_worker.py b/mocap/blend_export_worker.py
new file mode 100644
index 0000000..8fede24
--- /dev/null
+++ b/mocap/blend_export_worker.py
@@ -0,0 +1,14 @@
+"""Derived Blender export worker; does not change inference cache identities."""
+def main(emit):
+ import argparse,sys,time
+ from pathlib import Path
+ from .compute_policy import configure_worker_cpu
+ stage=sys.argv[1];configure_worker_cpu(stage)
+ parser=argparse.ArgumentParser();parser.add_argument('--project',type=Path,required=True);parser.add_argument('--output',type=Path,required=True)
+ args=parser.parse_args(sys.argv[2:]);started=time.monotonic()
+ if stage=='save_blend_scene':from .blend_multicam_export import run
+ elif stage=='save_blend':from .blend_export import run
+ else:raise ValueError('Unknown Blender export stage')
+ count=run(args.output,emit)
+ emit('complete',stage=stage,files=count,elapsed=time.monotonic()-started)
+ return 0
diff --git a/mocap/blend_multicam_export.py b/mocap/blend_multicam_export.py
new file mode 100644
index 0000000..d718861
--- /dev/null
+++ b/mocap/blend_multicam_export.py
@@ -0,0 +1,124 @@
+"""Transactional MAMMA scene export; no inference and no project writes."""
+import json, struct
+from pathlib import Path
+import numpy as np
+from .result_artifacts import file_stat, artifacts_current
+from .motion_tools import selected_export, result_is_current
+from .blend_support import Bundle,read,copy_video,build,disk_check
+
+
+def run(request, emit=lambda *a, **k: None):
+ from .people_store import safe_child, load_people
+ from .scene_export import context
+ from .scene_camera import validate_transform, read_camera
+ from .mamma_body import WORLD_ROTATION
+ from .mesh_data import reference_vertices
+ from .fbx_export import run as export_fbx
+ from .video import probe
+ request=Path(request);temporary=None;bundle=None
+ if request.stat().st_size>4*1024**2:raise ValueError('Export request is too large')
+ spec=read(request);root=Path(spec['root']).resolve();target=Path(spec['target']).resolve()
+ if target.suffix.lower()!='.blend' or target.parent.exists() or not target.parent.parent.is_dir():
+ raise ValueError('Choose a new Blender bundle folder')
+ tracked={};checks=[]
+ def track(path):
+ path=Path(path);tracked[path]=file_stat(path);return path
+ try:
+ state=read(track(root/'project.json'))
+ if state.get('pipeline',{}).get('model')!='mamma':raise ValueError('Whole-scene export requires a MAMMA result')
+ if (root/'mamma_pending.json').exists():raise ValueError('MAMMA publication is incomplete')
+ work=(root/state['mamma_work']).resolve()
+ workspace=(root/state['workspace_root']).resolve()
+ if not work.is_relative_to(workspace):raise ValueError('Invalid MAMMA data path')
+ cameras=read(track(work/'camera-world.json'));entries=read(track(work/'inputs.json'))
+ if len(entries)<2 or set(cameras)!={e['id'] for e in entries}:raise ValueError('Camera calibration and videos differ')
+ people=load_people(root);track(root/'people.json');track(root/'people_scene.json')
+ ids=spec['people'];kind=spec['kind']
+ if not isinstance(ids,list) or not 1<=len(ids)<=8 or len(set(ids))!=len(ids):raise ValueError('Select at least one person')
+ selected=[p for p in people['people'] if p['id'] in ids]
+ if len(selected)!=len(ids):raise ValueError('Selected people changed')
+ n=int(state['frames']);fps=float(state['fps']);actors=[]
+ if not 1<=n<=1800 or not np.isfinite(fps) or fps<=0:raise ValueError('Invalid MAMMA scene timing')
+ for person in selected:
+ if not person['takes']:raise ValueError('Selected person has no animation')
+ for take in person['takes']:
+ p=safe_child(root,take['project']);meta=read(track(p/'project.json'))
+ source=selected_export(p,kind)
+ if source is None or not result_is_current(p,kind) or not artifacts_current(p,kind):
+ raise ValueError(person['name']+': selected result is stale. Apply Correction or Prepare Preview first.')
+ track(source);scene=context(root,p)
+ if not np.allclose(scene['transform'],np.eye(4),atol=1e-6):raise ValueError('MAMMA actors must share one native world')
+ first,end=map(int,meta['person_frames'])
+ if not 0<=first<end<=n or end-first!=meta['frames'] or abs(meta['fps']-fps)>1e-6:raise ValueError('Invalid actor timing')
+ info=read(track(p/(kind+'_mesh.json')))
+ if Path(info['frames_file']).name!=info['frames_file']:raise ValueError('Invalid mesh cache path')
+ asset=track(Path(info['asset']));frames=track(p/info['frames_file'])
+ if info.get('version')!=1 or info['frames']!=end-first:raise ValueError('Prepare the current mesh preview first')
+ for suffix in ('_mixamo.json','_artifacts.json'):
+ track(p/(kind+suffix))
+ checks.append((p,source,scene))
+ actors.append(dict(project=p,name=person['name'],color=person['color'],first=first,end=end,asset=asset,frames=frames,source=source,scene=scene))
+ primary=entries[0]['id'];camera_jobs=[]
+ for i,e in enumerate(entries):
+ name=e['id']
+ if Path(name).name!=name or any(c in name for c in '/\\:'):raise ValueError('Invalid camera name')
+ c=cameras[name];k=np.asarray(c['intrinsic_matrix'],float);ext=np.asarray(c['extrinsics_matrix'],float)
+ if k.shape!=(3,3) or not np.isfinite(k).all() or min(k[0,0],k[1,1])<=0 or abs(k[0,1])>1e-6:raise ValueError('Unsupported camera intrinsics')
+ if np.any(np.abs(c.get('distortion_coeffs',[0]))>1e-8):raise ValueError('This Blender scene export requires undistorted camera videos/calibration')
+ if ext.shape!=(3,4):raise ValueError('Invalid camera extrinsics')
+ w2c=np.eye(4);w2c[:3,:3]=ext[:,:3]@WORLD_ROTATION.T;w2c[:3,3]=ext[:,3];validate_transform(w2c)
+ video=track(work/'videos'/(name+'.mp4'));media=probe(video)
+ if media['frames']!=n or abs(media['fps']-fps)>.001 or [media['width'],media['height']]!=c['image_size']:raise ValueError('Camera video timing/resolution differs from calibration: '+name)
+ camera_jobs.append(dict(name=name,K=k.tolist(),world_to_camera=w2c.tolist(),width=media['width'],height=media['height'],video=f'videos/camera_{i+1:03}.mp4',source=video))
+ for p,_,_ in checks:
+ camera=read_camera(p)
+ if camera is None or not np.allclose(camera['world_to_camera'],camera_jobs[0]['world_to_camera'],atol=1e-6):raise ValueError('Primary camera changed. Prepare Preview first.')
+ required=sum(file_stat(c['source'])[0] for c in camera_jobs)+sum((a['end']-a['first'])*10475*12 for a in actors)+512*1024**2
+ disk_check(target.parent.parent,required)
+ bundle=Bundle(target,request);temporary=bundle.work
+ (temporary/'videos').mkdir();(temporary/'meshes').mkdir();job_actors=[];bounds=None
+ for c in camera_jobs:copy_video(c['source'],temporary/c['video'],emit,'save_blend_scene')
+ for index,a in enumerate(actors):
+ emit('progress',stage='save_blend_scene',current=index,total=len(actors),message='Baking exact body mesh: '+a['name'])
+ stem=f'actor_{index+1:03}';cache='meshes/'+stem+'.pc2'
+ with np.load(a['asset'],allow_pickle=False) as asset:
+ packed=asset['packed'];faces=asset['faces'];count=int(asset['vertex_count'])
+ if count!=10475 or packed.size!=count*(3*507+55) or not np.isfinite(packed).all():raise ValueError('Invalid SMPL-X mesh asset')
+ if faces.ndim!=2 or faces.shape[1]!=3 or not np.issubdtype(faces.dtype,np.integer) or faces.min()<0 or faces.max()>=count:raise ValueError('Invalid mesh topology')
+ frames=np.load(a['frames'],mmap_mode='r',allow_pickle=False)
+ try:
+ if frames.shape!=(a['end']-a['first'],1389) or frames.dtype!=np.float32:raise ValueError('Unexpected SMPL-X frame layout')
+ with (temporary/cache).open('wb') as out:
+ out.write(struct.pack('<12siiffi',b'POINTCACHE2\0',1,count,0.,1.,len(frames)))
+ for f,frame in enumerate(frames):
+ vertices=reference_vertices(packed,frame,count)[:,[0,2,1]].copy();vertices[:,1]*=-1
+ if not np.isfinite(vertices).all():raise ValueError('Non-finite mesh vertices')
+ if f==0:
+ np.savez(temporary/(stem+'.npz'),vertices=vertices,faces=faces)
+ lo=vertices.min(0);hi=vertices.max(0)
+ bounds=[lo,hi] if bounds is None else [np.minimum(bounds[0],lo),np.maximum(bounds[1],hi)]
+ out.write(vertices.astype('<f4').tobytes())
+ if f%30==0:emit('progress',stage='save_blend_scene',current=f,total=len(frames),message='Mesh '+a['name'])
+ finally:frames._mmap.close()
+ nested=temporary/'fbx-request.json';nested.write_text(json.dumps([dict(project=str(a['project']),kind=kind,source=str(a['source']),target=str(temporary/(stem+'.fbx')),rig_name=a['name'],scene=a['scene'])]),encoding='utf8')
+ export_fbx(nested)
+ job_actors.append(dict(name=a['name'],color=a['color'],first=a['first'],end=a['end'],cache=cache,geometry=stem+'.npz',fbx=stem+'.fbx'))
+ job=dict(target=target.name,frames=n,fps=fps,actors=job_actors,cameras=[{k:v for k,v in c.items() if k!='source'} for c in camera_jobs],bounds=np.asarray(bounds).tolist())
+ (temporary/'scene-job.json').write_text(json.dumps(job),encoding='utf8')
+ emit('progress',stage='save_blend_scene',current=0,total=0,message='Building MAMMA Blender scene')
+ build(temporary,'blend_multicam_scene.py',emit,'save_blend_scene')
+ for path,stamp in tracked.items():
+ if file_stat(path)!=stamp:raise ValueError('Scene inputs changed during export. Retry.')
+ for p,source,scene in checks:
+ if selected_export(p,kind)!=source or not result_is_current(p,kind) or context(root,p)!=scene:raise ValueError('Selected motion changed during export')
+ report=dict(model='mamma',result=kind,frames=n,fps=fps,cameras=job['cameras'],actors=[{k:v for k,v in a.items() if k not in ('geometry','fbx')} for a in job_actors],geometry='Exact baked SMPL-X surface, separate editable source skeletons',calibration='Saved MAMMA calibration; automatic scale/floor remain estimates')
+ (temporary/'scene_report.json').write_text(json.dumps(report,indent=2),encoding='utf8')
+ (temporary/'README.txt').write_text('Open the .blend file in Blender 4.5+. Keep videos/ and meshes/ beside it.\nBodies use exact baked PC2 animation; armatures are separate editable reference skeletons, not mesh deformation rigs.\nAll cameras use the common MAMMA world. Video panels and camera backgrounds share the timeline.\nUse the scene selector: Overview shows all cameras; Camera - name scenes use matching image dimensions. Numpad 0 enters camera view.\nEach camera scene has its own output resolution and excludes video panels; camera backgrounds are viewport references.\nThe floor and lighting are presentation aids, not reconstructed scene geometry.\nNo T-pose is inserted in this synchronized scene export.\n',encoding='utf8')
+ for a in job_actors:
+ (temporary/a['geometry']).unlink();(temporary/a['fbx']).unlink()
+ for name in ('scene-job.json','blender.log'):(temporary/name).unlink()
+ bundle.publish();temporary=None
+ return 1
+ finally:
+ if bundle is not None:bundle.close()
+ request.unlink(missing_ok=True)
diff --git a/mocap/blend_multicam_scene.py b/mocap/blend_multicam_scene.py
new file mode 100644
index 0000000..47ff3e8
--- /dev/null
+++ b/mocap/blend_multicam_scene.py
@@ -0,0 +1,105 @@
+"""PR #18-derived Blender-only portable multi-view scene builder. No playback Python handlers."""
+import json,sys
+from pathlib import Path
+import bpy
+import numpy as np
+from mathutils import Matrix,Vector,Quaternion
+
+def progress(current,total,message):
+ print('@@BLEND@@'+json.dumps(dict(current=current,total=total,message=message)),flush=True)
+
+folder=Path(sys.argv[sys.argv.index('--')+1]);job=json.loads((folder/'scene-job.json').read_text(encoding='utf-8'))
+progress(0,0,'Importing source animation')
+bpy.ops.wm.read_factory_settings(use_empty=True);scene=bpy.context.scene
+scene.frame_start=0;scene.frame_end=job['frames']-1
+scene.render.fps=round(job['fps']);scene.render.fps_base=round(job['fps'])/job['fps']
+scene.unit_settings.system='METRIC';scene.unit_settings.scale_length=1
+def collection(name):
+ c=bpy.data.collections.new(name);scene.collection.children.link(c);return c
+bodies=collection('Animated bodies');rigs=collection('Reference skeletons');cameras=collection('Calibrated cameras');panels=collection('Video panels');stage=collection('Presentation')
+def move(obj,c):
+ for old in list(obj.users_collection):old.objects.unlink(obj)
+ c.objects.link(obj)
+def visibility(obj,first,end):
+ for f,hide in [(-1,True),(first,False),(end,True)]:
+ for prop in ('hide_viewport','hide_render'):
+ setattr(obj,prop,hide);obj.keyframe_insert(data_path=prop,frame=f)
+ if obj.animation_data:
+ for curve in obj.animation_data.action.fcurves:
+ if curve.data_path in ('hide_viewport','hide_render'):
+ for p in curve.keyframe_points:p.interpolation='CONSTANT'
+for actor_index,a in enumerate(job['actors']):
+ progress(actor_index,len(job['actors']),'Building animated body: '+a['name'])
+ before=set(scene.objects)
+ bpy.ops.import_scene.fbx(filepath=str(folder/a['fbx']),anim_offset=a['first'],automatic_bone_orientation=False,use_prepost_rot=True,ignore_leaf_bones=True)
+ for obj in set(scene.objects)-before:
+ move(obj,rigs);obj.show_in_front=False;visibility(obj,a['first'],a['end'])
+ with np.load(folder/a['geometry']) as z:verts=z['vertices'];faces=z['faces']
+ mesh=bpy.data.meshes.new(a['name']);mesh.from_pydata(verts.tolist(),[],faces.tolist());mesh.update()
+ obj=bpy.data.objects.new(a['name']+' body',mesh);bodies.objects.link(obj)
+ for face in mesh.polygons:face.use_smooth=True
+ color=tuple(int(a['color'][i:i+2],16)/255 for i in (1,3,5))+(1.,)
+ mat=bpy.data.materials.new(a['name']+' color');mat.diffuse_color=color;mat.use_nodes=True
+ mat.node_tree.nodes.get('Principled BSDF').inputs['Base Color'].default_value=color
+ mat.node_tree.nodes.get('Principled BSDF').inputs['Roughness'].default_value=.65
+ mesh.materials.append(mat);obj.color=color
+ mod=obj.modifiers.new('Exact recorded surface','MESH_CACHE');mod.cache_format='PC2';mod.filepath='//'+a['cache']
+ mod.play_mode='SCENE';mod.time_mode='FRAME';mod.frame_start=a['first'];mod.frame_scale=1.;mod.forward_axis='POS_Y';mod.up_axis='POS_Z'
+ mod.deform_mode='OVERWRITE';visibility(obj,a['first'],a['end'])
+camera_objects={}
+world=Matrix(((1,0,0,0),(0,0,-1,0),(0,1,0,0),(0,0,0,1)));cv=Matrix.Diagonal((1,-1,-1,1))
+for camera_index,c in enumerate(job['cameras']):
+ progress(camera_index,len(job['cameras']),'Building calibrated camera: '+c['name'])
+ data=bpy.data.cameras.new(c['name']);obj=bpy.data.objects.new(c['name'],data);cameras.objects.link(obj)
+ obj.matrix_world=world@Matrix(c['world_to_camera']).inverted()@cv
+ camera_objects[c['name']]=obj
+ k=c['K'];w=c['width'];h=c['height'];aspect=k[0][0]/k[1][1]
+ obj['video_width']=w;obj['video_height']=h;obj['pixel_aspect_y']=aspect
+ data.sensor_fit='HORIZONTAL';data.sensor_width=36;data.lens=k[0][0]*36/w
+ data.shift_x=(w/2-k[0][2])/w;data.shift_y=(k[1][2]-h/2)*aspect/w
+ data.clip_start=.01;data.clip_end=10000;data.display_size=.3;obj.show_name=True
+ if scene.camera is None:scene.camera=obj
+ image=bpy.data.images.load(str(folder/c['video']));image.filepath='//'+c['video']
+ data.show_background_images=True;bg=data.background_images.new();bg.source='IMAGE';bg.image=image
+ bg.image_user.frame_start=0;bg.image_user.frame_duration=job['frames'];bg.image_user.use_auto_refresh=True;bg.alpha=1;bg.display_depth='BACK';bg.frame_method='FIT'
+ depth=.8
+ corners=[((u-k[0][2])/k[0][0]*depth,-(v-k[1][2])/k[1][1]*depth,-depth) for u,v in [(0,h),(w,h),(w,0),(0,0)]]
+ mesh=bpy.data.meshes.new(c['name']+' screen');mesh.from_pydata(corners,[],[(0,1,2,3)]);mesh.uv_layers.new()
+ for loop,uv in zip(mesh.uv_layers.active.data,[(0,0),(1,0),(1,1),(0,1)]):loop.uv=uv
+ screen=bpy.data.objects.new(c['name']+' video',mesh);panels.objects.link(screen);screen.parent=obj
+ mat=bpy.data.materials.new(c['name']+' video');mat.use_nodes=True;nodes=mat.node_tree.nodes;nodes.clear()
+ tex=nodes.new('ShaderNodeTexImage');tex.image=image;tex.image_user.frame_start=0;tex.image_user.frame_duration=job['frames'];tex.image_user.use_auto_refresh=True;tex.interpolation='Linear'
+ emission=nodes.new('ShaderNodeEmission');output=nodes.new('ShaderNodeOutputMaterial');mat.node_tree.links.new(tex.outputs['Color'],emission.inputs['Color']);mat.node_tree.links.new(emission.outputs[0],output.inputs['Surface']);mesh.materials.append(mat)
+# Linked scenes preserve each camera's own aspect ratio without playback scripts.
+scene.render.resolution_percentage=100;scene.render.pixel_aspect_x=1
+primary=job['cameras'][0]
+scene.render.resolution_x=primary['width'];scene.render.resolution_y=primary['height']
+ratio=primary['K'][0][0]/primary['K'][1][1]
+scene.render.pixel_aspect_x=max(1.,1./ratio);scene.render.pixel_aspect_y=max(1.,ratio)
+points=np.array(job['bounds']);lo=points.min(0);hi=points.max(0);center=(lo+hi)/2;span=max(3.,float(np.max(hi-lo)))
+bpy.ops.mesh.primitive_plane_add(size=max(12.,span*3),location=(center[0],center[1],min(0.,lo[2])-.01));floor=bpy.context.object;floor.name='Reference floor (not reconstructed)';move(floor,stage)
+mat=bpy.data.materials.new('Floor');mat.use_nodes=True;nodes=mat.node_tree.nodes;checker=nodes.new('ShaderNodeTexChecker');checker.inputs['Color1'].default_value=(.16,.18,.20,1);checker.inputs['Color2'].default_value=(.24,.26,.28,1);checker.inputs['Scale'].default_value=12
+mat.node_tree.links.new(checker.outputs['Color'],nodes.get('Principled BSDF').inputs['Base Color']);floor.data.materials.append(mat)
+world_data=bpy.data.worlds.new('Studio');scene.world=world_data;world_data.use_nodes=True;world_data.node_tree.nodes.get('Background').inputs[0].default_value=(.12,.12,.12,1)
+for x,y,z,power in [(-3,-4,7,1600),(4,1,5,1000)]:
+ light=bpy.data.lights.new('Studio area','AREA');light.energy=power;light.shape='DISK';light.size=5
+ obj=bpy.data.objects.new(light.name,light);stage.objects.link(obj);obj.location=Vector(center)+Vector((x,y,z));obj.rotation_euler=(Vector(center)-obj.location).to_track_quat('-Z','Y').to_euler()
+for screen in bpy.data.screens:
+ for area in screen.areas:
+ if area.type=='VIEW_3D':
+ space=area.spaces.active;space.region_3d.view_perspective='PERSP';space.region_3d.view_location=Vector(center);space.region_3d.view_distance=span*2.5;space.region_3d.view_rotation=Quaternion((.88,.28,.12,.35)).normalized();space.shading.type='MATERIAL';space.overlay.show_floor=False
+scene['RGBMoCap scene']='MAMMA shared world; baked surfaces and separate reference rigs; keep videos/ and meshes/'
+for c in job['cameras']:
+ view=bpy.data.scenes.new('Camera - '+c['name'])
+ for coll in (bodies,rigs,cameras,stage):view.collection.children.link(coll)
+ view.camera=camera_objects[c['name']];view.world=scene.world
+ view.frame_start=0;view.frame_end=job['frames']-1
+ view.render.fps=scene.render.fps;view.render.fps_base=scene.render.fps_base
+ view.render.resolution_percentage=100;view.render.resolution_x=c['width'];view.render.resolution_y=c['height']
+ ratio=c['K'][0][0]/c['K'][1][1]
+ view.render.pixel_aspect_x=max(1.,1./ratio);view.render.pixel_aspect_y=max(1.,ratio)
+ view.unit_settings.system='METRIC';view.unit_settings.scale_length=1
+scene.name='Overview - all cameras'
+scene.frame_set(0);bpy.context.view_layer.update()
+progress(0,0,'Saving portable Blender project')
+bpy.ops.wm.save_as_mainfile(filepath=str(folder/job['target']),check_existing=False)
diff --git a/mocap/blend_support.py b/mocap/blend_support.py
new file mode 100644
index 0000000..8860d1e
--- /dev/null
+++ b/mocap/blend_support.py
@@ -0,0 +1,104 @@
+"""Bounded, transactional helpers for portable Blender exports."""
+import json,os,shutil,subprocess,time
+from pathlib import Path
+from .result_artifacts import file_stat
+
+
+def read(path,limit=4*1024**2):
+ path=Path(path)
+ if path.stat().st_size>limit:raise ValueError('Blender export metadata exceeds its size limit')
+ return json.loads(path.read_text(encoding='utf-8'))
+
+
+class Inputs:
+ def __init__(self):self.files={}
+ def track(self,path):
+ path=Path(path);stamp=file_stat(path)
+ if path in self.files and self.files[path]!=stamp:raise ValueError('Export input changed while reading')
+ self.files[path]=stamp
+ return path
+ def verify(self):
+ if any(file_stat(p)!=s for p,s in self.files.items()):raise ValueError('Export inputs changed. Retry without changing the project.')
+
+
+def partial(folder,request):
+ folder=Path(folder)
+ return folder.with_name('.'+folder.name+'.rgbmocap-'+Path(request).stem+'.partial')
+
+
+def cleanup(path,request):
+ """Remove only an owned staging directory, never a finished/user folder."""
+ path=Path(path);request=Path(request)
+ if not path.exists():return
+ if (not path.name.startswith('.') or not path.name.endswith('.rgbmocap-'+request.stem+'.partial')
+ or path.is_symlink() or getattr(path,'is_junction',lambda:False)() or path.resolve().parent!=path.parent.resolve()):
+ raise ValueError('Invalid Blender export staging directory')
+ marker=path/'.rgbmocap-owner'
+ if not marker.is_file() or marker.read_text(encoding='utf-8')!=request.stem:
+ raise ValueError('Unowned Blender export staging directory')
+ shutil.rmtree(path)
+
+
+class Bundle:
+ def __init__(self,target,request):
+ self.target=Path(target).resolve();self.folder=self.target.parent;self.request=Path(request)
+ if self.target.suffix.lower()!='.blend' or self.folder.exists() or not self.folder.parent.is_dir():
+ raise ValueError('Choose a new Blender bundle folder in an existing directory')
+ self.work=partial(self.folder,self.request);self.work.mkdir()
+ try:(self.work/'.rgbmocap-owner').write_text(self.request.stem,encoding='utf-8')
+ except Exception:self.work.rmdir();raise
+ def close(self):cleanup(self.work,self.request)
+ def publish(self):
+ if self.folder.exists():raise ValueError('Blender bundle destination was created during export; existing files were retained')
+ if not (self.work/self.target.name).is_file():raise ValueError('Blender did not create the project')
+ self.work.rename(self.folder)
+ (self.folder/'.rgbmocap-owner').unlink()
+
+
+def copy_video(source,target,emit,stage):
+ size=Path(source).stat().st_size;done=0;last=0.
+ with Path(source).open('rb') as inp,Path(target).open('xb') as out:
+ while True:
+ chunk=inp.read(4*1024**2)
+ if not chunk:break
+ out.write(chunk);done+=len(chunk);now=time.monotonic()
+ if now-last>.2 or done==size:
+ emit('progress',stage=stage,current=done,total=size,message='Copying synchronized video');last=now
+
+
+def build(work,script,emit,stage):
+ from .retarget.runtime import blender
+ work=Path(work);logpath=work/'blender.log'
+ cmd=[str(blender()),'-b','--factory-startup','--disable-autoexec','--threads','3','--python-exit-code','1',
+ '--python',str(Path(__file__).with_name(script)),'--',str(work)]
+ env=dict(os.environ,OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',PYTHONIOENCODING='utf-8')
+ p=None
+ try:
+ with logpath.open('wb') as log,logpath.open('rb') as reader:
+ p=subprocess.Popen(cmd,stdout=log,stderr=subprocess.STDOUT,env=env,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
+ last=0.;carry=b''
+ while True:
+ try:p.wait(timeout=.2);done=True
+ except subprocess.TimeoutExpired:done=False
+ data=reader.read(256*1024)
+ if data:
+ lines=(carry+data).split(b'\n');carry=lines.pop()[-16384:]
+ for line in lines:
+ if line.startswith(b'@@BLEND@@'):
+ event=json.loads(line[len(b'@@BLEND@@'):]);emit('progress',stage=stage,**event);last=time.monotonic()
+ if not done and time.monotonic()-last>2:
+ emit('progress',stage=stage,current=0,total=0,message='Building Blender project');last=time.monotonic()
+ if done:break
+ if p.returncode:
+ with logpath.open('rb') as log:log.seek(max(0,logpath.stat().st_size-3000));detail=log.read().decode('utf-8',errors='replace')
+ raise RuntimeError('Blender export failed: '+detail)
+ finally:
+ if p is not None and p.poll() is None:
+ p.terminate()
+ try:p.wait(timeout=2)
+ except subprocess.TimeoutExpired:p.kill();p.wait()
+
+
+def disk_check(folder,required):
+ if shutil.disk_usage(Path(folder)).free<required+256*1024**2:
+ raise ValueError('Insufficient free disk space for the Blender bundle, videos and mesh caches')
diff --git a/mocap/bone_overlay.py b/mocap/bone_overlay.py
index 761ada1..ea3c854 100644
--- a/mocap/bone_overlay.py
+++ b/mocap/bone_overlay.py
@@ -130,6 +130,7 @@ def open_preview(project,kind,cancelled=lambda:False):
try:
with np.load(project/info['asset_file'],allow_pickle=False) as source:
asset['bones']=geometry(source['rest'],source['parents'],source['ends'],asset['key'])
+ asset['parents']=source['parents'].copy()
except (OSError,ValueError,KeyError) as error:
asset['bone_warning']='Export bone overlay unavailable: '+str(error)
return result
diff --git a/mocap/camera_background.py b/mocap/camera_background.py
new file mode 100644
index 0000000..acec2a2
--- /dev/null
+++ b/mocap/camera_background.py
@@ -0,0 +1,138 @@
+"""PR #18-derived optional background rotation refinement of display cameras.
+
+Preserve the original camera centers and source motion; no AI or project writes.
+"""
+import json
+from pathlib import Path
+import numpy as np
+from .result_artifacts import file_stat
+
+
+def fit_rotation(a,b,k,saved,size):
+ """Fit on half of robust matches; accept only on held-out matches."""
+ import cv2
+ from scipy.optimize import least_squares
+ from scipy.spatial.transform import Rotation
+ a=np.asarray(a,float).reshape(-1,2);b=np.asarray(b,float).reshape(-1,2)
+ if len(a)<60:return None,{'reason':'too few background matches'}
+ _,mask=cv2.findHomography(a,b,cv2.RANSAC,1.5)
+ if mask is None:return None,{'reason':'no background consensus'}
+ keep=mask.ravel().astype(bool);a=a[keep];b=b[keep]
+ if len(a)<60:return None,{'reason':'too few background inliers'}
+ cells=np.floor(a/np.array(size)*[4,3]).astype(int)
+ if len(np.unique(cells,axis=0))<6:return None,{'reason':'insufficient background coverage'}
+ order=np.random.default_rng(42).permutation(len(a));train=order[::2];test=order[1::2]
+ rays=np.c_[a,np.ones(len(a))]@np.linalg.inv(k).T
+ def project(r):
+ return q[:,:2]/np.maximum(q[:,2:],1e-8)
+ def matrix(v):return Rotation.from_rotvec(v).as_matrix()@saved
+ solution=least_squares(lambda v:(project(matrix(v))[train]-b[train]).ravel(),np.zeros(3),loss='soft_l1',f_scale=1,max_nfev=35)
+ fitted=matrix(solution.x)
+ before=np.linalg.norm(project(saved)[test]-b[test],axis=1)
+ after=np.linalg.norm(project(fitted)[test]-b[test],axis=1)
+ report=dict(matches=len(a),before_px=float(np.median(before)),after_px=float(np.median(after)),p90_px=float(np.percentile(after,90)),correction_degrees=float(np.rad2deg(np.linalg.norm(solution.x))))
+ accepted=(solution.success and report['correction_degrees']<=2 and report['after_px']<2.5 and report['p90_px']<5 and report['after_px']<report['before_px']*.8 and report['before_px']-report['after_px']>.2)
+ report['reason']='accepted' if accepted else 'parallax, small benefit or unreliable rotation fit'
+ return (fitted if accepted else None),report
+
+
+def refine(project,track,intrinsics,cancelled=lambda:False,progress=lambda *args:None):
+ import cv2
+ from scipy.spatial.transform import Rotation,Slerp
+ from .video import select_preview
+ project=Path(project);track=np.asarray(track,float)
+ sources=[]
+ def read(path):
+ sources.append((path,file_stat(path)))
+ return json.loads(path.read_text(encoding='utf-8'))
+ state=read(project/'project.json');video=select_preview(project);sources.append((video,file_stat(video)))
+ for name in ('input.mp4','preview.json'):
+ path=project/name
+ if path.exists():sources.append((path,file_stat(path)))
+ n=len(track);fps=float(state['fps']);width=960;height=round(state['height']*width/state['width'])
+ if (n<1 or n*16*8>32*1024**2 or height<1 or width*height>2*1024**2
+ or not np.isfinite(fps) or fps<=0):raise ValueError('Background refinement exceeds its bounded preview size')
+ if int(state['frames'])!=n:raise ValueError('Background camera timing differs from the selected take')
+ model=state.get('pipeline',{}).get('model')
+ if model not in ('exmr','flowhmr'):raise ValueError('Background refinement is unavailable for this model')
+ if track.shape!=(n,4,4) or not np.isfinite(track).all():raise ValueError('Invalid camera track')
+ k=np.array(intrinsics,float);k[:2]*=width/state['width']
+ # Mask every known actor, not just the exported actor.
+ box_tracks=[];root=(project/state.get('people_root','.')).resolve()
+ if not project.resolve().is_relative_to(root):raise ValueError('Invalid people root')
+ people=root/'people.json';begin=int(state.get('person_frames',[0])[0])
+ candidates=[(project,begin)]
+ if people.is_file():
+ group=read(people)
+ for person in group['people']:
+ for take in person.get('takes',[]):
+ path=(root/take['project']).resolve()
+ if not path.is_relative_to(root):raise ValueError('Invalid take path')
+ candidates.append((path,int(take['first'])))
+ seen=set()
+ for path,start in candidates:
+ path=path/'tracking.npz'
+ if path in seen or not path.exists():continue
+ seen.add(path);sources.append((path,file_stat(path)))
+ import zipfile
+ with zipfile.ZipFile(path) as archive:
+ if archive.getinfo('boxes.npy').file_size>32*1024**2:raise ValueError('Background actor mask exceeds its size limit')
+ with np.load(path,allow_pickle=False) as data:boxes=np.array(data['boxes'],float)
+ if boxes.ndim!=2 or boxes.shape[1]!=4:raise ValueError('Invalid background actor boxes')
+ box_tracks.append((start,boxes))
+ if not box_tracks:raise ValueError('Actor tracking is unavailable for background masking')
+ def check():
+ if cancelled():raise InterruptedError('Background camera refinement cancelled')
+ def foreground_mask(index):
+ mask=np.full((height,width),255,np.uint8)
+ for start,boxes in box_tracks:
+ j=begin+index-start
+ if 0<=j<len(boxes) and np.isfinite(boxes[j]).all():
+ x1,y1,x2,y2=boxes[j]*width/state['width'];pad=max(10,(x2-x1)*.08)
+ cv2.rectangle(mask,(max(0,int(x1-pad)),max(0,int(y1-pad))),(min(width-1,int(x2+pad)),min(height-1,int(y2+pad))),0,-1)
+ return mask
+ report=dict(method='Background rotation refinement with held-out validation; fixed camera centers',reference_frame=0,measurement_width=width,samples=[],accepted=0)
+ result=track.copy();cap=cv2.VideoCapture(str(video))
+ try:
+ if not cap.isOpened():raise ValueError('Cannot read camera reference video')
+ if abs(cap.get(cv2.CAP_PROP_FPS)-fps)>.01 or int(cap.get(cv2.CAP_PROP_FRAME_COUNT))!=n:raise ValueError('Camera video timing does not match motion')
+ def frame(index):
+ check();cap.set(cv2.CAP_PROP_POS_FRAMES,int(index));ok,img=cap.read();check()
+ if not ok:raise ValueError('Cannot decode camera reference frame '+str(index))
+ if abs(img.shape[1]/img.shape[0]-width/height)>.01:raise ValueError('Camera video aspect ratio does not match motion')
+ return cv2.resize(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY),(width,height))
+ check();progress(0,0);first=frame(0);points=cv2.goodFeaturesToTrack(first,1200,.01,10,mask=foreground_mask(0))
+ if points is None or len(points)<60:
+ report['reason']='Insufficient visible background; original camera retained'
+ if any(file_stat(p)!=s for p,s in sources):raise ValueError('Background tracking inputs changed; retry')
+ return result,sources,report
+ step=max(1,round(fps/5),int(np.ceil(n/600)))
+ ids=np.unique(np.r_[np.arange(0,n,step),n-1]);corrections=[np.eye(3)]
+ cv2.setRNGSeed(42)
+ for sample,index in enumerate(ids[1:],1):
+ check();progress(sample-1,len(ids)-1)
+ gray=frame(index);q,status,_=cv2.calcOpticalFlowPyrLK(first,gray,points,None,winSize=(31,31),maxLevel=4)
+ if q is None:
+ corrections.append(np.eye(3));continue
+ back,back_status,_=cv2.calcOpticalFlowPyrLK(gray,first,q,None,winSize=(31,31),maxLevel=4)
+ if back is None:
+ corrections.append(np.eye(3));continue
+ a=points[:,0];b=q[:,0];xy=np.rint(b).astype(int);inside=(xy[:,0]>=0)&(xy[:,0]<width)&(xy[:,1]>=0)&(xy[:,1]<height)
+ keep=(status.ravel()==1)&(back_status.ravel()==1)&(np.linalg.norm(back[:,0]-a,axis=1)<1)&inside
+ mask=foreground_mask(index);keep[inside]&=mask[xy[inside,1],xy[inside,0]]>0
+ saved=track[index,:3,:3]@track[0,:3,:3].T
+ fitted,detail=fit_rotation(a[keep],b[keep],k,saved,(width,height))
+ detail['frame']=int(index);report['samples'].append(detail)
+ corrections.append([email protected] if fitted is not None else np.eye(3))
+ report['accepted']+=int(fitted is not None)
+ check();progress(len(ids)-1,len(ids)-1)
+ # Interpolate only short, validated intervals; failures retain the saved
+ # camera with a taper to identity at the rejected sample, never bridge gaps.
+ smooth=Slerp(ids,Rotation.from_matrix(corrections))(np.arange(n)).as_matrix() if n>1 else np.eye(3)[None]
+ result[:,:3,:]=smooth@track[:,:3,:]
+ report['reason']='Applied validated rotation corrections' if report['accepted'] else 'No reliable improvement; original camera retained'
+ finally:cap.release()
+ check()
+ if any(file_stat(p)!=s for p,s in sources):raise ValueError('Background tracking inputs changed; retry')
+ return result,sources,report
diff --git a/mocap/camera_background_worker.py b/mocap/camera_background_worker.py
new file mode 100644
index 0000000..b4429e9
--- /dev/null
+++ b/mocap/camera_background_worker.py
@@ -0,0 +1,133 @@
+"""Isolated, cancellable CPU background-camera work and a bounded session cache."""
+from pathlib import Path
+import hashlib,json,os,subprocess,tempfile,time
+import numpy as np
+from .paths import HOME,worker_command
+from .result_artifacts import file_stat
+
+MAX_BYTES=32*1024**2
+
+
+def current(sources):
+ try:return all(file_stat(Path(path))==stamp for path,stamp in sources)
+ except OSError:return False
+
+
+def refined(data,project,cancelled,progress,cache):
+ """Return a display-only camera copy; never rewrite original camera receipts."""
+ if data['model'] not in ('flowhmr','exmr') or data.get('static_camera',False):
+ return dict(data,background_report=dict(skipped='Static camera: background rotation refinement skipped.'))
+ project=Path(project);state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ camera=data['cameras'][0];fps=float(state['fps']);count=int(state['frames'])
+ first=round((float(state['start'])-camera['start'])*fps);matrices=camera['matrices']
+ if abs(camera['fps']-fps)>1e-6 or first<0 or first+count>len(matrices):
+ raise ValueError('Saved camera does not cover the selected background video')
+ track=np.asarray(matrices[first:first+count],float)
+ if track.nbytes>MAX_BYTES:raise ValueError('Background camera exceeds its preview size limit')
+ digest=hashlib.sha256(track.tobytes()+camera['K'].tobytes())
+ for name in ('camera_background.py','camera_background_worker.py'):
+ digest.update(Path(__file__).with_name(name).read_bytes())
+ key=(str(project.resolve()),digest.hexdigest(),first,count)
+ prior=cache.get(key)
+ if prior and current(prior['sources']):
+ track_result=prior['matrices'];report=dict(prior['report'],cache_hit=True)
+ else:
+ folder=HOME/'cache'/'camera_background';folder.mkdir(parents=True,exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='job-',dir=folder) as directory:
+ work=Path(directory);np.save(work/'input.npy',track,allow_pickle=False)
+ (work/'job.json').write_text(json.dumps(dict(project=str(project.resolve()),K=camera['K'].tolist())),encoding='utf-8')
+ env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1')
+ p=subprocess.Popen(worker_command('camera_background','--work',str(work)),stdout=subprocess.PIPE,stderr=subprocess.PIPE,env=env,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
+ deadline=time.monotonic()+180;last=(-1,-1)
+ try:
+ while True:
+ if cancelled():raise InterruptedError('Background camera refinement cancelled')
+ if time.monotonic()>deadline:raise ValueError('Background camera refinement timed out; original camera retained')
+ try:output,error=p.communicate(timeout=.1);done=True
+ except subprocess.TimeoutExpired as wait:
+ output,error=wait.output or b'',wait.stderr or b'';done=False
+ if len(output)+len(error)>512*1024:raise ValueError('Background camera worker log exceeded its limit')
+ event=None
+ progress_path=work/'progress.json'
+ try:
+ if progress_path.stat().st_size<=1024:event=json.loads(progress_path.read_text(encoding='utf-8'))
+ except (OSError,ValueError):pass
+ if event is not None:
+ value=(event.get('current',0),event.get('total',0))
+ if all(type(x) is int for x in value) and 0<=value[0]<=value[1]<=600:
+ progress(*value);last=value
+ elif not done:progress(0,0)
+ for line in reversed(output.splitlines()):
+ if not line.startswith(b'@@BACKGROUND@@'):continue
+ try:event=json.loads(line[len(b'@@BACKGROUND@@'):]);value=(event['current'],event['total'])
+ except (ValueError,KeyError):continue
+ if value!=last:progress(*value);last=value
+ break
+ if done:break
+ if p.returncode:raise ValueError(error.decode('utf-8',errors='replace').strip()[-800:] or 'Background camera refinement failed')
+ finally:
+ if p.poll() is None:
+ p.terminate()
+ try:p.communicate(timeout=1)
+ except subprocess.TimeoutExpired:p.kill();p.communicate()
+ if cancelled():raise InterruptedError('Background camera refinement cancelled')
+ report_path=work/'report.json'
+ if report_path.stat().st_size>1024**2:raise ValueError('Background report exceeds its size limit')
+ record=json.loads(report_path.read_text(encoding='utf-8'));sources=record['sources']+list(data.get('camera_sources',{}).items())
+ if not current(sources):raise ValueError('Camera/background inputs changed during refinement')
+ mapped=np.load(work/'result.npy',mmap_mode='r',allow_pickle=False)
+ try:
+ if mapped.shape!=track.shape or mapped.dtype!=np.float64 or mapped.nbytes>MAX_BYTES or not np.isfinite(mapped).all():raise ValueError('Invalid refined camera output')
+ track_result=None if np.array_equal(mapped,track) else np.array(mapped)
+ finally:mapped._mmap.close()
+ report=dict(record['report'],cache_hit=False)
+ while cache and (len(cache)>=4 or sum(v['matrices'].nbytes for v in cache.values() if v['matrices'] is not None)+(0 if track_result is None else track_result.nbytes)>MAX_BYTES):
+ cache.pop(next(iter(cache)))
+ cache[key]=dict(matrices=track_result,report=report,sources=sources)
+ if cancelled():raise InterruptedError('Background camera refinement cancelled')
+ result=dict(data);cam=dict(camera)
+ if track_result is not None:
+ updated=matrices.copy();updated[first:first+count]=track_result;cam['matrices']=updated
+ result['cameras']=[cam];result['background_report']=report
+ result['note']+=' Background rotation refinement: '+str(report.get('accepted',0))+'/'+str(len(report.get('samples',[])))+' samples accepted; source motion and camera centers unchanged.'
+ return result
+
+
+def main():
+ import argparse
+ import sys
+ parser=argparse.ArgumentParser();parser.add_argument('--work',type=Path,required=True);args=parser.parse_args(sys.argv[2:])
+ work=args.work
+ try:
+ if (work/'job.json').stat().st_size>16*1024:raise ValueError('Invalid camera job size')
+ job=json.loads((work/'job.json').read_text(encoding='utf-8'))
+ import psutil
+ if psutil.virtual_memory().available<512*1024**2:raise MemoryError('Insufficient available RAM for background camera refinement')
+ import cv2
+ cv2.setNumThreads(4)
+ from .camera_background import refine
+ from .camera_tracks import valid_rotations
+ track=np.load(work/'input.npy',mmap_mode='r',allow_pickle=False)
+ try:
+ if track.ndim!=3 or track.shape[1:]!=(4,4) or track.nbytes>MAX_BYTES:raise ValueError('Invalid input camera dimensions')
+ valid_rotations(track[:,:3,:3])
+ start=time.monotonic()
+ last_progress=[0.,-1]
+ def progress(current,total):
+ now=time.monotonic()
+ if total==last_progress[1] and current!=total and now-last_progress[0]<.2:return
+ event=dict(current=current,total=total);temporary=work/'progress.tmp'
+ temporary.write_text(json.dumps(event),encoding='utf-8');os.replace(temporary,work/'progress.json')
+ print('@@BACKGROUND@@'+json.dumps(event),flush=True);last_progress[:]=[now,total]
+ result,sources,report=refine(Path(job['project']),track,np.asarray(job['K'],float),progress=progress)
+ valid_rotations(result[:,:3,:3])
+ before=-np.einsum('tji,tj->ti',track[:,:3,:3],track[:,:3,3]);after=-np.einsum('tji,tj->ti',result[:,:3,:3],result[:,:3,3])
+ if not np.allclose(before,after,rtol=0,atol=1e-7):raise ValueError('Background refinement changed camera centers')
+ report['elapsed_seconds']=time.monotonic()-start
+ np.save(work/'result.npy',result,allow_pickle=False)
+ (work/'report.json').write_text(json.dumps(dict(sources=[(str(path),stamp) for path,stamp in sources],report=report)),encoding='utf-8')
+ finally:track._mmap.close()
+ return 0
+ except Exception as error:
+ import sys
+ print(str(error),file=sys.stderr,flush=True);return 1
diff --git a/mocap/camera_reference.py b/mocap/camera_reference.py
new file mode 100644
index 0000000..87e0ea7
--- /dev/null
+++ b/mocap/camera_reference.py
@@ -0,0 +1,79 @@
+"""Read an original paired SMPL-X camera in an isolated CPU process; no writes."""
+from pathlib import Path
+import json,zipfile
+import numpy as np
+
+
+def reference(project):
+ from .result_artifacts import artifacts_current,file_stat
+ from .scene_camera import paired_camera,validate_transform
+ project=Path(project).resolve()
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ model=state.get('pipeline',{}).get('model')
+ if model not in ('exmr','gvhmr'):raise ValueError('Paired source camera is unsupported for this model.')
+ if not artifacts_current(project,'initial'):raise ValueError('Original motion preview is stale. Use Prepare Preview.')
+ names=['hmr4d_results.pt','initial_joints.npz','initial_mesh.json','tracking.npz']
+ if (project/'initial_artifacts.json').exists():names.append('initial_artifacts.json')
+ saved=cam_root=None
+ if model=='exmr':
+ names.append('exmr_camera_sources.json')
+ saved=json.loads((project/'exmr_camera_sources.json').read_text(encoding='utf-8'))
+ cam_root=(project/saved['root']).resolve()
+ if not project.is_relative_to(cam_root):raise ValueError('Invalid ExMR camera root.')
+ import os
+ names.extend(os.path.relpath(cam_root/name,project) for name in ('exmr_camera.json','exmr_camera.npy'))
+ sources={name:file_stat(project/name) for name in names}
+ import psutil
+ if psutil.virtual_memory().available<512*1024**2:raise MemoryError('Free at least 512 MiB RAM to read the saved camera.')
+ import torch
+ torch.set_num_threads(1)
+ from scipy.spatial.transform import Rotation
+ motion=torch.load(project/'hmr4d_results.pt',map_location='cpu',weights_only=True,mmap=True)
+ world,incam=motion['smpl_params_global'],motion['smpl_params_incam']
+ # Read only one joint directly from the archive; do not extract a preview cache.
+ with zipfile.ZipFile(project/'initial_joints.npz') as archive:
+ with archive.open('joints.npy') as stream:
+ version=np.lib.format.read_magic(stream)
+ reader=np.lib.format.read_array_header_1_0 if version==(1,0) else np.lib.format.read_array_header_2_0
+ shape,fortran,dtype=reader(stream)
+ if fortran or dtype.kind!='f' or len(shape)!=3 or shape[0]!=len(world['transl']) or shape[1:]!=(22,3):
+ raise ValueError('Original source joints do not match the saved motion.')
+ root=np.frombuffer(stream.read(3*dtype.itemsize),dtype=dtype).astype(float)
+ pelvis=root-world['transl'][0].numpy()
+ if pelvis.shape!=(3,) or not np.isfinite(pelvis).all():raise ValueError('Invalid original pelvis pivot.')
+ rotation=lambda params:Rotation.from_rotvec(params['global_orient'][0].numpy()).as_matrix()
+ matrix=paired_camera(rotation(world),rotation(incam),world['transl'][0].numpy(),incam['transl'][0].numpy(),pelvis)
+ centers=None
+ if model=='exmr':
+ align=np.asarray(saved['reference_rotation'])@np.asarray(saved['first_rotation']).T
+ matrix[:3,:3]=align@matrix[:3,:3];matrix[:3,3]=align@matrix[:3,3]
+ policy=json.loads((cam_root/'exmr_camera.json').read_text(encoding='utf-8'))
+ if not policy['identity']['static']:
+ rotations=np.load(cam_root/'exmr_camera.npy',mmap_mode='r',allow_pickle=False)
+ try:
+ count=len(world['transl']);first=saved['first']
+ if count*3*8>32*1024**2:raise ValueError('Camera path exceeds the preview memory limit.')
+ r=np.asarray(rotations[first:first+count],float)@np.asarray(saved['reference_rotation']).T@matrix[:3,:3]
+ if len(r)!=count:raise ValueError('ExMR camera does not cover the original take.')
+ # Relative camera-center estimates from ORIGINAL paired roots.
+ # Body/inference errors remain visible; no pose refitting occurs.
+ centers=world['transl'].numpy()+pelvis-np.einsum('tji,tj->ti',r,incam['transl'].numpy()+pelvis)
+ if not np.isfinite(centers).all():raise ValueError('Invalid estimated camera path.')
+ finally:rotations._mmap.close()
+ with np.load(project/'tracking.npz',allow_pickle=False) as data:k=data['K'].tolist()
+ if not artifacts_current(project,'initial') or any(file_stat(project/name)!=stamp for name,stamp in sources.items()):
+ raise ValueError('Original camera inputs changed while loading.')
+ return dict(schema=2,world_to_camera=validate_transform(matrix).tolist(),K=k,sources=sources,
+ centers=None if centers is None else centers.tolist(),start=state['start'],fps=state['fps'])
+
+
+def main():
+ import sys
+ from .compute_policy import configure_worker_cpu
+ configure_worker_cpu('camera_reference')
+ try:
+ print(json.dumps(reference(Path(sys.argv[sys.argv.index('--project')+1]))),flush=True)
+ return 0
+ except Exception as error:
+ print('Saved original camera could not be read: '+str(error),file=sys.stderr,flush=True)
+ return 1
diff --git a/mocap/camera_tracks.py b/mocap/camera_tracks.py
new file mode 100644
index 0000000..ab9d212
--- /dev/null
+++ b/mocap/camera_tracks.py
@@ -0,0 +1,192 @@
+"""Read saved cameras without inference or body-based camera refitting."""
+from pathlib import Path
+import json,zipfile
+import numpy as np
+from .scene_camera import read_camera,validate_transform
+
+MAX_BYTES=32*1024**2
+
+def read(path):
+ path=Path(path)
+ if path.stat().st_size>2*1024**2:raise ValueError('Camera metadata exceeds the preview limit.')
+ return json.loads(path.read_text(encoding='utf-8'))
+
+def load_array(path,key=None):
+ if key is not None:
+ with zipfile.ZipFile(path) as z:
+ entry=z.getinfo(key+'.npy')
+ if entry.file_size>MAX_BYTES:raise ValueError('Camera track exceeds the preview memory limit.')
+ with np.load(path,allow_pickle=False) as z:return np.array(z[key],dtype=float)
+ a=np.load(path,mmap_mode='r',allow_pickle=False)
+ try:
+ if a.nbytes>MAX_BYTES:raise ValueError('Camera track exceeds the preview memory limit.')
+ return np.array(a,dtype=float)
+ finally:a._mmap.close()
+
+def valid_rotations(r):
+ if r.ndim!=3 or r.shape[1:]!=(3,3) or not len(r) or not np.isfinite(r).all():raise ValueError('Invalid camera rotations.')
+ if not np.allclose(r.swapaxes(-1,-2)@r,np.eye(3),atol=2e-4) or not np.allclose(np.linalg.det(r),1,atol=2e-4):raise ValueError('Camera rotations are not rigid.')
+
+def record(name,k,size,matrices,start,fps,description,displacement=None):
+ k=np.asarray(k,float);m=np.asarray(matrices,float)
+ if m.shape==(4,4):m=m[None]
+ valid_rotations(m[:,:3,:3])
+ if m.shape[1:]!=(4,4) or not np.isfinite(m).all() or not np.allclose(m[:,3],[0,0,0,1]):raise ValueError('Invalid camera transforms.')
+ if (k.shape!=(3,3) or not np.isfinite(k).all() or min(k[0,0],k[1,1])<=0
+ or not np.allclose(k[2],[0,0,1]) or abs(np.linalg.det(k))<1e-9):raise ValueError('Invalid camera intrinsics.')
+ if len(size)!=2 or not np.isfinite(size).all() or min(size)<=0 or not np.isfinite(start) or not np.isfinite(fps) or fps<=0:raise ValueError('Invalid camera timing or image size.')
+ return dict(name=name,K=k,size=tuple(size),matrices=m,start=float(start),fps=float(fps),description=description,displacement=displacement)
+
+def at(camera,time,translation_scale=0.):
+ m=camera['matrices'];index=round((time-camera['start'])*camera['fps'])
+ if len(m)>1 and not 0<=index<len(m):return None
+ index=max(0,min(len(m)-1,index));result=m[index]
+ if translation_scale and camera['displacement'] is not None:
+ result=result.copy();result[:3,3]-=result[:3,:3]@(camera['displacement'][index]*translation_scale)
+ return result
+
+def centers(camera,scale=0.):
+ m=camera['matrices'];ids=np.unique(np.linspace(0,len(m)-1,min(len(m),256),dtype=int))
+ result=-np.einsum('tji,tj->ti',m[ids,:3,:3],m[ids,:3,3])
+ if scale and camera['displacement'] is not None:result+=scale*camera['displacement'][ids]
+ return result
+
+def geometry(camera,matrix,depth=.35):
+ """CV +Z forward/+Y down, transported into the application's Y-up world."""
+ k=camera['K'];w,h=camera['size']
+ pixels=np.array([[0,0],[w,0],[w,h],[0,h],[w*.32,0],[w*.5,-h*.22],[w*.68,0]])
+ local=np.c_[pixels,np.ones(7)]@np.linalg.inv(k).T
+ local*=depth/local[:,2,None]
+ local=np.vstack(([0.,0.,0.],local))
+ world=(local-matrix[:3,3])@matrix[:3,:3]
+ edges=np.array([(0,i) for i in range(1,5)]+[(1,2),(2,3),(3,4),(4,1),(5,6),(6,7),(7,5)])
+ return world[edges],world[0]
+
+def paired_reference(project,cancelled,cache):
+ """Keep tensor deserialization outside the editor, including its loader thread."""
+ import os,subprocess,time
+ from .paths import worker_command
+ from .result_artifacts import file_stat,artifacts_current
+ if not artifacts_current(project,'initial'):raise ValueError('Original motion preview is stale. Use Prepare Preview.')
+ prior=cache.get(str(project)) if cache is not None else None
+ if prior and prior.get('schema')==2 and all(file_stat(project/name)==stamp for name,stamp in prior['sources'].items()):return prior
+ environment=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1')
+ process=subprocess.Popen(worker_command('camera_reference','--project',str(project)),stdout=subprocess.PIPE,stderr=subprocess.PIPE,
+ env=environment,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
+ deadline=time.monotonic()+60
+ try:
+ while True:
+ if cancelled():raise ValueError('Camera load cancelled.')
+ if time.monotonic()>deadline:raise ValueError('Saved camera loading timed out. Retry after other processing finishes.')
+ try:output,error=process.communicate(timeout=.1);break
+ except subprocess.TimeoutExpired:pass
+ if process.returncode:raise ValueError('Saved original camera is unavailable. Use Prepare Preview; check the original motion and body data.')
+ if len(output)>MAX_BYTES:raise ValueError('Saved camera metadata exceeds the preview limit.')
+ value=json.loads(output.decode('utf-8'))
+ if value.get('centers') is not None:
+ value['centers']=np.asarray(value['centers'],float)
+ if value['centers'].ndim!=2 or value['centers'].shape[1]!=3 or value['centers'].nbytes>MAX_BYTES or not np.isfinite(value['centers']).all():
+ raise ValueError('Invalid estimated camera centers.')
+ if cache is not None:
+ if len(cache)>=8:cache.pop(next(iter(cache)))
+ cache[str(project)]=value
+ return value
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ try:process.communicate(timeout=2)
+ except subprocess.TimeoutExpired:process.kill();process.communicate()
+
+
+def load(project,group=None,cancelled=lambda:False,reference_cache=None):
+ from .result_artifacts import file_stat
+ project=Path(project).resolve();state=read(project/'project.json');dependencies={}
+ def tracked(p):
+ p=Path(p);dependencies[p]=file_stat(p);return p
+ tracked(project/'project.json')
+ model=state.get('pipeline',{}).get('model');group=Path(group).resolve() if group else None
+ had_scene=(project/'scene_camera.json').exists()
+ camera=read_camera(project)
+ if camera is None and group is None and model=='flowhmr' and not had_scene:
+ # Single-person FlowHMR does not publish the multi-person scene receipt.
+ # Reuse its committed WV basis/height, never refit to the corrected body.
+ from .flow_placement import current
+ if not current(project):raise ValueError('FlowHMR placement is stale. Use Prepare Preview.')
+ world=read(tracked(project/'flow_world.json'))
+ raw=load_array(tracked(project/'flow_camera.npz'),'camera_RT_yup')
+ matrix=np.eye(4);matrix[:3,:3]=raw[0,:3,:3]@np.asarray(world['scene_basis'],float).T
+ matrix[:3,3]=-matrix[:3,:3]@np.array([0.,world['camera_height'],0.])
+ camera=dict(world_to_camera=validate_transform(matrix),K=world['intrinsics'])
+ if camera is None and group is None and model in ('exmr','gvhmr') and not had_scene:
+ camera=paired_reference(project,cancelled,reference_cache)
+ for name,stamp in camera['sources'].items():dependencies[project/name]=stamp
+ if camera is None:raise ValueError('Saved camera is unavailable or stale. Use Prepare Preview.')
+ if had_scene:tracked(project/'scene_camera.json')
+ reference=validate_transform(camera['world_to_camera'])
+ transform=np.eye(4)
+ if group is not None:
+ from .scene_export import context
+ placement=context(group,project);transform=validate_transform(placement['transform'])
+ tracked(group/'people_scene.json')
+ [email protected](transform);items=[];note='';warning='';static_camera=False
+ if model=='mamma':
+ from .mamma_body import WORLD_ROTATION
+ root=group or project;meta=read(tracked(root/'project.json'))
+ work=(root/meta['mamma_work']).resolve();workspace=(root/meta['workspace_root']).resolve()
+ if not work.is_relative_to(workspace):raise ValueError('Invalid MAMMA camera data path.')
+ saved=read(tracked(work/'camera-world.json'));entries=read(tracked(work/'inputs.json'))
+ if set(saved)!={e['id'] for e in entries}:raise ValueError('MAMMA camera identities differ.')
+ for e in entries:
+ c=saved[e['id']];ext=np.asarray(c['extrinsics_matrix'],float)
+ if ext.shape!=(3,4):raise ValueError('Invalid MAMMA camera matrix.')
+ m=np.eye(4);m[:3,:3]=ext[:,:3]@WORLD_ROTATION.T;m[:3,3]=ext[:,3]
+ if np.any(np.abs(c.get('distortion_coeffs',[0]))>1e-8):note=warning='Distorted camera videos may not align with the pinhole overlay.'
+ items.append(record(e['id'],c['intrinsic_matrix'],c['image_size'],m,meta['start'],meta['fps'],'Saved fixed MAMMA calibration'))
+ if not np.allclose(items[0]['matrices'][0],base,atol=1e-6):raise ValueError('MAMMA camera world changed. Prepare Preview first.')
+ elif model in ('flowhmr','exmr'):
+ root=group or project;meta=read(tracked(root/'project.json'))
+ if model=='flowhmr':
+ from .flow_camera import saved_interval
+ static_camera=saved_interval(project,state)==-1
+ from .flow_placement import current
+ if not current(project):raise ValueError('FlowHMR placement is stale. Use Prepare Preview.')
+ raw=load_array(tracked(root/'flow_camera.npz'),'camera_RT_yup');r=raw[:,:3,:3];valid_rotations(r)
+ rotations=r@r[0].T@base[:3,:3]
+ original_centers=-np.einsum('tji,tj->ti',r,raw[:,:3,3])
+ basis=base[:3,:3].T@r[0]
+ displacement=(original_centers-original_centers[0])@basis.T
+ note='Estimated VGGT camera path; movement scale is approximate. Motion scale 0 keeps the saved camera center. Gizmos only; video overlays keep the calibrated reference.'
+ else:
+ receipt=read(tracked(project/'exmr_camera_sources.json'));root=(project/receipt['root']).resolve()
+ if not project.is_relative_to(root):raise ValueError('Invalid ExMR camera root.')
+ p=tracked(root/'exmr_camera.npy')
+ if file_stat(p)!=receipt['root_stat']:raise ValueError('ExMR camera changed. Prepare Preview first.')
+ r=load_array(p);valid_rotations(r)
+ [email protected](receipt['reference_rotation'],float).T@base[:3,:3]
+ meta=read(tracked(root/'project.json'));displacement=None
+ note='ExMR camera rotation; fixed camera position.'
+ policy=read(tracked(root/'exmr_camera.json'))
+ static_camera=bool(policy['identity']['static'])
+ if not policy['identity']['static']:
+ anchor=project if group is None else (group/read(group/'people_scene.json')['anchor']).resolve()
+ if group is not None and not anchor.is_relative_to(group):raise ValueError('Invalid camera reference take.')
+ try:path=paired_reference(anchor,cancelled,reference_cache)
+ except (OSError,ValueError,RuntimeError):path=None
+ if path is not None:
+ for name,stamp in path['sources'].items():dependencies[anchor/name]=stamp
+ points=path.get('centers') if path is not None else None
+ if (points is not None and len(points)==len(r) and abs(path['start']-meta['start'])<1e-6 and path['fps']==meta['fps']):
+ displacement=points-points[0]
+ note='Estimated ExMR camera movement from original paired world/camera roots. Approximate, not measured motion. Gizmos only; video overlays keep the calibrated reference.'
+ else:warning='Camera movement reference is unavailable or incomplete; showing rotation only.'
+ m=np.tile(np.eye(4),(len(rotations),1,1));m[:,:3,:3]=rotations
+ center=-base[:3,:3].T@base[:3,3];m[:,:3,3]=-np.einsum('tij,j->ti',rotations,center)
+ items=[record('Camera 1',camera['K'],[state['width'],state['height']],m,meta['start'],meta['fps'],note,displacement)]
+ else:
+ items=[record('Camera 1',camera['K'],[state['width'],state['height']],base,state['start'],state['fps'],'Saved reference camera; no dynamic camera track exposed')]
+ note='Saved reference camera only; no dynamic camera translation is available.'
+ if cancelled():return None
+ if (project/'scene_camera.json').exists()!=had_scene:raise ValueError('Camera inputs changed while loading.')
+ if model=='flowhmr' and not current(project):raise ValueError('FlowHMR placement changed while loading. Use Prepare Preview.')
+ if any(file_stat(p)!=stamp for p,stamp in dependencies.items()):raise ValueError('Camera inputs changed while loading.')
+ return dict(cameras=items,model=model,note=note,warning=warning,project=str(project),static_camera=static_camera,camera_sources={str(p):stamp for p,stamp in dependencies.items()})
diff --git a/mocap/camera_ui.py b/mocap/camera_ui.py
new file mode 100644
index 0000000..bd366c4
--- /dev/null
+++ b/mocap/camera_ui.py
@@ -0,0 +1,219 @@
+"""Display-only saved cameras; one bounded loader and the existing video frame."""
+from threading import Condition
+import time
+import numpy as np
+from PySide6.QtCore import QThread,Signal,Qt,QPointF
+from PySide6.QtGui import QPainter,QPen,QColor
+from PySide6.QtWidgets import QDoubleSpinBox
+from .viewer import VideoView
+from .camera_tracks import at,load,centers
+
+BACKGROUND_HELP='Refine saved camera rotation using background features. Only validated corrections up to 2 degrees are applied. Unreliable samples retain the original camera. CPU processing; no motion re-inference or camera-position correction. Off keeps the original tracking.'
+
+class CameraLoader(QThread):
+ ready=Signal(int,object)
+ failed=Signal(int,str)
+ activity=Signal(int,str)
+ def __init__(self,parent):
+ super().__init__(parent);self.condition=Condition();self.generation=0;self.pending=None;self.stopping=False;self.references={};self.backgrounds={}
+ def request(self,project,group,background=False):
+ with self.condition:
+ self.generation+=1;self.pending=(self.generation,project,group,background);self.condition.notify();return self.generation
+ def cancel(self):
+ with self.condition:self.generation+=1;self.pending=None
+ def close(self):
+ with self.condition:self.stopping=True;self.condition.notify()
+ self.wait();self.references.clear();self.backgrounds.clear()
+ def run(self):
+ while True:
+ with self.condition:
+ while self.pending is None and not self.stopping:self.condition.wait()
+ if self.stopping:return
+ token,project,group,background=self.pending;self.pending=None
+ cancelled=lambda:self.stopping or token!=self.generation
+ try:
+ result=load(project,group,cancelled,self.references)
+ if background and result is not None and result['model'] in ('exmr','flowhmr') and not cancelled():
+ from .camera_background_worker import refined
+ self.ready.emit(token,dict(result,background_pending=True));started=time.monotonic()
+ def activity(current,total):
+ elapsed=time.monotonic()-started
+ done=f' {current}/{total}' if total else ''
+ remaining=f' | about {elapsed*(total-current)/current:.0f}s remaining' if current and total>current else ''
+ if not cancelled():self.activity.emit(token,f'Refining camera background rotation{done} | {elapsed:.0f}s{remaining}')
+ try:result=refined(result,project,cancelled,activity,self.backgrounds)
+ except InterruptedError:
+ if not cancelled():raise
+ except (OSError,ValueError,RuntimeError,KeyError) as error:
+ result=dict(result,warning=(result.get('warning','')+' Background camera refinement failed: '+str(error)+'. Original camera retained.').strip(),background_report=dict(failed=str(error)))
+ if background and result is not None and not cancelled():
+ from .camera_background_worker import current
+ if not current(list(result.get('camera_sources',{}).items())):raise ValueError('Saved camera changed during background refinement. Reload the camera preview.')
+ if not cancelled():self.ready.emit(token,result)
+ except FileNotFoundError:
+ if not cancelled():self.failed.emit(token,'Saved camera data is incomplete. Prepare the motion preview before displaying cameras.')
+ except Exception as error:
+ if not cancelled():self.failed.emit(token,str(error))
+
+def actors(view):
+ def skeleton(frames,asset):
+ frames=np.asarray(frames);points=np.array(frames[:,:3,3],float);parents=np.array(asset['parents'],int)
+ # Terminal tips use the same outgoing local tails as the 3D overlay.
+ bones=asset.get('bones',{})
+ for bone,child,_,_ in bones.get('endpoint_vertices',[]):
+ if child==-1:
+ tip=frames[bone,:3,:3]@bones['segments'][bone][2]+points[bone]
+ points=np.vstack((points,tip));parents=np.r_[parents,bone]
+ return points,parents
+ if view.people_mode:
+ for take,index in view.scene_actors():
+ if 'rig' in take.arrays and take.target_asset is not None and 'parents' in take.target_asset:
+ p,parents=skeleton(take.arrays['rig'][index],take.target_asset)
+ yield [email protected][:3,:3].T+take.transform[:3,3],parents,view.scene_colors.get(take.ident,'#ffcf4a')
+ elif view.single_actor_visible and view.target_frames is not None and view.target_asset is not None and 'parents' in view.target_asset:
+ if 0<=view.index<len(view.target_frames):
+ p,parents=skeleton(view.target_frames[view.index],view.target_asset)
+ yield p,parents,'#ffcf4a'
+
+class CameraCanvas(VideoView):
+ def __init__(self,tools):
+ super().__init__();self.tools=tools;self.show_observations=False;self.pair=None
+ def mirror(self,*args):
+ tool=self.tools;w=tool.w;source=w.video_view;view=w.motion_view
+ if not tool.data or source.frame is None:
+ self.frame=None;self.pair=None;self.update();return
+ # The source view emits only after its matching decoded image is committed.
+ # Freeze this complete pair; later source/rig selections cannot mix it.
+ ready=(w.project is None or (view.path is not None and view.path.parent==w.project))
+ ci=getattr(w,'mamma_active_camera',0) if tool.data['model']=='mamma' else 0
+ cameras=tool.data['cameras'];camera=cameras[min(max(0,ci),len(cameras)-1)]
+ # Approximate displacement is a camera-gizmo aid, not a replacement for
+ # the saved projection used to inspect the source/correction overlay.
+ matrix=at(camera,view.scene_time,0)
+ self.pair=(camera,matrix,list(actors(view)) if ready else [])
+ self.frame=source.frame;self.source_size=source.source_size;self.index=source.index;self.update();source.update()
+ def paintEvent(self,event):
+ super().paintEvent(event)
+ painter=QPainter(self);painter.setRenderHint(QPainter.Antialiasing)
+ self.tools.paint_overlay(painter,self.image_rect(),self.tools.w.motion_view.show_bones,labels=True)
+
+class CameraTools:
+ def __init__(self,w,stack,header):
+ self.w=w;self.stack=stack;self.data=None;self.message='';self.key=None;self.token=0;self.scale_values={};self.background_log_key=None
+ self.canvas=CameraCanvas(self);stack.addWidget(w.motion_view);stack.addWidget(self.canvas)
+ self.scale=QDoubleSpinBox();self.scale.setRange(0,100);self.scale.setDecimals(3);self.scale.setValue(1)
+ self.scale.setPrefix('Motion x ');self.scale.setSpecialValueText('Rotation only');self.scale.setMaximumWidth(150)
+ self.scale.setToolTip('Estimated camera movement: 1 uses the stored estimate, 0 fixes the camera center. Adjust the approximate distance scale. Camera gizmos only; video overlays and motion are unchanged.')
+ header.addWidget(self.scale);self.scale.hide();self.scale.valueChanged.connect(self.scale_changed)
+ self.loader=CameraLoader(w);self.loader.ready.connect(self.loaded);self.loader.failed.connect(self.failed);self.loader.activity.connect(self.activity);self.loader.start()
+ w.video_view.frame_presented.connect(self.canvas.mirror)
+ w.video_view.projected_overlay=self.paint_video_overlay
+ def background_options(self):
+ return {model:bool(getattr(self.w,model+'_background',None) and getattr(self.w,model+'_background').isChecked()) for model in ('flowhmr','exmr')}
+ def restore_background(self,values):
+ values=values if isinstance(values,dict) else {}
+ for model in ('flowhmr','exmr'):
+ control=getattr(self.w,model+'_background',None)
+ if control is not None:
+ control.blockSignals(True);control.setChecked(values.get(model) is True);control.blockSignals(False);control.setToolTip(BACKGROUND_HELP)
+ self.key=None
+ def background_changed(self,*args):
+ self.key=None;self.sync()
+ def activity(self,token,message):
+ if token!=self.token:return
+ self.message=message;self.w.motion_view.camera_message=message
+ self.canvas.update();self.w.video_view.update();self.w.motion_view.update()
+ def preview(self):return self.w.view_choice.currentText()=='Camera Preview'
+ def set_view(self,name):
+ self.stack.setCurrentIndex(int(name=='Camera Preview'))
+ if name!='Camera Preview':self.w.motion_view.set_view(name)
+ else:self.canvas.mirror()
+ self.sync()
+ def sync(self):
+ w=self.w;view=w.motion_view;pear=getattr(w,'_pear_active',False)
+ self.scale.setVisible(bool(self.data and not pear and view.show_cameras and not self.preview() and any(c['displacement'] is not None for c in self.data['cameras'])))
+ item=w.view_choice.model().item(w.view_choice.findText('Camera Preview'))
+ if item is not None:item.setEnabled(not pear)
+ if pear and self.preview():
+ w.view_choice.setCurrentText(view.view_name)
+ left=w.video_view.show_observations and w.project is not None and w.preview_data is not None
+ wanted=(view.show_cameras or self.preview() or left) and not pear
+ background=self.background_options().get(w.model_choice.currentData(),False)
+ key=(str(w.project),str(w.people_root),id(w.preview_data),bool(w.busy),pear,wanted,background)
+ if key==self.key:
+ self.canvas.mirror();return
+ self.key=key;self.loader.cancel();self.token=self.loader.generation;self.data=None;self.scale.hide()
+ view.camera_records=[];view.camera_message='';self.canvas.frame=None;self.canvas.pair=None
+ self.message=''
+ if wanted:
+ self.message='Camera data is paused during processing.' if w.busy else 'Loading saved cameras...'
+ if w.project is None:self.message='Open a reconstructed project to show saved cameras.'
+ elif not w.busy:self.token=self.loader.request(w.project,w.people_root,background)
+ view.camera_message=self.message
+ self.canvas.update();w.video_view.update();view.update()
+ def loaded(self,token,data):
+ if token!=self.token:return
+ self.data=data;self.message='Refining camera background rotation...' if data.get('background_pending') else data.get('warning','');self.w.motion_view.camera_message=self.message
+ report=data.get('background_report')
+ if report is not None:
+ summary=report.get('skipped') or report.get('failed') or f"{report.get('accepted',0)}/{len(report.get('samples',[]))} samples accepted; "+('cached; no new processing' if report.get('cache_hit') else f"{report.get('elapsed_seconds',0):.2f}s; CPU")
+ if 'accepted' in report and not report['accepted']:summary+='; original camera retained'
+ control=getattr(self.w,data['model']+'_background',None)
+ if control is not None:control.setToolTip(BACKGROUND_HELP+' Last result: '+summary)
+ log_key=(str(self.w.project),data['model'],summary)
+ if log_key!=self.background_log_key:
+ self.background_log_key=log_key;self.w.log.append('Camera background refinement ('+data['model']+'): '+summary)
+ self.scale.blockSignals(True);self.scale.setValue(self.scale_values.get(data['model'],1));self.scale.blockSignals(False)
+ self.scale.setVisible(self.w.motion_view.show_cameras and not self.preview() and any(c['displacement'] is not None for c in data['cameras']))
+ self.w.viewport_checks['show_cameras'].setToolTip('Show saved cameras. Display only. '+data['note'])
+ self.canvas.setToolTip(data['note']);self.scale_changed()
+ def failed(self,token,message):
+ if token!=self.token:return
+ self.data=None;self.message=message;self.w.motion_view.camera_message=message
+ self.w.motion_view.update();self.canvas.update();self.w.video_view.update()
+ def scale_changed(self,*args):
+ view=self.w.motion_view
+ if self.data:self.scale_values[self.data['model']]=self.scale.value()
+ view.camera_records=[] if not self.data else [(c,centers(c,self.scale.value())) for c in self.data['cameras']]
+ view.camera_translation_scale=self.scale.value();view.update();self.canvas.mirror();self.w.video_view.update()
+ def paint_video_overlay(self,painter,rect):
+ source=self.w.video_view
+ if getattr(self.w,'_pear_active',False) or source.external_mode:return
+ if source.frame is not None and self.data is None:
+ self.paint_overlay(painter,rect,False);return
+ if (source.frame is None or self.canvas.frame is None or self.canvas.index!=source.index
+ or source.frame.cacheKey()!=self.canvas.frame.cacheKey()):return
+ self.paint_overlay(painter,rect,True)
+ def paint_overlay(self,painter,rect,bones,labels=False):
+ message=self.message
+ pair=self.canvas.pair
+ painter.save()
+ try:
+ if self.canvas.frame is not None and pair:
+ camera,matrix,paired_actors=pair
+ if matrix is None:message='Outside saved camera timing.'
+ else:
+ if labels:message=camera['name']+' | saved camera / displayed source frame'
+ if bones:
+ painter.setClipRect(rect);k=camera['K'];width,height=camera['size']
+ for points,parents,color in paired_actors:
+ cam=points@matrix[:3,:3].T+matrix[:3,3]
+ painter.setPen(QPen(QColor(color),2,Qt.SolidLine,Qt.RoundCap))
+ for j,parent in enumerate(parents):
+ if parent<0:continue
+ a,b=cam[parent].copy(),cam[j].copy()
+ if not np.isfinite([a,b]).all() or max(a[2],b[2])<=.03:continue
+ if a[2]<.03:a+=(b-a)*((.03-a[2])/(b[2]-a[2]))
+ if b[2]<.03:b+=(a-b)*((.03-b[2])/(a[2]-b[2]))
+ q=np.array([a,b])@k.T;q=q[:,:2]/q[:,2:]
+ q[:,0]=rect.left()+q[:,0]*rect.width()/width;q[:,1]=rect.top()+q[:,1]*rect.height()/height
+ painter.drawLine(QPointF(*q[0]),QPointF(*q[1]))
+ painter.setClipping(False)
+ if labels and not paired_actors:message+=' | no source bones at this time'
+ if labels and self.message:message+='\n'+self.message
+ if message:
+ painter.setPen(QColor('#e8c38d' if self.message else '#dddddd'))
+ painter.drawText(rect.adjusted(12,10,-12,-12),Qt.AlignTop|Qt.TextWordWrap,message)
+ finally:painter.restore()
+ def close(self):
+ self.loader.close();self.w.video_view.projected_overlay=None;self.data=None;self.w.motion_view.camera_records=[];self.canvas.shutdown();self.canvas.frame=None
diff --git a/mocap/export_copy.py b/mocap/export_copy.py
index fa57c14..38df086 100644
--- a/mocap/export_copy.py
+++ b/mocap/export_copy.py
@@ -14,7 +14,10 @@ def run(request,emit=lambda *a,**k:None):
staged=[]
try:
for i,row in enumerate(rows):
+ profile=row.get('bvh_profile','generic')
+ if profile not in ('generic','biped'):raise ValueError('Unsupported BVH export profile')
project=Path(row['project']);source=selected_export(project,row['kind']);target=Path(row['target'])
+ if target.suffix.lower()!='.bvh':raise ValueError('Choose a BVH destination')
if source is None or source.resolve()!=Path(row['source']).resolve():raise ValueError('Selected target motion changed. Export again.')
if source.resolve()==target.resolve():raise ValueError('Choose a different export destination')
if any(target.resolve()==old[1].resolve() for old in staged):raise ValueError('Duplicate export destination')
@@ -27,9 +30,19 @@ def run(request,emit=lambda *a,**k:None):
staged.append((temporary,target,project,row['kind'],source,stamp,scene))
with source.open('rb') as inp,temporary.open('xb') as out:
def progress():emit('progress',stage='copy_bvh',current=i,total=len(rows),message='Saving BVH in shared scene' if scene else 'Saving BVH')
- if scene is not None and not np.allclose(scene['transform'],np.eye(4),rtol=0,atol=1e-12):
+ prepare=row.get('prepend_tpose',False) or (scene is not None and not np.allclose(scene['transform'],np.eye(4),rtol=0,atol=1e-12))
+ if profile=='biped':
+ from .biped_bvh import convert
+ if prepare:
+ from tempfile import TemporaryFile
+ from .scene_export import transform_motion
+ with TemporaryFile() as prepared:
+ transform_motion(inp,prepared,np.eye(4) if scene is None else scene['transform'],progress,prepend_tpose=row.get('prepend_tpose',False))
+ prepared.seek(0);convert(prepared,out,progress)
+ else:convert(inp,out,progress)
+ elif prepare:
from .scene_export import transform_motion
- transform_motion(inp,out,scene['transform'],progress)
+ transform_motion(inp,out,np.eye(4) if scene is None else scene['transform'],progress,prepend_tpose=row.get('prepend_tpose',False))
else:
while True:
chunk=inp.read(1024*1024)
diff --git a/mocap/fbx_export.py b/mocap/fbx_export.py
index b7f2500..57ed880 100644
--- a/mocap/fbx_export.py
+++ b/mocap/fbx_export.py
@@ -45,7 +45,7 @@ def run(request, emit=lambda *a, **k:None):
write(temporary,info['names'],a['parents'],a['fbx_rest'],a['fbx_rest_frames'],
a['fbx_display_frames'],a['fbx_tip_local'],frames,info['fps'],
transform=None if scene is None else scene['transform'],progress=progress,
- rig_name=row.get('rig_name','SourceAnimation'))
+ rig_name=row.get('rig_name','SourceAnimation'),prepend_tpose=row.get('prepend_tpose',False))
finally:frames._mmap.close()
for _,_,project,kind,paths,stamps,scene in staged:
if [file_stat(p) for p in paths]!=stamps or selected_export(project,kind)!=paths[1]:
diff --git a/mocap/fbx_writer.py b/mocap/fbx_writer.py
index da089d6..78afe17 100644
--- a/mocap/fbx_writer.py
+++ b/mocap/fbx_writer.py
@@ -66,7 +66,7 @@ def _euler(matrix):
def write(path, names, parents, rest, rest_frames, display, tip_local, frames, fps,
- transform=None, progress=lambda *args:None, rig_name='SourceAnimation'):
+ transform=None, progress=lambda *args:None, rig_name='SourceAnimation', prepend_tpose=False):
"""Write one committed mapped take; working rotation arrays are one bone wide."""
from .person_names import validate_name
rig_name=validate_name(rig_name)
@@ -122,7 +122,8 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, f
pose_nodes.append(node('PoseNode',children=[node('Node',int(ids[j])),node('Matrix',M.T.reshape(-1))]))
objects.append(node('Pose',5000,'BindPose\0\1Pose','BindPose',children=[node('Type','BindPose'),node('Version',100),node('NbPoseNodes',len(pose_nodes)),*pose_nodes]))
# Zero-based file times import at frame 1 with Blender's default offset 1.
- times=np.rint(np.arange(n)*TICKS/fps).astype(np.int64)
+ key_count=n+int(bool(prepend_tpose))
+ times=np.rint(np.arange(key_count)*TICKS/fps).astype(np.int64)
stop=int(times[-1]);stack=6000;layer=6001
objects.append(node('AnimationStack',stack,'Motion\0\1AnimStack','',children=[properties(
prop('LocalStart','KTime',0),prop('LocalStop','KTime',stop),prop('ReferenceStart','KTime',0),prop('ReferenceStop','KTime',stop))]))
@@ -152,7 +153,7 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, f
uid=nextid;nextid+=1
_element(out,node('AnimationCurve',uid,'\0\1AnimCurve','',children=[node('Default',float(values[0,axis])),node('KeyVer',4008),
node('KeyTime',times),node('KeyValueFloat',values[:,axis].astype(np.float32)),
- node('KeyAttrFlags',np.array([4],np.int32)),node('KeyAttrDataFloat',np.zeros(4,np.float32)),node('KeyAttrRefCount',np.array([n],np.int32))]))
+ node('KeyAttrFlags',np.array([4],np.int32)),node('KeyAttrDataFloat',np.zeros(4,np.float32)),node('KeyAttrRefCount',np.array([key_count],np.int32))]))
link(uid,cid,'d|'+a)
for j,p in enumerate(parents):
world=np.asarray(frames[:,j,:3,:3],float)@display[j]
@@ -160,6 +161,7 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, f
local=transform[:3,:3]@world
positions=np.asarray(frames[:,0,:3,3],float)@transform[:3,:3].T+transform[:3,3]
if not np.isfinite(positions).all():raise ValueError('Non-finite FBX root')
+ if prepend_tpose:positions=np.concatenate((positions[:1],positions))
curves(j,'Lcl Translation',positions)
else:
parent=np.asarray(frames[:,p,:3,:3],float)@display[p]
@@ -168,6 +170,11 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, f
if not np.isfinite(actual).all() or np.max(abs(actual-offsets[j]))>2e-5:
raise ValueError('Non-rigid bone offset in committed source animation')
if not np.isfinite(local).all():raise ValueError('Non-finite FBX animation')
+ if prepend_tpose:
+ # Identity BVH world frames describe the straight-arm export bind.
+ # Display axes transport that T-pose into the FBX bone basis.
+ pose=transform[:3,:3]@display[j] if p<0 else display[p].T@display[j]
+ local=np.concatenate((pose[None],local))
angles=np.degrees(continuous_angles(np.radians(_euler(np.asarray(local_rest[j]).T@local))))
curves(j,'Lcl Rotation',angles);progress(j+1,52)
out.write(b'\0'*13);end=out.tell();out.seek(start);out.write(struct.pack('<IIIB',end,0,0,7));out.seek(end)
@@ -177,4 +184,4 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, f
out.write(bytes.fromhex('fabcab09d0c8d466b176fb831cf7267e'))
out.write(b'\0'*((-out.tell())%16));out.write(struct.pack('<I',7400));out.write(b'\0'*120)
out.write(bytes.fromhex('f85a8c6adef5d97eece90ce3758f290b'))
-
+
diff --git a/mocap/gui.py b/mocap/gui.py
index cbc6b4c..5bb4ac7 100644
--- a/mocap/gui.py
+++ b/mocap/gui.py
@@ -32,6 +32,9 @@ from .theme import STYLE
STAGES["mesh"] = "Prepare SMPL-X Mesh"
STAGES['rig']='Prepare Bone Preview'
STAGES['save_fbx']='Save FBX'
+STAGES['copy_bvh']='Save BVH'
+STAGES['save_blend']='Save Blender Project'
+STAGES['save_blend_scene']='Save MAMMA Blender Scene'
STAGES["footmr"] = "Refine Ankles / FootMR"
STAGES["handflow"] = "Infer Fingers / HandFlow"
STAGES['correct'] = 'Motion Correction'
@@ -432,6 +435,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
@read_only_checks
def update_readiness(self):
if self._pear_active:
+ if hasattr(self,'camera_tools'):self.camera_tools.sync()
self.pear_sync_controls();return
if getattr(self,'_readiness_depth',0):
self._readiness_pending=True
@@ -476,9 +480,9 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.reset_footlocks_button.setEnabled(self.slider.contact_edit_enabled)
self.reset_trim_button.setEnabled(self.slider.trim_enabled)
character=self.selected_character()
- self.export_action.setText('Export Character...' if character else 'Export FBX...')
+ self.export_action.setText('Export Character...' if character else 'Export...')
self.export_action.setEnabled(not self.busy and (bool(character.get('takes')) and not character.get('needs_retarget') if character else self.project is not None and self.current_export() is not None))
- self.export_action.setToolTip(tooltip_text("Choose a character export format and whether to include its mesh. PMX characters also support VMD motion." if character else "Save the displayed skeleton animation as FBX. For multiple people, each checked person gets a separate named file and rig."))
+ self.export_action.setToolTip(tooltip_text("Choose a character export format and whether to include its mesh. PMX characters also support VMD motion." if character else "Export the displayed motion as FBX, BVH or a portable Blender project. Multiple people export separately; MAMMA also offers a whole-scene Blender bundle."))
self.play_button.setEnabled(self.info is not None and self.video_readable)
for action in self.open_actions:
action.setEnabled(not self.busy)
@@ -491,10 +495,13 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.flow_acceleration.setEnabled(not self.busy)
self.exmr_camera.setEnabled(not self.busy)
self.exmr_smoothing.setEnabled(not self.busy)
+ self.flowhmr_background.setEnabled(not self.busy)
+ self.exmr_background.setEnabled(not self.busy)
self.analyze_button.setVisible(tool.key=='gvhmr')
self.sync_correction_floor_preview()
self.sync_mamma_controls()
self.sync_prompthmr_controls()
+ if hasattr(self,'camera_tools'):self.camera_tools.sync()
def sync_correction_floor_preview(self):
self.motion_view.correction_floor_applicable=self.correction_mode.currentData()=='flat'
@@ -584,6 +591,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
def render_changed(self):
self.motion_view.show_bones=self.bone_overlay.isChecked()
self.motion_view.update()
+ if hasattr(self,'camera_tools'):self.camera_tools.canvas.update()
def preview_preparation_available(self):
if self.project is None or self.busy or self.contact_saving:return False
@@ -672,6 +680,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.flow_gpu_crop.setChecked(True)
self.exmr_camera.setCurrentIndex(0)
self.exmr_smoothing.setChecked(True)
+ self.camera_tools.restore_background({})
self.handflow_refine.blockSignals(True)
self.handflow_refine.setChecked(self.model_choice.currentData()=='gvhmr')
self.handflow_refine.blockSignals(False)
@@ -763,6 +772,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.clear_preview()
self.motion_view.auto_fit = True
self.project = project
+ self.camera_tools.restore_background({})
self.workspace_project_loaded(project,manifest)
from .project_storage import storage_root
saved_root=storage_root(project,manifest)
@@ -937,6 +947,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
self.timer.start(max(1, math.ceil(remaining * 1000)))
def shutdown_preview(self):
+ if hasattr(self,'camera_tools'):self.camera_tools.close()
self.shutdown_mamma()
self.stop_playback()
if hasattr(self,'character_loader'):
@@ -1250,10 +1261,13 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
(f' · Elapsed {duration(elapsed)}' if elapsed is not None else ''))
self.progress.setRange(0, 100)
self.progress.setValue(0 if self.failed or self.cancelled else 100)
- if self.current_stage=='save_fbx':
+ if self.current_stage in ('save_fbx','copy_bvh','save_blend','save_blend_scene'):
# Saving a derived file does not replace scene/preview data.
# Reloading the people scene here moves a following camera.
- if not self.failed and not self.cancelled:self.status.setText('FBX export complete.')
+ if not self.failed and not self.cancelled:
+ paths=getattr(self,'_motion_export_targets',[])
+ self.status.setText('Motion export complete.'+(' '+paths[0] if len(paths)==1 else f' {len(paths)} files.' if paths else ''))
+ for path in paths:self.log.append('Exported: '+path)
self.update_readiness()
return
if self.current_stage=='save_project':
@@ -1719,25 +1733,45 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
def save_fbx(self):
if self.selected_character() is not None:
self.export_character(self.selected_character());return
+ if self.busy or self.current_export() is None:
+ self.status.setText('Selected motion is unavailable or has pending correction edits. Apply Correction / Prepare Preview before exporting.');return
+ from .source_export_dialog import SourceExportDialog
+ dialog=SourceExportDialog(self)
+ if dialog.exec()!=QDialog.Accepted:return
+ if self.current_export() is None:
+ self.status.setText('Motion changed while choosing export options. Apply Correction / Prepare Preview first.');return
+ self._source_export_options=dialog.options()
+ if self._source_export_options['format']=='blend_scene':
+ from .blend_export_ui import export_scene
+ export_scene(self);return
if self.export_checked_people():return
source = self.current_export()
if source:
from .person_names import export_stem
- default=export_stem(self.export_person_name(self.project))+'.fbx'
- name, _ = QFileDialog.getSaveFileName(self, "Export FBX", default, "FBX (*.fbx)")
+ fmt=self._source_export_options['format']
+ default=export_stem(self.export_person_name(self.project))+'.'+fmt
+ name, _ = QFileDialog.getSaveFileName(self, "Export", default, fmt.upper()+" (*."+fmt+")",options=QFileDialog.DontConfirmOverwrite if fmt=='blend' else QFileDialog.Option(0))
if name:
+ if not Path(name).suffix:name+='.'+fmt
self.submit_fbx_exports([(self.project,self.active_result,source,Path(name))])
def submit_fbx_exports(self,files):
- if self.busy:return
+ if self.busy or not files or self.current_export() is None:return
import uuid
from .storage import atomic_json
request=self.project/('.fbx-export-'+uuid.uuid4().hex+'.json')
rows=[]
+ if getattr(self,'_source_export_options',{}).get('format')=='blend':
+ from .blend_export_ui import targets
+ files=targets(files)
try:
for project,kind,source,target in files:
row=dict(project=str(project),kind=kind,source=str(source),target=str(target))
row['rig_name']=self.export_person_name(project)
+ row['prepend_tpose']=getattr(self,'_source_export_options',{}).get('prepend_tpose',False)
+ row['bvh_profile']=getattr(self,'_source_export_options',{}).get('bvh_profile','generic')
+ for key,default in (('animate_camera',True),('background_refine',False),('camera_translation_scale',1.)):
+ row[key]=getattr(self,'_source_export_options',{}).get(key,default)
if self.people_root is not None:
from .scene_export import context
row['scene']=context(self.people_root,project)
@@ -1745,16 +1779,25 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorksp
except (OSError,ValueError,KeyError) as error:
self.status.setText('Cannot export shared scene: '+str(error));return
atomic_json(request,rows)
+ self._motion_export_targets=[str(target) for _,_,_,target in files]
self._fbx_export_cleanup=(request,[target.with_name('.'+target.name+'.rgbmocap-'+request.stem+'.partial') for _,_,_,target in files])
- self.start_jobs([('save_fbx',['--project',str(self.project),'--output',str(request)])])
+ stage='copy_bvh' if getattr(self,'_source_export_options',{}).get('format','fbx')=='bvh' else 'save_fbx'
+ if getattr(self,'_source_export_options',{}).get('format')=='blend':
+ from .blend_support import partial
+ stage='save_blend';self._fbx_export_cleanup=(request,[partial(target.parent,request) for _,_,_,target in files])
+ self.start_jobs([(stage,['--project',str(self.project),'--output',str(request)])])
def cleanup_fbx_export(self):
pending=getattr(self,'_fbx_export_cleanup',None)
if pending:
request,paths=pending
for path in [request,*paths]:
- try:path.unlink(missing_ok=True)
- except OSError:pass
+ try:
+ if path.is_dir():
+ from .blend_support import cleanup
+ cleanup(path,request)
+ else:path.unlink(missing_ok=True)
+ except (OSError,ValueError):pass
self._fbx_export_cleanup=None
def open_folder(self):
diff --git a/mocap/model_guide.py b/mocap/model_guide.py
index 7f9c964..02e8662 100644
--- a/mocap/model_guide.py
+++ b/mocap/model_guide.py
@@ -26,12 +26,12 @@ PROJECT_URLS = {
}
DESCRIPTIONS = {
'pear':'Experimental support. Tracking and pose estimates may be unstable. Real-time tracking of webcam or video input, with a single-person body and finger bone preview from one or multiple fixed-camera views. Select synchronized videos with Open Video, or assign distinct webcam devices using the camera-count slots and thumbnails. Start Live Tracking attempts Camera Align first, including one camera; VGGT and GeoCalib are needed for alignment. A single view uses estimated body/depth scale; multiple views use triangulation. If alignment fails or its support/models are missing, tracking continues from the selected camera with a visible warning, without camera fusion or aligned foot lock. Use Camera Align to retry. Fixed bone lengths are calibrated once; Reset Bones recalibrates from the displayed pose, then aligns cameras again. World Position is on by default; off fixes pelvis translation while preserving rotation. Body mesh is not computed per live frame. Select a webcam in the table below the video for image preview without loading PEAR; click Start Live Tracking to attempt alignment and begin tracking. Capture stays connected during Start and Camera Align; opened videos can play while models load or align. Choose None for video. Stop releases models and the webcam. Uses YOLOv8s person detection; detector boxes can affect the resulting pose. Rotation and One Euro Filter apply to both sources. One Euro Filter has independent Bone Rotation and World Position checkboxes, both on by default, with shared Filter Strength. The position-filter checkbox is separate from the World Position movement switch. Filtering reduces tremors with some motion-dependent lag and no extra inference. Seeks start from the selected frame; filtering continues during playback. After successful alignment, default-on lightweight Foot Lock stabilizes low, slow feet with smooth causal transitions, fixed lengths and preserved ankle/toe directions. Reach limits and incorrect ground estimates can leave residual sliding. No Find person, recording, offline Motion Correction, retargeting or motion export in this live mode. Single-view pelvis placement assumes a fixed camera. Camera Align estimates background gravity, camera positions, scale and floor; these are not measured calibration and feet can still slide. Changed inputs and Reset Bones trigger realignment. After moving physical cameras, click Camera Align again. Webcam arrival-time pairing is approximate, not hardware sync. Support files are included in install.cmd and update.cmd, reusing the shared runtime without upgrading its packages or requiring a CUDA compiler. Prepare the checkpoint and registered SMPL-X 2020/FLAME geometry bundle in Model Manager. See docs/models/PEAR.md.',
- 'prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed cameras only in this Windows integration. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.',
+ 'prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed cameras only in this Windows integration. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX/BVH/Blender export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.',
'mamma': 'Multi-view reconstruction of one or several people from two or more synchronized fixed-camera videos of the same performance. No fixed camera-count maximum; practical capacity depends on available RAM and VRAM. Detects people automatically; Find person is not needed. Uses SAM 2.1 masks and FP32 landmarks. Automatic cameras combine VGGT-Omega placement with GeoCalib background gravity before 3D fitting; manual calibration bypasses both. GeoCalib uses the base Flow support overlay and a shared checkpoint in Model Manager. Unreliable gravity needs manual calibration or clearer views; it does not fall back to the person as a vertical reference. Body and finger motion, original results and contact-corrected results are preserved. Best suited to views that complement each other; occlusion and bad masks can cause errors. Slower than single-video methods. Requires the separate Setup_MAMMA.cmd runtime and registered restricted-use models. See Model Manager > Runtime Setup and docs/MAMMA.md.',
'gvhmr': 'Lowest overall motion quality in our tests, but sometimes better for unusual poses such as backflips. '
'No native finger tracking. Optional HandFlow adds finger motion; FootMR refines ankles, and HTD refines body motion. These add processing time.',
- 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers together without a separate finger add-on. With Fast SAM and Adaptive Batching on, Automatic selects 1-16 frames from available memory and image size; Low Memory uses one. Tests of 4 to 16 frames reduced warm feature time by 16-23%, with allocated VRAM 3.84 to 5.43 GiB and small numerical motion differences. Short whole jobs benefit much less because model loading dominates. Batch selection, GPU Hand Crops and OOM batch retries appear in Console and CMD. See docs/models/FLOWHMR.md.',
- 'exmr': 'Generally fast, with good motion quality in our tests. A practical choice for a first attempt. Tracks body and fingers together without a separate finger add-on.',
+ 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers together without a separate finger add-on. With Fast SAM and Adaptive Batching on, Automatic selects 1-16 frames from available memory and image size; Low Memory uses one. Tests of 4 to 16 frames reduced warm feature time by 16-23%, with allocated VRAM 3.84 to 5.43 GiB and small numerical motion differences. Short whole jobs benefit much less because model loading dominates. Batch selection, GPU Hand Crops and OOM batch retries appear in Console and CMD. Optional Refine Camera Rotation validates small background-based corrections for camera display only; source motion is unchanged. See docs/models/FLOWHMR.md.',
+ 'exmr': 'Generally fast, with good motion quality in our tests. A practical choice for a first attempt. Tracks body and fingers together without a separate finger add-on. Optional Refine Camera Rotation validates small background-based corrections for camera display only; source motion is unchanged.',
}
@@ -51,6 +51,7 @@ th { text-align:left; background-color:#333333; } td, th { padding:7px; }
<h3>Choosing a model</h3>
<p>These are subjective observations from our test videos, not a universal ranking or accuracy benchmark.
Try another model if a particular movement looks wrong.</p>""" + descriptions + """
+<p>Offline source motion: File &gt; Export offers FBX, BVH and portable Blender projects with video/cameras. MAMMA also offers a whole-scene Blender bundle with checked body meshes and all cameras. Keep exported video/mesh folders together. No additional inference is run for export.</p>
<h3>Recorded processing time and memory</h3>
<table width="98%" border="0" cellspacing="1" cellpadding="7">
<tr><th>Model</th><th>Input</th><th>Processing time</th><th>Peak VRAM (GiB)</th><th>Peak RAM (GiB)</th></tr>""" + rows + """</table>
diff --git a/mocap/people_ui.py b/mocap/people_ui.py
index 31ff682..47df9bd 100644
--- a/mocap/people_ui.py
+++ b/mocap/people_ui.py
@@ -233,6 +233,7 @@ class PeopleWorkspace:
self.motion_view.actor_name=self._single_actor['name'] if self._single_actor else 'Person 1'
self.motion_view.scene_selected=self.active_person_id
self.motion_view.scene_time=self.source_offset+self.motion_view.index/(self.info['fps'] if self.info else 30)
+ if hasattr(self,'camera_tools'):self.camera_tools.canvas.mirror()
self.motion_view.update()
def build_people_editor(self, video):
@@ -712,7 +713,7 @@ class PeopleWorkspace:
from .person_names import export_path
used={p.name.casefold() for p in Path(folder).iterdir()}
for source,name in files:
- target=export_path(folder,name,used)
+ target=export_path(folder,name,used,suffix='.'+getattr(self,'_source_export_options',{}).get('format','fbx'))
copies.append((source.parent,self.active_result,source,target))
self.submit_fbx_exports(copies)
return True
diff --git a/mocap/person_names.py b/mocap/person_names.py
index 981ca6c..c92c34d 100644
--- a/mocap/person_names.py
+++ b/mocap/person_names.py
@@ -23,10 +23,11 @@ def export_stem(name):
return stem
-def export_path(folder,stem,used):
+def export_path(folder,stem,used,suffix='.fbx'):
"""Reserve names across both this batch and existing files on Windows."""
- candidate=Path(folder)/(stem+'.fbx');number=2
+ if suffix not in ('.fbx','.bvh'):raise ValueError('Unsupported source export format')
+ candidate=Path(folder)/(stem+suffix);number=2
while candidate.name.casefold() in used or candidate.exists():
- candidate=Path(folder)/(stem+f'_{number}.fbx');number+=1
+ candidate=Path(folder)/(stem+f'_{number}'+suffix);number+=1
used.add(candidate.name.casefold())
return candidate
diff --git a/mocap/project_workspace_ui.py b/mocap/project_workspace_ui.py
index 9794ec6..087c34a 100644
--- a/mocap/project_workspace_ui.py
+++ b/mocap/project_workspace_ui.py
@@ -42,7 +42,7 @@ class ModelWorkspace:
def workspace_view(self):
fps=self.info['fps'] if self.info else 30.
- return dict(source_time=self.source_offset+self.slider.value()/fps,
+ return dict(camera_background=self.camera_tools.background_options(),source_time=self.source_offset+self.slider.value()/fps,
trim_time=[self.source_offset+self.slider.clip_in/fps,self.source_offset+self.slider.clip_out/fps],
camera={**{key:np.asarray(getattr(self.motion_view,key)).tolist()
for key in ('yaw','pitch','distance','pan','scene_center')},'target':self.motion_view.target().tolist()})
@@ -69,6 +69,7 @@ class ModelWorkspace:
atomic_json(root/'project.json',saved)
def restore_workspace_view(self,view):
+ self.camera_tools.restore_background(view.get('camera_background',{}))
if self.info:
fps=self.info['fps']
times=view.get('trim_time')
diff --git a/mocap/scene_export.py b/mocap/scene_export.py
index f4d7414..eb2d3a0 100644
--- a/mocap/scene_export.py
+++ b/mocap/scene_export.py
@@ -33,7 +33,7 @@ def context(root,project):
sources=camera['sources'],anchor_sources=anchor['sources'],model=camera.get('model'))
-def transform_motion(inp,out,transform,progress=lambda:None):
+def transform_motion(inp,out,transform,progress=lambda:None,prepend_tpose=False):
"""Stream only root channels in bounded blocks; keep the hierarchy byte-for-byte."""
from scipy.spatial.transform import Rotation
import warnings
@@ -58,7 +58,8 @@ def transform_motion(inp,out,transform,progress=lambda:None):
raise ValueError('Invalid BVH motion header')
count=int(count_line.split(b':',1)[1]);step=float(time_line.split(b':',1)[1])
if count<1 or not np.isfinite(step) or step<=0:raise ValueError('Invalid BVH timing')
- out.write(count_line);out.write(time_line);previous=np.zeros(3)
+ out.write(f'Frames: {count+1}\n'.encode('ascii') if prepend_tpose else count_line)
+ out.write(time_line);previous=np.zeros(3)
for first in range(0,count,128):
rows=[]
for _ in range(min(128,count-first)):
@@ -73,6 +74,13 @@ def transform_motion(inp,out,transform,progress=lambda:None):
with warnings.catch_warnings():
warnings.filterwarnings('ignore',message='Gimbal lock detected')
angles=Rotation.from_matrix([email protected]_euler(root_order,values[:,3:6],degrees=True).as_matrix()).as_euler(root_order)
+ if first==0 and prepend_tpose:
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore',message='Gimbal lock detected')
+ reference=Rotation.from_matrix(rotation).as_euler(root_order)
+ pose=np.zeros(channels);pose[:3]=positions[0];pose[3:6]=np.rad2deg(reference)
+ out.write((' '.join(f'{v:.9f}' for v in pose)+'\n').encode('ascii'))
+ previous=reference
for index,(fields,_) in enumerate(rows):
aa=angles[index].copy();bb=aa.copy();bb[0]+=np.pi;bb[1]=np.pi-bb[1];bb[2]+=np.pi
aa+=2*np.pi*np.round((previous-aa)/(2*np.pi));bb+=2*np.pi*np.round((previous-bb)/(2*np.pi))
diff --git a/mocap/source_export_dialog.py b/mocap/source_export_dialog.py
new file mode 100644
index 0000000..c0d2271
--- /dev/null
+++ b/mocap/source_export_dialog.py
@@ -0,0 +1,50 @@
+"""Source-motion export options; existing character exports remain separate."""
+from PySide6.QtWidgets import QDialog,QVBoxLayout,QFormLayout,QComboBox,QCheckBox,QLabel,QDialogButtonBox,QDoubleSpinBox,QLayout
+
+class SourceExportDialog(QDialog):
+ def __init__(self,parent=None):
+ super().__init__(parent);self.setWindowTitle('Export');self.setMinimumWidth(480)
+ self.model=parent.model_choice.currentData() if parent is not None and hasattr(parent,'model_choice') else None
+ layout=QVBoxLayout(self);layout.setSizeConstraint(QLayout.SetMinimumSize);form=QFormLayout();layout.addLayout(form)
+ self.format=QComboBox();self.format.addItem('FBX (.fbx)','fbx');self.format.addItem('BVH (.bvh)','bvh');self.format.addItem('Blender project + video (.blend)','blend')
+ form.addRow('Format',self.format)
+ self.profile=QComboBox();self.profile.addItem('Generic / Blender','generic');self.profile.addItem('3ds Max Biped','biped')
+ self.profile.setToolTip('Generic / Blender keeps anatomical names and original rotation orders. 3ds Max Biped uses Character Studio names and uniform ZXY rotations. Both keep metre units and Y up.')
+ self.profile_label=QLabel('BVH profile');form.addRow(self.profile_label,self.profile)
+ self.whole_scene=QCheckBox('MAMMA whole scene: body meshes and all cameras');layout.addWidget(self.whole_scene)
+ self.whole_scene.setToolTip('Export checked people, exact animated surfaces, reference skeletons and every calibrated camera/video. Keeps the original timeline. Mesh caches can be large.')
+ self.tpose=QCheckBox('Add T-pose before motion');self.tpose.setChecked(False)
+ self.tpose.setToolTip('Insert a T-pose at the first motion frame root position. Original frames shift by one; their poses and timing intervals stay unchanged.')
+ layout.addWidget(self.tpose)
+ self.animate_camera=QCheckBox('Export saved camera tracking');self.animate_camera.setChecked(True);layout.addWidget(self.animate_camera)
+ self.background_refine=QCheckBox('Refine Camera Rotation');layout.addWidget(self.background_refine)
+ from .camera_ui import BACKGROUND_HELP
+ self.background_refine.setToolTip(BACKGROUND_HELP)
+ if parent is not None and hasattr(parent,'camera_tools'):self.background_refine.setChecked(parent.camera_tools.background_options().get(self.model,False))
+ self.translation_scale=QDoubleSpinBox();self.translation_scale.setRange(0,100);self.translation_scale.setDecimals(3);self.translation_scale.setValue(1);self.translation_scale.setSingleStep(.1)
+ if parent is not None and hasattr(parent,'camera_tools'):self.translation_scale.setValue(parent.camera_tools.scale.value())
+ self.translation_scale.setToolTip('Approximate saved camera movement. 0 fixes the camera center; 1 uses the estimate. This does not change the source animation.')
+ self.scale_label=QLabel('Camera movement scale');form.addRow(self.scale_label,self.translation_scale)
+ self.note=QLabel();self.note.setWordWrap(True);layout.addWidget(self.note)
+ buttons=QDialogButtonBox(QDialogButtonBox.Save|QDialogButtonBox.Cancel)
+ buttons.button(QDialogButtonBox.Save).setText('Continue...');buttons.accepted.connect(self.accept);buttons.rejected.connect(self.reject);layout.addWidget(buttons)
+ for signal in (self.format.currentIndexChanged,self.whole_scene.toggled,self.animate_camera.toggled):signal.connect(self.update_format)
+ self.update_format()
+ def update_format(self):
+ fmt=self.format.currentData();blend=fmt=='blend';whole=blend and self.model=='mamma' and self.whole_scene.isChecked()
+ self.profile_label.setVisible(fmt=='bvh');self.profile.setVisible(fmt=='bvh')
+ self.whole_scene.setVisible(blend and self.model=='mamma');self.tpose.setEnabled(not whole);self.tpose.setVisible(not whole)
+ self.animate_camera.setVisible(blend and not whole)
+ camera=blend and not whole and self.model in ('flowhmr','exmr')
+ self.background_refine.setVisible(camera);self.background_refine.setEnabled(self.animate_camera.isChecked())
+ self.scale_label.setVisible(camera);self.translation_scale.setVisible(camera);self.translation_scale.setEnabled(self.animate_camera.isChecked())
+ text=('Creates a new folder containing the .blend, videos and mesh caches. Keep the folder together. Bodies are baked PC2 surfaces; skeletons are separate editable references. No T-pose is inserted.' if whole else
+ 'Creates a new folder containing the .blend and synchronized video. Keep both together. The video is a camera-view background, not a render background. Saved camera movement is approximate.' if blend else
+ 'Exports the selected source skeleton. BVH uses metres and Y up. The T-pose is an extra animation frame; it does not replace the character bind pose.')
+ self.note.setText(text)
+ self.layout().activate();self.adjustSize()
+ def options(self):
+ fmt=self.format.currentData();whole=fmt=='blend' and self.model=='mamma' and self.whole_scene.isChecked()
+ value=dict(format='blend_scene' if whole else fmt,bvh_profile=self.profile.currentData() if fmt=='bvh' else 'generic',prepend_tpose=self.tpose.isChecked() and not whole)
+ if fmt=='blend':value.update(animate_camera=self.animate_camera.isChecked(),background_refine=self.background_refine.isChecked() and self.animate_camera.isChecked() and self.model in ('flowhmr','exmr'),camera_translation_scale=self.translation_scale.value())
+ return value
diff --git a/mocap/source_export_worker.py b/mocap/source_export_worker.py
new file mode 100644
index 0000000..4caaf5b
--- /dev/null
+++ b/mocap/source_export_worker.py
@@ -0,0 +1,12 @@
+"""Derived BVH save entry without changing AI worker/cache fingerprints."""
+def main(emit):
+ import argparse,sys,time
+ from pathlib import Path
+ from .compute_policy import configure_worker_cpu
+ configure_worker_cpu('copy_bvh')
+ parser=argparse.ArgumentParser();parser.add_argument('--project',type=Path,required=True);parser.add_argument('--output',type=Path,required=True)
+ args=parser.parse_args(sys.argv[2:]);started=time.monotonic()
+ from .export_copy import run
+ count=run(args.output,emit)
+ emit('complete',stage='copy_bvh',files=count,elapsed=time.monotonic()-started)
+ return 0
diff --git a/mocap/theme.py b/mocap/theme.py
index d1cb088..a91baf2 100644
--- a/mocap/theme.py
+++ b/mocap/theme.py
@@ -25,6 +25,10 @@ QComboBox,QAbstractSpinBox { background:#454545; border:1px solid #242424; borde
QComboBox:hover,QAbstractSpinBox:hover { border-color:#737373; }
QComboBox QAbstractItemView { background:#333333; selection-background-color:#477bb7; }
QCheckBox { spacing:6px; }
+QCheckBox::indicator { width:14px; height:14px; border:1px solid #949494; border-radius:2px; background:#303030; }
+QCheckBox::indicator:hover { border-color:#d8e9ff; background:#404c59; }
+QCheckBox::indicator:checked { border-color:#c7ddf6; background:#477bb7; image:url("CHECK_ICON"); }
+QCheckBox::indicator:disabled { border-color:#666666; background:#353535; }
QListWidget#peopleList::item { min-height:24px; }
QListWidget#peopleList::indicator { width:16px; height:16px; border:1px solid #949494; border-radius:2px; background:#303030; }
QListWidget#peopleList::indicator:hover { border-color:#d8e9ff; background:#404c59; }
diff --git a/mocap/viewer.py b/mocap/viewer.py
index 9f1c3f9..2edcd5a 100644
--- a/mocap/viewer.py
+++ b/mocap/viewer.py
@@ -40,6 +40,7 @@ class VideoView(QWidget):
self._source_key = None
self.timeline_requested_index = 0
self.show_observations = True
+ self.projected_overlay = None
self.actor_color = None
self.zoom = 1.0
self.pan = QPointF()
@@ -262,6 +263,8 @@ class VideoView(QWidget):
if score >= 0.25:
painter.setBrush(QColor("#fff6cf"))
painter.drawEllipse(QPointF(offset_x + point[0] * ratio, offset_y + point[1] * ratio), 3, 3)
+ if self.show_observations and self.projected_overlay is not None:
+ self.projected_overlay(painter,rect)
painter.end()
self.frame_painted.emit(self.index)
diff --git a/mocap/viewport.py b/mocap/viewport.py
index 96dfec9..7cf67e2 100644
--- a/mocap/viewport.py
+++ b/mocap/viewport.py
@@ -85,6 +85,7 @@ class MotionView(ViewportBase):
self.show_trajectory = True
self.show_foot_locks = True
self.show_names = True
+ self.show_cameras=False;self.camera_records=[];self.camera_message='';self.camera_translation_scale=0.
self.actor_name = 'Person 1'
self.scene_names = {}
self.name_labels_presented = []
@@ -916,6 +917,19 @@ class MotionView(ViewportBase):
painter.drawText(QRectF(18, 39, self.width() - 36, 20), Qt.AlignLeft, f"Frame {index + 1} / {len(self.joints)}")
painter.drawText(QRectF(18, 60, self.width() - 36, 20), Qt.AlignLeft,
f"X {joints[0, 0]:+.2f} Z {joints[0, 2]:+.2f} m")
+ if self.show_cameras:
+ from .camera_tracks import at,geometry
+ for camera,trail in self.camera_records:
+ matrix=at(camera,self.scene_time,self.camera_translation_scale)
+ if matrix is None:continue
+ edges,origin=geometry(camera,matrix)
+ lines3d(edges,'#ffae42',1.4)
+ if len(trail)>1:lines3d(np.stack((trail[:-1],trail[1:]),axis=1),'#a48250',1.)
+ xy,z,_=self.project(origin)
+ if z>.08:
+ painter.setPen(QColor('#ffcc82'));painter.drawText(QPointF(xy[0]+5,xy[1]-5),camera['name'])
+ if self.camera_message:
+ painter.setPen(QColor('#e8c38d'));painter.drawText(self.rect().adjusted(18,125,-18,-18),Qt.AlignTop|Qt.TextWordWrap,self.camera_message)
characters_drawn=self.draw_characters(painter)
# Final independent depth layer: exported bones stay above characters,
# with the same ordering whether Bone Overlay was on or off previously.
diff --git a/mocap/worker_progress.py b/mocap/worker_progress.py
index 3f968c5..0413907 100644
--- a/mocap/worker_progress.py
+++ b/mocap/worker_progress.py
@@ -12,6 +12,18 @@ def emit(kind,**value):
def main():
stage=sys.argv[1] if len(sys.argv)>1 else ''
+ if stage in ('save_blend','save_blend_scene'):
+ from .blend_export_worker import main as save_main
+ return save_main(emit)
+ if stage=='camera_background':
+ from .camera_background_worker import main as camera_main
+ return camera_main()
+ if stage=='camera_reference':
+ from .camera_reference import main as camera_main
+ return camera_main()
+ if stage=='copy_bvh':
+ from .source_export_worker import main as save_main
+ return save_main(emit)
if stage=='flow_mamma_gravity':
from .mamma_gravity_worker import main as gravity_main
return gravity_main()
diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.py
index 86dc87b..63d87ef 100644
--- a/mocap/workspace_ui.py
+++ b/mocap/workspace_ui.py
@@ -144,14 +144,17 @@ def build_workspace(w):
video_header.addWidget(w.fps_label, 1)
overlay = QCheckBox("Overlays")
overlay.setChecked(True)
- overlay.setToolTip(tooltip_text('Show tracked people and detected body points over the video. Display only.'))
+ overlay.setToolTip(tooltip_text('Show tracked people, detected points and the reconstructed skeleton projected through the saved camera over the video. Display only.'))
def toggle_overlay(enabled):
w.video_view.show_observations = enabled
+ if hasattr(w,'camera_tools'):w.camera_tools.sync()
w.video_view.update()
overlay.toggled.connect(toggle_overlay)
w.video_overlay=overlay
video_header.addWidget(overlay)
- motion_panel, motion_header = editor("3D Viewport", w.motion_view)
+ from PySide6.QtWidgets import QStackedWidget
+ camera_stack=QStackedWidget()
+ motion_panel, motion_header = editor("3D Viewport", camera_stack)
w.bone_overlay=QCheckBox('Bone Overlay')
w.bone_overlay.setChecked(True)
w.bone_overlay.setToolTip(tooltip_text('Show the skeleton used for FBX export over the motion mesh. Display only.'))
@@ -159,15 +162,17 @@ def build_workspace(w):
motion_header.addWidget(w.bone_overlay)
w.view_choice = QComboBox()
w.view_choice.setToolTip(tooltip_text('Choose a viewing direction. This changes the camera, not the motion.'))
- w.view_choice.addItems(["Perspective", "Front", "Back", "Right", "Left", "Top", "Bottom"])
- w.view_choice.currentTextChanged.connect(w.motion_view.set_view)
+ w.view_choice.addItems(["Perspective", "Front", "Back", "Right", "Left", "Top", "Bottom", "Camera Preview"])
+ from .camera_ui import CameraTools
+ w.camera_tools=CameraTools(w,camera_stack,motion_header)
+ w.view_choice.currentTextChanged.connect(w.camera_tools.set_view)
def view_changed(name):
w.view_choice.blockSignals(True)
w.view_choice.setCurrentText(name)
w.view_choice.blockSignals(False)
w.motion_view.view_changed.connect(view_changed)
motion_header.addWidget(w.view_choice)
- frame_view = button("Frame All", w.motion_view.frame_all, motion_header)
+ frame_view = button("Frame All", lambda:w.camera_tools.canvas.reset_view() if w.camera_tools.preview() else w.motion_view.frame_all(), motion_header)
frame_view.setToolTip('Fit all visible people in the 3D view.')
w.viewport_footer = QWidget()
w.viewport_footer.setObjectName("editorHeader")
@@ -176,16 +181,17 @@ def build_workspace(w):
viewport_footer.setContentsMargins(9, 3, 6, 3)
w.viewport_checks={}
for label, attribute in (("Floor Grid", "show_grid"), ("Correction Floor", "show_correction_floor"), ("Motion Path", "show_trajectory"),
- ("Lock", "show_foot_locks"), ("Name", "show_names")):
+ ("Lock", "show_foot_locks"), ("Name", "show_names"), ("Camera", "show_cameras")):
check = QCheckBox(label)
w.viewport_checks[attribute]=check
check.setChecked(getattr(w.motion_view, attribute))
- check.setToolTip(tooltip_text({'show_grid': 'Show the reference grid at height zero. Does not change ground contact.', 'show_correction_floor': 'Show the correction floor height as an orange plane. Display only.', 'show_trajectory': 'Show the path followed by the person.', 'show_foot_locks': '', 'show_names': 'Show each person\'s name above their mesh. Rename people by right-clicking the People list. Display only.'}[attribute]))
+ check.setToolTip(tooltip_text({'show_grid': 'Show the reference grid at height zero. Does not change ground contact.', 'show_correction_floor': 'Show the correction floor height as an orange plane. Display only.', 'show_trajectory': 'Show the path followed by the person.', 'show_foot_locks': '', 'show_names': 'Show each person\'s name above their mesh. Rename people by right-clicking the People list. Display only.', 'show_cameras':'Show saved camera frustums and available camera motion. Display only; does not estimate or refit cameras.'}[attribute]))
if attribute=='show_names':w.name_labels=check
if attribute=='show_foot_locks':
check.setToolTip(tooltip_text('Show active foot and hand contacts as colored discs. Colors match the timeline. Display only; does not enable correction.'))
def toggle(enabled, attr=attribute):
setattr(w.motion_view, attr, enabled)
+ if attr=='show_cameras':w.camera_tools.sync()
w.motion_view.update()
check.toggled.connect(toggle)
viewport_footer.addWidget(check)
@@ -392,6 +398,11 @@ def build_workspace(w):
w.flow_sampling.setToolTip(tooltip_text('Choose Static Camera only if the camera stays still without zooming. Otherwise start with Moving / Unknown - Auto. Frame intervals control camera analysis only; shorter intervals use more memory. Applies on Reconstruct 3D.'))
w.flow_sampling.currentIndexChanged.connect(lambda _: w.update_readiness())
flow_camera.addWidget(w.flow_sampling)
+ from .camera_ui import BACKGROUND_HELP
+ w.flowhmr_background=QCheckBox('Refine Camera Rotation')
+ w.flowhmr_background.setChecked(False);w.flowhmr_background.setToolTip(tooltip_text(BACKGROUND_HELP))
+ w.flowhmr_background.toggled.connect(w.camera_tools.background_changed)
+ flow_camera.addWidget(w.flowhmr_background)
flow_help = QLabel('Native SMPL-H body and hands')
flow_help.setToolTip(tooltip_text('FlowHMR: body and finger tracking. Slow, with the best overall motion quality in our subjective tests.'))
flow_camera.addWidget(flow_help)
@@ -411,6 +422,11 @@ def build_workspace(w):
w.exmr_camera.addItem('Moving Camera / SimpleVO',False)
w.exmr_camera.setToolTip(tooltip_text('Choose Static Camera if the camera stays still without zooming. Choose Moving Camera if it moves. Applies next time you run Reconstruct 3D.'))
exmr.addWidget(w.exmr_camera)
+ from .camera_ui import BACKGROUND_HELP
+ w.exmr_background=QCheckBox('Refine Camera Rotation')
+ w.exmr_background.setChecked(False);w.exmr_background.setToolTip(tooltip_text(BACKGROUND_HELP))
+ w.exmr_background.toggled.connect(w.camera_tools.background_changed)
+ exmr.addWidget(w.exmr_background)
w.exmr_smoothing=QCheckBox('Smooth Motion')
w.exmr_smoothing.setChecked(True)
w.exmr_smoothing.setToolTip(tooltip_text('Reduce small changes between frames for smoother motion. Turn off to keep the unsmoothed result. Applies next time you run Reconstruct 3D.'))
@@ -573,15 +589,15 @@ def build_workspace(w):
w.save_project_action.setShortcut('Ctrl+Shift+S')
w.save_project_action.setToolTip(tooltip_text('Save a separate project folder with a new name and location, including its video, motion and settings. Continue working in the saved copy.'))
file_menu.addSeparator()
- w.export_action = file_menu.addAction("Export FBX...", w.save_fbx)
- w.export_action.setToolTip(tooltip_text('Save the displayed skeleton animation as FBX. For multiple people, each checked person gets a separate named file and rig.'))
+ w.export_action = file_menu.addAction("Export...", w.save_fbx)
+ w.export_action.setToolTip(tooltip_text('Export the displayed motion as FBX, BVH or a portable Blender project. Multiple people export separately; MAMMA also offers a whole-scene Blender bundle.'))
file_menu.addAction("Open Project Folder", w.open_folder)
file_menu.addSeparator()
file_menu.addAction("Exit", w.close)
help_menu = w.menuBar().addMenu("Help")
w.check_system_action = help_menu.addAction("Check System", lambda: w.start_jobs([("diagnose", [])]))
help_menu.addAction("Controls", lambda: QMessageBox.information(w, "Workspace Controls",
- "Space: Play / Pause\nLeft / Right: Step one frame\nShift + Left / Right: Step one second\nHome / End: First / last frame\n\nViewport: LMB orbit, MMB / RMB pan, wheel zoom\nGizmo: click an axis to align the view\nTimeline: drag video clip edges to trim\nClick the frame ruler or drag the blue frame box to seek\nWheel to zoom; MMB to pan; Reset Trim restores the full clip\nClick ? in the timeline header for editing help.\nPlayback and reconstruction use the selected video clip range.\n\nThe mesh shows the selected motion result.\nFlowHMR and ExMR track fingers directly. GVHMR uses optional HandFlow for finger tracking.\nUse File > Export FBX to save the displayed animation."))
+ "Space: Play / Pause\nLeft / Right: Step one frame\nShift + Left / Right: Step one second\nHome / End: First / last frame\n\nViewport: LMB orbit, MMB / RMB pan, wheel zoom\nGizmo: click an axis to align the view\nTimeline: drag video clip edges to trim\nClick the frame ruler or drag the blue frame box to seek\nWheel to zoom; MMB to pan; Reset Trim restores the full clip\nClick ? in the timeline header for editing help.\nPlayback and reconstruction use the selected video clip range.\n\nThe mesh shows the selected motion result.\nFlowHMR and ExMR track fingers directly. GVHMR uses optional HandFlow for finger tracking.\nUse File > Export to choose FBX, BVH or a portable Blender project and save the displayed animation."))
menu_help = {
'Open Video...': 'Choose a video to create motion from.',