Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.
Python
Add origin placement and symmetrical rest pose export options
toyxyz5aaad4eedf1d
diff --git a/README.md b/README.mdindex c4c3dac..e4f1346 100644--- a/README.md+++ b/README.md@@ -124,7 +124,7 @@ 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 or BVH (Generic/Blender or 3ds Max Biped), with an optional leading T-pose; export characters as FBX with or without meshes,+- Export source animation as FBX or BVH (Generic/Blender or 3ds Max Biped), with optional leading T-pose, per-person origin placement and symmetrical rest 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.- Save side-by-side input video and the current 3D viewport as MP4 with **File > Export Preview...** (offline models).diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.jsonindex 560927b..d2e1fb8 100644--- a/SOURCE_MANIFEST.json+++ b/SOURCE_MANIFEST.json@@ -1,6 +1,6 @@{"schema": 1,- "date": "2026-11-06",+ "date": "2026-11-07","purpose": "Public source distribution; excludes model weights and runtime binaries","version": "git-source","files": [@@ -26,8 +26,8 @@},{"path": "README.md",- "bytes": 12770,- "sha256": "e7e36b21ae1e57cea71012be7d50de37e2e8474dce7b2603675b92f439440169"+ "bytes": 12822,+ "sha256": "384c79746debba53e3681df8dce0ab614ee334f30903741587629a73a04f11aa"},{"path": "RGBMoCap.cmd",@@ -96,8 +96,8 @@},{"path": "docs/AGENT_GUIDE.md",- "bytes": 70853,- "sha256": "d82371616b0a7442e88dfb0ce9086fcd3aaca3d80b85122f5ba5536fbada6a22"+ "bytes": 72104,+ "sha256": "0cdce931109df97b7c06b034c6fd283e7e10c8a595fe41f22d821196a5366892"},{"path": "docs/BUILD.md",@@ -126,13 +126,13 @@},{"path": "docs/USER_GUIDE.md",- "bytes": 65698,- "sha256": "4ea64b0722fef3ca43bfab9c6266dcf8b6cf620060a46b8b29ebeb75db804ed8"+ "bytes": 67027,+ "sha256": "bc3f9b1759a750979cb28e025e304b012a23a9309e7914be1016b2a51467ff78"},{"path": "docs/VALIDATION.md",- "bytes": 144966,- "sha256": "fc430e80094d020c483ebc24e42af44d31b9540d5a9a2d734ff62f93e24400ce"+ "bytes": 147163,+ "sha256": "ec150427aac5043ce649b5881f1421f9d26f8875877cd8a9a9d1acbc3b80e4df"},{"path": "docs/images/exmr-interaction-contact.png",@@ -1091,8 +1091,8 @@},{"path": "mocap/blend_export.py",- "bytes": 6782,- "sha256": "da140bb620221b218d4ab3ed2e75f3405f9290e83b8728a1af52112561cb2af0"+ "bytes": 6829,+ "sha256": "ea555a2b3ebf745865bf1b63316b13642caab547cc7a33ec884f47cf2490f8c1"},{"path": "mocap/blend_export_scene.py",@@ -1286,8 +1286,13 @@},{"path": "mocap/export_copy.py",- "bytes": 3907,- "sha256": "2135999f0dcf15dde96e68d05147e4cfe6d550c2faeccb815634ccf8567db016"+ "bytes": 4284,+ "sha256": "eaecd4a99a39ab5ee75320de3afd4237d3c530177bb439c4d9b59ba8fe0f5aa0"+ },+ {+ "path": "mocap/export_options.py",+ "bytes": 6700,+ "sha256": "d6c5dc96def560c5605c5d0cfbedf83a66c7fdcd769a353f54e648e9b8cc5218"},{"path": "mocap/fbx_bind.py",@@ -1296,13 +1301,13 @@},{"path": "mocap/fbx_export.py",- "bytes": 3713,- "sha256": "2c091f3859ab09798c2f07be3b4751176d8fbf6de7664452873d630b3f162949"+ "bytes": 4355,+ "sha256": "26dc1e3d69d6362372fa8237d1c207f15d520f4bca1acfe5961f4c476f5e15c6"},{"path": "mocap/fbx_writer.py",- "bytes": 11097,- "sha256": "3bcececf7d0f5696927a465ffe866389611f6cf0d2dea41aae58d9bf695a229d"+ "bytes": 11979,+ "sha256": "79f0fa4b834618c29bb90d7caabd0275069a4b8b04f283541b08257cd8a4328d"},{"path": "mocap/floor_overlay.py",@@ -1396,8 +1401,8 @@},{"path": "mocap/gui.py",- "bytes": 108365,- "sha256": "d0cd184bc15a36c9e8c2f14c31a304bed2ed4e0e5f91c70fa13bdf334d365822"+ "bytes": 109036,+ "sha256": "42f8ed90c156e54f288ca1caa2bb70c1426fc495b46293f0f79acaeecedd5310"},{"path": "mocap/gvhmr_attention.py",@@ -2011,8 +2016,8 @@},{"path": "mocap/scene_export.py",- "bytes": 5994,- "sha256": "d28be38ca2ff85ae9ea2fdbf40e04b74319096f43b6fc7ac39a155657b4c194c"+ "bytes": 6848,+ "sha256": "40fe1c952d2e862ef51b1908ec5dac290fc17e4ac0a4fd66e0bf7801acc0d54d"},{"path": "mocap/scene_floor.py",@@ -2041,8 +2046,8 @@},{"path": "mocap/source_export_dialog.py",- "bytes": 5586,- "sha256": "94ed6f290981573b37f64282622337dc421fde69c49a6ca15e1f478c67375aae"+ "bytes": 6579,+ "sha256": "249553c514df565b1360fdb29a7f9b36e4d3b30db80318f4c964bb3e45c191f4"},{"path": "mocap/source_export_worker.py",diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.mdindex 11942c5..93ec863 100644--- a/docs/AGENT_GUIDE.md+++ b/docs/AGENT_GUIDE.md@@ -360,6 +360,24 @@ both original-frame and fractional-frame suffix poses in Blender after changes.### Portable Blender export implementation+Source FBX/BVH requests accept default-off `place_at_origin` and `symmetric_rest`.+`gui.py` attaches a stable `origin_group` for each person, distinct from display+names. Within an export batch, each actor's first exported take determines one+constant XZ offset; later takes retain their relative travel and Y is untouched.+This intentionally discards placement between different people.++`export_options.py` constructs mirrored averaged-length rest offsets and a+vertical central chain. BVH changes exported hierarchy offsets; a rest-only+Generic export preserves MOTION bytes. FBX uses the same canonical reference+geometry with new proper display/rest bases and corresponding terminal markers.+Validate input rigid offsets against the original committed bind, not the new+lengths. Do not materialize a full new animation or rerun inference/contacts.+Changed proportions intentionally change animated endpoints. Both options off+retain the existing bind/output. `blend_export.py` explicitly clears both flags+before its nested FBX export; MAMMA whole-scene requests never propagate them.+Keep source results/receipts immutable, stream bounded BVH blocks, and validate+ordinary Blender imports, profiles, T-pose combinations and independent actors.+`blend_export_ui.py` constructs requests and selects new, collision-free bundlefolders. `blend_export_worker.py` routes `save_blend`/`save_blend_scene` through`worker_progress.py` before inference fingerprinting. Keep the existing runtimediff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex f11962f..3f9da81 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -680,6 +680,26 @@ before the original motion, at its initial root position; original frames shiftby one and retain their poses, frame rate and intervals. The option does notreplace the bind pose or edit project motion/contact timings.+**Place at origin** and **Symmetrical rest pose** default off and apply only to+source-skeleton FBX/BVH exports, including both BVH profiles. They are unavailable+for Blender project exports and do not change imported-character exports.++- **Place at origin:** move each person's first exported root position to X=0,+ Z=0, preserving its height, facing and subsequent travel. People are centered+ independently, so their relative scene placement is intentionally removed.+ Multiple exported takes of one person share the first exported take's constant+ offset rather than resetting at every tracking gap. An optional leading T-pose+ uses the same centered start.+- **Symmetrical rest pose:** average paired left/right segment lengths and mirror+ their reference directions, including shoulders, feet, hands, fingers and end+ tips. The central spine/neck/head chain is vertical. Motion timing and canonical+ animation rotations are retained, but the changed reference proportions move+ animated joint/end positions; existing hand/foot contacts are not re-solved.+ Source motion, correction results, viewport geometry and cached bind data remain+ unchanged. The option is a reference skeleton change, not an added T-pose frame.++The export options window keeps the same size when switching formats.+BVH uses the same 52-bone hierarchy, metre units and Y up, including finger bonesand terminal tips. Import into Blender with **Scale 1 / Forward -Z / Up Y**.The **3ds Max Biped** profile follows the PR #18 conversion: it uses Characterdiff --git a/docs/VALIDATION.md b/docs/VALIDATION.mdindex 624155e..5a9fec7 100644--- a/docs/VALIDATION.md+++ b/docs/VALIDATION.md@@ -2213,3 +2213,35 @@ MAMMA preparation reuses a committed pre-fix result without running processing.These are isolated fixture tests, not public-provider downloads, GUI click tests,new motion inference or a clean-Windows installation. No user model/project fileswere changed. Test scripts and outputs are kept outside the public source tree.++## Optional origin placement and symmetrical source export (2026-11-07)++Source FBX/BVH exports now offer default-off origin placement and symmetrical+rest geometry. Origin placement subtracts one constant horizontal translation per+actor; height and travel are retained. Ordered takes of one actor share that+offset. Symmetry averages paired lengths, mirrors reference segments/tips and+straightens the central spine/neck/head chain. These change only exported copies;+changed proportions can change animated hand/foot endpoints without contact IK.+Portable Blender exports explicitly exclude both options.++24 actual worker exports covered both flags on/off, optional T-pose, Generic BVH,+Biped BVH and FBX, using a short copied ExMR result and a nonidentity shared-scene+rotation/translation. Additional FBX files used four-frame samples from existing+FlowHMR, GVHMR, MAMMA and PromptHMR caches, with symmetry on/off. All 32 files were+reimported through Blender 4.5.0's ordinary importers. Maximum sampled joint+position discrepancy against expected FK was 0.013 mm, rest-head discrepancy+below 0.001 mm, and mirrored imported bone-length discrepancy below 0.001 mm.+This is file-conversion agreement, not inference accuracy or a contact-quality+claim. Tests account for Blender BVH's first key at frame 1 and FBX offset 0.++Default FBX output remained byte-identical to the preceding writer, with and+without its optional T-pose. Default Generic BVH copying remained byte-identical;+symmetry-only Generic export retained MOTION bytes. Other checks covered averaged+segment lengths, mirrored terminal tips, vertical central joints, independent+actor origins/later takes, malformed input rejection, source-file preservation,+failure before commit, destination preservation and closed frame mappings.+15 offscreen dialog cases across all five offline models retained a 660x400+logical-pixel window, visible unclipped controls and disabled/hidden options for+Blender. Representative images were visually inspected. The new work did not run+AI inference, modify user caches or test a complete real-time export gesture.+Scripts, fixtures and generated files remain outside the public source tree.diff --git a/mocap/blend_export.py b/mocap/blend_export.pyindex ee8177b..013e73e 100644--- a/mocap/blend_export.py+++ b/mocap/blend_export.py@@ -58,7 +58,7 @@ def run(request,emit=lambda *a,**k:None):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.workcopy_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')+ nested=work/'fbx-request.json';nested.write_text(json.dumps([{**row,'target':str(work/'animation.fbx'),'place_at_origin':False,'symmetric_rest':False}]),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'],diff --git a/mocap/export_copy.py b/mocap/export_copy.pyindex 38df086..986e1bb 100644--- a/mocap/export_copy.py+++ b/mocap/export_copy.py@@ -11,7 +11,7 @@ def run(request,emit=lambda *a,**k:None):if request.stat().st_size>4*1024**2:raise ValueError('Export request is too large')rows=json.loads(request.read_text(encoding='utf-8'))if not isinstance(rows,list) or not 1<=len(rows)<=4096:raise ValueError('Invalid export request')- staged=[]+ staged=[];origins={}try:for i,row in enumerate(rows):profile=row.get('bvh_profile','generic')@@ -30,19 +30,24 @@ 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')- 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))+ transform=np.eye(4) if scene is None else np.asarray(scene['transform'],float)+ if row.get('place_at_origin',False):+ from .export_options import centered_transform,first_bvh_root+ transform=centered_transform(transform,first_bvh_root(inp),origins,row.get('origin_group',str(project)))+ symmetric=row.get('symmetric_rest',False)+ prepare=row.get('prepend_tpose',False) or symmetric or not np.allclose(transform,np.eye(4),rtol=0,atol=1e-12)if profile=='biped':from .biped_bvh import convertif prepare:from tempfile import TemporaryFilefrom .scene_export import transform_motionwith 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))+ transform_motion(inp,prepared,transform,progress,prepend_tpose=row.get('prepend_tpose',False),symmetric_rest=symmetric)prepared.seek(0);convert(prepared,out,progress)else:convert(inp,out,progress)elif prepare:from .scene_export import transform_motion- transform_motion(inp,out,np.eye(4) if scene is None else scene['transform'],progress,prepend_tpose=row.get('prepend_tpose',False))+ transform_motion(inp,out,transform,progress,prepend_tpose=row.get('prepend_tpose',False),symmetric_rest=symmetric)else:while True:chunk=inp.read(1024*1024)diff --git a/mocap/export_options.py b/mocap/export_options.pynew file mode 100644index 0000000..67ac5e6--- /dev/null+++ b/mocap/export_options.py@@ -0,0 +1,115 @@+"""Optional transforms of exported copies, never of committed source motion."""+import numpy as np+++def symmetric_rest(names, parents, rest, ends):+ """Mirror averaged paired segments; place the central chain vertically."""+ parents=np.asarray(parents);rest=np.asarray(rest,float);ends=np.asarray(ends,float)+ if len(names)!=52 or len(set(names))!=52 or rest.shape!=(52,3) or ends.shape!=(52,3) or parents.shape!=(52,):+ raise ValueError('Expected the complete anatomical 52-bone skeleton')+ if names[0]!='Hips' or parents[0]!=-1 or any(not 0<=parents[j]<j for j in range(1,52)):+ raise ValueError('Invalid export hierarchy')+ if not np.isfinite(rest).all() or not np.isfinite(ends).all():raise ValueError('Non-finite rest pose')+ offsets=rest.copy();offsets[1:]-=rest[parents[1:]]+ result=np.zeros_like(rest);tips=ends.copy();mirror=np.array([-1.,1.,1.])+ central={'Hips','Spine','Spine1','Spine2','Neck','Head'}+ lookup={name:j for j,name in enumerate(names)}+ for j,name in enumerate(names):+ if name in central:+ offsets[j]=[0.,float(np.linalg.norm(offsets[j])),0.]+ tips[j]=[0.,float(np.linalg.norm(ends[j])),0.]+ elif name.startswith('Left'):+ other='Right'+name[4:]+ if other not in lookup:raise ValueError('Missing paired bone: '+other)+ k=lookup[other]+ expected=names[parents[j]]+ expected='Right'+expected[4:] if expected.startswith('Left') else expected+ if names[parents[k]]!=expected:raise ValueError('Mismatched paired hierarchy')+ for values in (offsets,tips):+ a=values[j].copy();b=values[k]*mirror+ length=(np.linalg.norm(a)+np.linalg.norm(b))*.5+ direction=a+b;norm=np.linalg.norm(direction)+ if length>1e-10 and norm<1e-10:raise ValueError('Opposed paired rest directions')+ values[j]=direction*(length/norm) if norm>1e-10 else 0.+ values[k]=values[j]*mirror+ elif name.startswith('Right'):+ if 'Left'+name[5:] not in lookup:raise ValueError('Missing paired bone: '+name)+ else:raise ValueError('Unsupported anatomical bone: '+name)+ for j,p in enumerate(parents):result[j]=offsets[j] if p<0 else result[p]+offsets[j]+ floor=min(result[lookup['LeftToeBase'],1],result[lookup['RightToeBase'],1])+ result[:,1]-=floor+ return result,tips+++def centered_transform(transform, first_root, origins, group):+ """Keep one XZ offset per actor across its ordered visible takes."""+ matrix=np.asarray(transform,float).copy()+ root=matrix[:3,:3]@np.asarray(first_root,float)+matrix[:3,3]+ if not np.isfinite(root).all():raise ValueError('Non-finite initial root')+ if group not in origins:origins[group]=np.array([root[0],0.,root[2]])+ matrix[:3,3]-=origins[group]+ return matrix+++def read_header(inp, symmetric=False):+ """Read a bounded, strict source BVH header and optionally replace offsets."""+ lines=[];names=[];parents=[];offsets=[];ends=[];offset_lines={};end_lines={}+ stack=[];pending=None;channels=0;root_order=None;orders=[];header_bytes=0+ for _ in range(4096):+ line=inp.readline(65537)+ if not line or len(line)>65536:raise ValueError('Invalid BVH hierarchy')+ header_bytes+=len(line)+ if header_bytes>2*1024**2:raise ValueError('BVH hierarchy is too large')+ index=len(lines);lines.append(line);tokens=line.split()+ if tokens[:1] in ([b'ROOT'],[b'JOINT']):+ if len(tokens)!=2:raise ValueError('Invalid BVH joint')+ parent=stack[-1] if stack else -1+ if parent is None or (tokens[0]==b'ROOT')!=(not names):raise ValueError('Invalid BVH hierarchy root')+ pending=len(names);names.append(tokens[1].decode('ascii'));parents.append(parent)+ if len(names)>52:raise ValueError('Expected 52 anatomical bones')+ offsets.append(None);ends.append(np.zeros(3))+ elif tokens==[b'End',b'Site']:pending=None+ elif tokens==[b'{']:stack.append(pending)+ elif tokens==[b'}']:+ if not stack:raise ValueError('Invalid BVH braces')+ stack.pop()+ elif tokens[:1]==[b'OFFSET']:+ value=np.asarray(tokens[1:],float)+ if value.shape!=(3,) or not np.isfinite(value).all() or not stack:raise ValueError('Invalid BVH offset')+ if stack[-1] is None:+ joint=stack[-2];ends[joint]=value;end_lines[joint]=index+ else:+ joint=stack[-1];offsets[joint]=value;offset_lines[joint]=index+ elif tokens[:1]==[b'CHANNELS']:+ if not stack or stack[-1] is None:raise ValueError('Invalid BVH channels')+ joint=stack[-1];count=int(tokens[1]);expected=6 if joint==0 else 3+ if count!=expected or len(tokens)!=count+2:raise ValueError('Invalid BVH channel count')+ if joint==0 and tokens[2:5]!=[b'Xposition',b'Yposition',b'Zposition']:raise ValueError('Invalid root position channels')+ rotation=tokens[5:] if joint==0 else tokens[2:]+ if sorted(rotation)!=[b'Xrotation',b'Yrotation',b'Zrotation']:raise ValueError('Invalid BVH rotation channels')+ order=''.join(v[:1].decode('ascii') for v in rotation);orders.append(order);channels+=count+ if joint==0:root_order=order+ if line.strip()==b'MOTION':break+ else:raise ValueError('BVH hierarchy is too large')+ if stack or len(names)!=52 or channels!=159 or len(orders)!=52 or any(v is None for v in offsets):raise ValueError('Expected the complete 52-bone BVH')+ if symmetric:+ rest=np.asarray(offsets,float);parents=np.asarray(parents)+ for j,p in enumerate(parents):+ if p>=0:rest[j]+=rest[p]+ rest,tips=symmetric_rest(names,parents,rest,np.asarray(ends))+ for j,index in offset_lines.items():+ value=rest[j] if parents[j]<0 else rest[j]-rest[parents[j]]+ lines[index]=b' OFFSET '+(' '.join(f'{v:.9f}' for v in value)).encode('ascii')+b'\n'+ for j,index in end_lines.items():lines[index]=b' OFFSET '+(' '.join(f'{v:.9f}' for v in tips[j])).encode('ascii')+b'\n'+ return lines,root_order+++def first_bvh_root(inp):+ position=inp.tell()+ try:+ read_header(inp)+ if not inp.readline(256).startswith(b'Frames:') or not inp.readline(256).startswith(b'Frame Time:'):raise ValueError('Invalid BVH timing')+ row=np.asarray(inp.readline(65537).split(),float)+ if row.shape!=(159,) or not np.isfinite(row).all():raise ValueError('Invalid initial BVH frame')+ return row[:3]+ finally:inp.seek(position)diff --git a/mocap/fbx_export.py b/mocap/fbx_export.pyindex 57ed880..d6fdf97 100644--- a/mocap/fbx_export.py+++ b/mocap/fbx_export.py@@ -14,7 +14,7 @@ def run(request, emit=lambda *a, **k:None):if request.stat().st_size>4*1024**2:raise ValueError('Export request is too large')rows=json.loads(request.read_text(encoding='utf-8'))if not isinstance(rows,list) or not 1<=len(rows)<=4096:raise ValueError('Invalid export request')- staged=[]+ staged=[];origins={}try:for i,row in enumerate(rows):project=Path(row['project']);kind=row['kind'];target=Path(row['target'])@@ -38,14 +38,22 @@ def run(request, emit=lambda *a, **k:None):needed=('parents','fbx_rest','fbx_rest_frames','fbx_display_frames','fbx_tip_local')if not all(k in data for k in needed):raise ValueError('FBX rest pose is unavailable. Use Prepare Preview first.')a={k:data[k] for k in needed}+ symmetric=None+ if row.get('symmetric_rest',False):+ if not all(k in data for k in ('rest','ends')):raise ValueError('Symmetric rest data is unavailable. Use Prepare Preview first.')+ symmetric=dict(rest=data['rest'],ends=data['ends'])frames=np.load(project/info['frames_file'],mmap_mode='r',allow_pickle=False)try:+ transform=np.eye(4) if scene is None else np.asarray(scene['transform'],float)+ if row.get('place_at_origin',False):+ from .export_options import centered_transform+ transform=centered_transform(transform,frames[0,0,:3,3],origins,row.get('origin_group',str(project)))def progress(done,total):emit('progress',stage='save_fbx',current=i*52+done,total=len(rows)*52,message='Export FBX: '+kind)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'),prepend_tpose=row.get('prepend_tpose',False))+ transform=transform,progress=progress,+ rig_name=row.get('rig_name','SourceAnimation'),prepend_tpose=row.get('prepend_tpose',False),symmetric_bind=symmetric)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.pyindex 78afe17..847d8a2 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', prepend_tpose=False):+ transform=None, progress=lambda *args:None, rig_name='SourceAnimation', prepend_tpose=False,symmetric_bind=None):"""Write one committed mapped take; working rotation arrays are one bone wide."""from .person_names import validate_namerig_name=validate_name(rig_name)@@ -86,6 +86,20 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, ffor a in (rest_frames,display):if np.max(abs(a.swapaxes(-1,-2)@a-np.eye(3)))>1e-5 or np.linalg.det(a).min()<.99999:raise ValueError('Invalid FBX rest rotation')+ source_display=display+ source_offsets=[rest[j] if p<0 else rest_frames[p].T@(rest[j]-rest[p]) for j,p in enumerate(parents)]+ if symmetric_bind is not None:+ from .export_options import symmetric_rest+ from .bone_overlay import reference_frame+ rest,ends=symmetric_rest(names,parents,symmetric_bind['rest'],symmetric_bind['ends'])+ display=[]+ for j in range(52):+ children=np.flatnonzero(parents==j)+ delta=rest[children].mean(0)-rest[j] if len(children) else ends[j]+ if np.linalg.norm(delta)<.001:delta=delta+[0.,.1,0.]+ display.append(reference_frame(delta))+ display=np.asarray(display);rest_frames=display+ tip_local=np.einsum('nji,nj->ni',display,ends)from .scene_camera import validate_transformtransform=validate_transform(np.eye(4) if transform is None else transform)ids=np.arange(1000,1052);objects=[];connections=[]@@ -166,8 +180,9 @@ def write(path, names, parents, rest, rest_frames, display, tip_local, frames, felse:parent=np.asarray(frames[:,p,:3,:3],float)@display[p]local=parent.swapaxes(-1,-2)@world- actual=np.einsum('tji,tj->ti',parent,np.asarray(frames[:,j,:3,3],float)-frames[:,p,:3,3])- if not np.isfinite(actual).all() or np.max(abs(actual-offsets[j]))>2e-5:+ source_parent=np.asarray(frames[:,p,:3,:3],float)@source_display[p]+ actual=np.einsum('tji,tj->ti',source_parent,np.asarray(frames[:,j,:3,3],float)-frames[:,p,:3,3])+ if not np.isfinite(actual).all() or np.max(abs(actual-source_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:diff --git a/mocap/gui.py b/mocap/gui.pyindex 2b608d9..fa0c647 100644--- a/mocap/gui.py+++ b/mocap/gui.py@@ -1813,6 +1813,14 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWorow['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 in ('place_at_origin','symmetric_rest'):+ row[key]=getattr(self,'_source_export_options',{}).get(key,False) and getattr(self,'_source_export_options',{}).get('format','fbx') in ('fbx','bvh')+ row['origin_group']=str(Path(project).resolve())+ if self.people_state:+ from .people_store import safe_child+ for person in self.people_state['people']:+ if any(safe_child(self.people_root,t['project'])==Path(project).resolve() for t in person.get('takes',[])):+ row['origin_group']='person:'+str(person['id']);breakfor 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:diff --git a/mocap/scene_export.py b/mocap/scene_export.pyindex eb2d3a0..863a3da 100644--- a/mocap/scene_export.py+++ b/mocap/scene_export.py@@ -33,13 +33,18 @@ def context(root,project):sources=camera['sources'],anchor_sources=anchor['sources'],model=camera.get('model'))-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."""+def transform_motion(inp,out,transform,progress=lambda:None,prepend_tpose=False,symmetric_rest=False):+ """Stream root transforms; optionally replace only exported rest offsets."""from scipy.spatial.transform import Rotationimport warningstransform=validate_transform(transform);rotation=transform[:3,:3];translation=transform[:3,3]channels=0;root_seen=False;root_order=None+ if symmetric_rest:+ from .export_options import read_header+ lines,root_order=read_header(inp,symmetric=True)+ out.writelines(lines);channels=159;root_seen=Truefor _ in range(4096):+ if symmetric_rest:breakline=inp.readline(65537)if not line or len(line)>65536:raise ValueError('Invalid BVH hierarchy')out.write(line);tokens=line.split()@@ -60,6 +65,16 @@ def transform_motion(inp,out,transform,progress=lambda:None,prepend_tpose=False)if count<1 or not np.isfinite(step) or step<=0:raise ValueError('Invalid BVH timing')out.write(f'Frames: {count+1}\n'.encode('ascii') if prepend_tpose else count_line)out.write(time_line);previous=np.zeros(3)+ if symmetric_rest and not prepend_tpose and np.array_equal(transform,np.eye(4)):+ # Rest-only exports retain the committed motion encoding byte-for-byte.+ for first in range(0,count,128):+ for _ in range(min(128,count-first)):+ line=inp.readline(65537);values=np.asarray(line.split(),float)+ if len(line)>65536 or values.shape!=(159,) or not np.isfinite(values).all():raise ValueError('Invalid BVH motion')+ out.write(line)+ progress()+ if inp.read(1):raise ValueError('Unexpected trailing BVH data')+ returnfor first in range(0,count,128):rows=[]for _ in range(min(128,count-first)):diff --git a/mocap/source_export_dialog.py b/mocap/source_export_dialog.pyindex c0d2271..db3d086 100644--- a/mocap/source_export_dialog.py+++ b/mocap/source_export_dialog.py@@ -1,11 +1,12 @@"""Source-motion export options; existing character exports remain separate."""-from PySide6.QtWidgets import QDialog,QVBoxLayout,QFormLayout,QComboBox,QCheckBox,QLabel,QDialogButtonBox,QDoubleSpinBox,QLayout+from PySide6.QtWidgets import QDialog,QVBoxLayout,QFormLayout,QComboBox,QCheckBox,QLabel,QDialogButtonBox,QDoubleSpinBoxclass SourceExportDialog(QDialog):def __init__(self,parent=None):- super().__init__(parent);self.setWindowTitle('Export');self.setMinimumWidth(480)+ super().__init__(parent);self.setWindowTitle('Export');self.setFixedSize(660,400)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)+ layout=QVBoxLayout(self);layout.setContentsMargins(18,18,18,18);layout.setSpacing(12)+ form=QFormLayout();form.setVerticalSpacing(12);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')@@ -16,6 +17,10 @@ class SourceExportDialog(QDialog):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.place_at_origin=QCheckBox('Place at origin');layout.addWidget(self.place_at_origin)+ self.place_at_origin.setToolTip("Center each person's first exported frame on world X/Z. Height and travel are preserved. People are centered independently; their relative placement changes.")+ self.symmetric_rest=QCheckBox('Symmetrical rest pose');layout.addWidget(self.symmetric_rest)+ self.symmetric_rest.setToolTip('Use mirrored left/right rest bones with averaged paired lengths and a straight vertical spine. Animation rotations and timing are retained; changed proportions can move hands and feet. Exported files only.')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@@ -26,6 +31,7 @@ class SourceExportDialog(QDialog):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)+ layout.addStretch(1)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)@@ -34,6 +40,7 @@ class SourceExportDialog(QDialog):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)+ for control in (self.place_at_origin,self.symmetric_rest):control.setVisible(not blend);control.setEnabled(not blend)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())@@ -42,9 +49,10 @@ class SourceExportDialog(QDialog):'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()+ self.layout().activate()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)+ value.update(place_at_origin=self.place_at_origin.isChecked() and fmt in ('fbx','bvh'),symmetric_rest=self.symmetric_rest.isChecked() and fmt in ('fbx','bvh'))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