Skip to content

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

Python

Fix character preview reload loop and long-path retarget exports

toyxyz7a9001441dba
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index 70d944e..9db9008 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -101,8 +101,8 @@
},
{
"path": "docs/VALIDATION.md",
- "bytes": 3817,
- "sha256": "689d72e826477b6306300a1a7a1ae2fc61b1817240479657e3fb19c68b787369"
+ "bytes": 4911,
+ "sha256": "8f5d4a81659420bf939ee394b9005bcfa988e00f42a1b346e3c7090d16f5bade"
},
{
"path": "docs/images/rgbmocap-workspace.png",
@@ -946,8 +946,8 @@
},
{
"path": "mocap/character_data.py",
- "bytes": 4343,
- "sha256": "4277e64cfe7eec62d048864857bccf82e80f01a87ed6ff5f7be8cedb1255e994"
+ "bytes": 4629,
+ "sha256": "bc4ce431193e5dabfe03f0853a41923cb19eeb70cb49c04f130ce2b6ad546e0b"
},
{
"path": "mocap/character_export_dialog.py",
@@ -1301,8 +1301,8 @@
},
{
"path": "mocap/retarget/blender_bake.py",
- "bytes": 8258,
- "sha256": "abe950f2b0ecc8777ff0ac802b145273383d7f3ad0372004c90e2502ba68df5f"
+ "bytes": 8296,
+ "sha256": "bde63f85766f36611a5b488f59ad4c11e73d1324528af18a8ac994ca58e7daa3"
},
{
"path": "mocap/retarget/blender_entry.py",
@@ -1311,13 +1311,13 @@
},
{
"path": "mocap/retarget/blender_geometry.py",
- "bytes": 3795,
- "sha256": "03e0fb48d06494fa771581ac91476972ff1f1ac11f21648573bb78364cc95a8c"
+ "bytes": 3837,
+ "sha256": "08e807facc8f54a341aeeace379cc471aa8fb2c8bdedabfdd8da8d015a0ff7ce"
},
{
"path": "mocap/retarget/blender_io.py",
- "bytes": 12339,
- "sha256": "55b2f0bc4dae651fd0c4ebffe55e5deef137e8655a5cbfdb167d7cc0f179eb05"
+ "bytes": 12567,
+ "sha256": "85523cfe0101b991d622fe9c8a10d92dae2dc214a2601f8329c0ee82d9d924af"
},
{
"path": "mocap/retarget/bounded_stabilizer.py",
@@ -1331,8 +1331,8 @@
},
{
"path": "mocap/retarget/file_paths.py",
- "bytes": 411,
- "sha256": "2daf10db98efe1ae9ecb518d83bf60dc65ddadfce1aa1d684a2abdd289aa306f"
+ "bytes": 1426,
+ "sha256": "34bbf11ddb08a4e88b02bf3759a0d31899b4616cac17c46751a03461d4871dbb"
},
{
"path": "mocap/retarget/foot_calibration.py",
@@ -1391,8 +1391,8 @@
},
{
"path": "mocap/retarget/vmd_export.py",
- "bytes": 8619,
- "sha256": "31159383d7f014381d58a75b50398a434e46f14465cd29f0e411affdc6ef69cc"
+ "bytes": 8742,
+ "sha256": "97ba9c1164a72f9250c1a024b094f4c3d627615904834f283df73e2d3f8de5f8"
},
{
"path": "mocap/retarget/worker.py",
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index 80457ab..1be9a08 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -54,6 +54,23 @@ outputs were kept outside the public checkout.
This audit did not repeat fresh installation, long-clip performance testing,
interactive playback, standalone MMD playback or testing on other GPUs.
+## Character preview and long-path fixes (2026-10-27)
+
+- Final preview windows no longer reload themselves. Loader checks covered
+ 1, 2, 10, 111, 112 and 400 frames, exact frame retrieval, bounded windows and
+ worker shutdown. An isolated five-second character viewport check loaded once
+ and performed no redraws after warm-up. This is an idle-loop check, not a
+ playback FPS or whole-desktop performance guarantee.
+- A 474-frame PMX animation was baked and reopened under a 295-character data
+ path. All 215 animation channels retained exactly the same key values as the
+ short-path baseline; no armature-object animation keys were added.
+- Animation-only FBX and PMX VMD exports succeeded at 289-character destination
+ paths. Blender reimport checks found finite sampled FBX poses and no object
+ transform keys. Short- and long-path VMD outputs were byte-identical.
+- Test scripts, character assets and generated outputs remained outside the
+ public checkout. These checks did not repeat standalone MMD playback or test
+ other GPUs, network shares or every possible Windows path.
+
These checks describe the recorded examples, not a guarantee for every video,
character or computer. Model weights and registered body data remain separate and
subject to their providers' terms. Review the applicable third-party notices and
diff --git a/mocap/character_data.py b/mocap/character_data.py
index d2a3b02..c22fc79 100644
--- a/mocap/character_data.py
+++ b/mocap/character_data.py
@@ -23,7 +23,10 @@ class CharacterLoader(QThread):
with self.condition:
window=self.windows.get(key)
if window and window[0]<=index<window[0]+len(window[1]):
- if index>=window[0]+len(window[1])*3//4:
+ # A final window already contains every remaining frame.
+ # Reloading it emits ready/changed and can create a repaint loop,
+ # especially for imported characters with a one-frame rest pose.
+ if window[0]+len(window[1])<window[2] and index>=window[0]+len(window[1])*3//4:
self.pending[key]=(index,self.epoch);self.condition.notify()
return window[1][index-window[0]]
self.request(path,index);return None
@@ -69,7 +72,7 @@ class CharacterLoader(QThread):
block=np.asarray(a[start:min(a.shape[0],start+count)]).copy()
with self.condition:
if requested!=self.epoch:continue
- self.windows[key]=(start,block)
+ self.windows[key]=(start,block,a.shape[0])
self.ready.emit(key,dict(asset=self.data[key],frames=a.shape[0],palette=a.shape[1]))
self.changed.emit()
except Exception as exc:
diff --git a/mocap/retarget/blender_bake.py b/mocap/retarget/blender_bake.py
index 9a9e163..75b71e3 100644
--- a/mocap/retarget/blender_bake.py
+++ b/mocap/retarget/blender_bake.py
@@ -1,7 +1,7 @@
import bpy,sys,json,time,numpy as np
from pathlib import Path
from mathutils import Matrix
-from .file_paths import io_path
+from .file_paths import io_path, save_blend
A=np.array([[1.,0,0],[0,0,-1],[0,1,0]])
def curves(action):
return action.fcurves if hasattr(action, 'fcurves') else next((b for l in action.layers for s in l.strips for b in s.channelbags)).fcurves
@@ -40,11 +40,11 @@ def align(a, b):
def bake(kind, label, method):
start = time.perf_counter()
timings = {}
- bpy.ops.wm.open_mainfile(filepath=str(OUT / (kind + '-rest.blend')))
- rig = json.loads((OUT / (kind + '-rig.json')).read_text(encoding='utf8'))
+ bpy.ops.wm.open_mainfile(filepath=io_path(OUT / (kind + '-rest.blend')))
+ rig = json.loads(Path(io_path(OUT / (kind + '-rig.json'))).read_text(encoding='utf8'))
arm = bpy.data.objects[rig['armature']]
arm.animation_data_clear()
- data = np.load(OUT / (label + '-' + kind + '-' + method + '.npz'))
+ data = np.load(io_path(OUT / (label + '-' + kind + '-' + method + '.npz')))
n = len(data['root'])
mapped = {name: i for (i, name) in enumerate(data['names'].tolist())}
bones = list(arm.data.bones)
@@ -52,7 +52,7 @@ def bake(kind, label, method):
rest = np.array([arm.matrix_world @ b.head_local for b in bones])
R0 = np.array([rotation(np.array(arm.matrix_world @ b.matrix_local)[:3, :3]) for b in bones])
parents = np.array([indices[b.parent.name] if b.parent else -1 for b in bones])
- source_entry = next((e for e in json.loads((OUT / 'sources.json').read_text()) if e['label'] == label))
+ source_entry = next((e for e in json.loads(Path(io_path(OUT / 'sources.json')).read_text()) if e['label'] == label))
folder = Path(source_entry['folder'])
info = source_entry['info']
source_frames = np.load(io_path(folder / info['frames_file']), mmap_mode='r')
@@ -60,7 +60,7 @@ def bake(kind, label, method):
source_names = info['names']
source_rest = source_asset['rest']
extra = {}
- base = np.load(OUT / (label + '-' + kind + '-rotation.npz'))
+ base = np.load(io_path(OUT / (label + '-' + kind + '-rotation.npz')))
for (j, name) in enumerate(source_names[22:], 22):
side = 'left' if name.startswith('Left') else 'right'
hand = 20 if side == 'left' else 21
@@ -157,8 +157,8 @@ def bake(kind, label, method):
assert all((c.data_path.startswith('pose.bones[') for c in curves(arm.animation_data.action)))
timings['fk_and_action_seconds'] = time.perf_counter() - fk_start
scene=bpy.context.scene
- fps=float(np.load(OUT/'motion-source.npz')['fps'])
+ fps=float(np.load(io_path(OUT/'motion-source.npz'))['fps'])
scene.frame_start=1;scene.frame_end=n;scene.render.fps=round(fps);scene.render.fps_base=round(fps)/fps
scene.frame_set(1)
- bpy.ops.wm.save_as_mainfile(filepath=str(OUT/'animation.blend'))
+ save_blend(OUT/'animation.blend')
return arm, sorted(keyed)
diff --git a/mocap/retarget/blender_geometry.py b/mocap/retarget/blender_geometry.py
index 75857c6..19b8058 100644
--- a/mocap/retarget/blender_geometry.py
+++ b/mocap/retarget/blender_geometry.py
@@ -1,5 +1,6 @@
import bpy,json,numpy as np
from .mapping import A
+from .file_paths import io_path
def register(OUT,kind,rig,arm,mapping,rest):
mapped={name:i for i,name in enumerate(mapping)};bone_map={}
if kind=='pmx':
@@ -46,4 +47,4 @@ def register(OUT,kind,rig,arm,mapping,rest):
assert len(hand_ids)>3,(kind,side,'palm')
payload.update({f'palm_v{side}':v[hand_ids],f'palm_w{side}':W[hand_ids],f'palm_ids{side}':hand_ids})
counts.append(dict(foot_vertices=len(ids),sole_vertices=len(bottom),palm_vertices=len(hand_ids),shin_weighted_sole_vertices=int((W[bottom,shin]>.5).sum())))
- np.savez(OUT/(kind+'-contact-geometry.npz'),**payload)
+ np.savez(io_path(OUT/(kind+'-contact-geometry.npz')),**payload)
diff --git a/mocap/retarget/blender_io.py b/mocap/retarget/blender_io.py
index dfaf767..1bdc68f 100644
--- a/mocap/retarget/blender_io.py
+++ b/mocap/retarget/blender_io.py
@@ -7,6 +7,7 @@ import numpy as np
import bpy
import addon_utils
from .mapping import A, PARENTS, body_mapping, body_trajectory_root
+from .file_paths import io_path, save_blend
def report(message):
@@ -14,7 +15,7 @@ def report(message):
def import_character(filename, out):
- out.mkdir(parents=True,exist_ok=True)
+ Path(io_path(out)).mkdir(parents=True,exist_ok=True)
kind={'.fbx':'mixamo','.vrm':'vrm','.pmx':'pmx'}[filename.suffix.lower()]
bpy.ops.wm.read_factory_settings(use_empty=True)
addons=Path(__file__).resolve().parents[2]/'third_party/character_import'
@@ -26,7 +27,7 @@ def import_character(filename, out):
elif kind=='vrm':
addon_utils.enable('io_scene_vrm',default_set=True,persistent=False)
bpy.ops.import_scene.vrm(filepath=str(filename))
- with filename.open('rb') as f:
+ with open(io_path(filename),'rb') as f:
if f.read(4)!=b'glTF':raise ValueError('Invalid VRM container')
f.read(8);length,chunk=struct.unpack('<II',f.read(8))
if length>32*1024*1024:raise ValueError('VRM metadata is too large')
@@ -74,17 +75,17 @@ def import_character(filename, out):
count=sum(len(o.data.vertices) for o in meshes)
if not 0<count<=1_000_000:raise ValueError('Character preview supports 1 to 1,000,000 vertices.')
rig=dict(kind=kind,armature=arm.name,semantic=semantic,trajectory_root=trajectory_root,bones=[dict(name=b.name,parent=b.parent.name if b.parent else None) for b in arm.data.bones],meshes=[dict(name=o.name,vertices=len(o.data.vertices)) for o in meshes])
- (out/f'{kind}-rig.json').write_text(json.dumps(rig,ensure_ascii=False),encoding='utf8')
- np.savez(out/f'{kind}-canonical.npz',rest=rest,names=mapping,parents=PARENTS)
+ Path(io_path(out/f'{kind}-rig.json')).write_text(json.dumps(rig,ensure_ascii=False),encoding='utf8')
+ np.savez(io_path(out/f'{kind}-canonical.npz'),rest=rest,names=mapping,parents=PARENTS)
from .blender_geometry import register
report('Registering soles, palms and humanoid proportions')
register(out,kind,rig,arm,mapping,rest)
bpy.ops.file.pack_all()
- bpy.ops.wm.save_as_mainfile(filepath=str(out/f'{kind}-rest.blend'))
+ save_blend(out/f'{kind}-rest.blend')
preview(out,arm,None,1)
metadata=dict(kind=kind,name=filename.stem,vertices=count,bones=len(arm.data.bones))
if kind=='pmx':metadata['mmd_import_scale']=.08
- (out/'import.json').write_text(json.dumps(metadata),encoding='utf8')
+ Path(io_path(out/'import.json')).write_text(json.dumps(metadata),encoding='utf8')
def vertex_colors(obj):
@@ -127,7 +128,8 @@ def vertex_colors(obj):
def preview(out,arm,keyed,n):
from .selective_fbx import body_dependencies
- kind=json.loads((out/'import.json').read_text())['kind'] if (out/'import.json').exists() else next(p.stem.split('-')[0] for p in out.glob('*-rig.json'))
+ metadata=Path(io_path(out/'import.json'))
+ kind=json.loads(metadata.read_text())['kind'] if metadata.exists() else next(p.stem.split('-')[0] for p in Path(io_path(out)).glob('*-rig.json'))
dynamic=set(keyed or [])|body_dependencies(kind,arm)
if not keyed:dynamic={b.name for b in arm.data.bones}
dynamic={name for name in dynamic if name in arm.data.bones}
@@ -157,8 +159,8 @@ def preview(out,arm,keyed,n):
from mocap.mesh_data import adjacency
vertices=np.concatenate(vertices).astype('float32');faces=np.asarray(faces,np.uint32)
offsets,neighbors=adjacency(faces,len(vertices))
- np.savez(out/'preview.npz',vertices=vertices,colors=np.concatenate(colors),faces=faces,weights=np.asarray(influences,np.float32),rows=np.asarray(rows,np.uint32),offsets=offsets,neighbors=neighbors)
- frames=np.lib.format.open_memmap(out/'preview-frames.npy',mode='w+',dtype='float32',shape=(n,len(palette)+1,4,4))
+ np.savez(io_path(out/'preview.npz'),vertices=vertices,colors=np.concatenate(colors),faces=faces,weights=np.asarray(influences,np.float32),rows=np.asarray(rows,np.uint32),offsets=offsets,neighbors=neighbors)
+ frames=np.lib.format.open_memmap(io_path(out/'preview-frames.npy'),mode='w+',dtype='float32',shape=(n,len(palette)+1,4,4))
C=np.eye(4);C[:3,:3]=A.T
rest_inv={name:([email protected][name].matrix_local).inverted() for name in palette}
for i in range(n):
@@ -179,7 +181,7 @@ def main(args):
arm,keyed=blender_bake.bake(rest[0],'motion','stance')
n=bpy.context.scene.frame_end
preview(out,arm,keyed,n)
- (out/'bake.json').write_text(json.dumps(dict(keyed_bones=keyed,frames=n,object_animation_channels=0)),encoding='utf8')
+ Path(io_path(out/'bake.json')).write_text(json.dumps(dict(keyed_bones=keyed,frames=n,object_animation_channels=0)),encoding='utf8')
elif mode=='export':
from .selective_fbx import body_only_sampler,body_dependencies
from mathutils import Matrix
@@ -188,17 +190,17 @@ def main(args):
options=json.loads(rest[4]) if len(rest)>4 else {}
fmt=options.get('format','fbx')
if fmt not in {'fbx','vmd'}:raise ValueError('Unsupported character export format')
- kind=json.loads((folder/'import.json').read_text(encoding='utf8'))['kind']
+ kind=json.loads(Path(io_path(folder/'import.json')).read_text(encoding='utf8'))['kind']
if fmt=='vmd':
if kind!='pmx':raise ValueError('VMD export requires a PMX character')
from .vmd_export import export_vmd
export_vmd(folder,target,transform,rest[3])
return
- bpy.ops.wm.open_mainfile(filepath=str(folder/'animation.blend'),load_ui=False)
+ bpy.ops.wm.open_mainfile(filepath=io_path(folder/'animation.blend'),load_ui=False)
arm=next(o for o in bpy.context.scene.objects if o.type=='ARMATURE')
arm.name=rest[3]
- info=json.loads((folder/'bake.json').read_text(encoding='utf8'))
- kind=json.loads((folder/'import.json').read_text(encoding='utf8'))['kind']
+ info=json.loads(Path(io_path(folder/'bake.json')).read_text(encoding='utf8'))
+ kind=json.loads(Path(io_path(folder/'import.json')).read_text(encoding='utf8'))['kind']
if transform is not None:
C=np.eye(4);C[:3,:3]=A
M=Matrix(([email protected](transform)@C.T).tolist())
@@ -214,9 +216,9 @@ def main(args):
with body_only_sampler(arm,set(info['keyed_bones'])|body_dependencies(kind,arm)):
# Explicit terminal markers keep Blender's Ignore Leaf Bones
# option from removing real terminal finger bones.
- bpy.ops.export_scene.fbx(filepath=str(temp),use_selection=True,object_types=types,add_leaf_bones=True,
+ bpy.ops.export_scene.fbx(filepath=io_path(temp),use_selection=True,object_types=types,add_leaf_bones=True,
bake_anim=True,bake_anim_use_all_bones=False,bake_anim_use_all_actions=False,bake_anim_use_nla_strips=False,
bake_anim_simplify_factor=0.,use_mesh_modifiers=True,path_mode='COPY',embed_textures=True)
- temp.replace(target)
- finally:temp.unlink(missing_ok=True)
+ Path(io_path(temp)).replace(io_path(target))
+ finally:Path(io_path(temp)).unlink(missing_ok=True)
else:raise ValueError('Unknown character operation')
diff --git a/mocap/retarget/file_paths.py b/mocap/retarget/file_paths.py
index c9b7a0d..d901d1b 100644
--- a/mocap/retarget/file_paths.py
+++ b/mocap/retarget/file_paths.py
@@ -10,3 +10,28 @@ def io_path(path):
if value.startswith('\\\\'):
return '\\\\?\\UNC\\' + value[2:]
return '\\\\?\\' + value
+
+
+def save_blend(path):
+ """Save Blender files despite its native long-path rename limitation."""
+ import bpy
+ value = os.path.abspath(os.fspath(path))
+ if os.name != 'nt' or len(value) < 240:
+ bpy.ops.wm.save_as_mainfile(filepath=value)
+ return
+ import shutil
+ import tempfile
+ import uuid
+ # Blender can read an extended path but its save/backup rename cannot.
+ # Keep packed resources and existing relative references unchanged, then
+ # publish through a sibling temporary file (also safe across volumes).
+ pending = io_path(value + '.' + uuid.uuid4().hex + '.partial')
+ try:
+ with tempfile.TemporaryDirectory(prefix='rgbmocap-blend-') as stage:
+ saved = os.path.join(stage, 'animation.blend')
+ bpy.ops.wm.save_as_mainfile(filepath=saved, relative_remap=False)
+ shutil.copyfile(saved, pending)
+ os.replace(pending, io_path(value))
+ finally:
+ if os.path.exists(pending):
+ os.unlink(pending)
diff --git a/mocap/retarget/vmd_export.py b/mocap/retarget/vmd_export.py
index 872d70e..f2af96f 100644
--- a/mocap/retarget/vmd_export.py
+++ b/mocap/retarget/vmd_export.py
@@ -5,6 +5,7 @@ camera, morph or physics data is generated. Outputs target the same PMX rig.
"""
import json,math,struct,sys,uuid
from pathlib import Path
+from .file_paths import io_path
import bpy,addon_utils
from mathutils import Matrix,Quaternion
@@ -54,10 +55,10 @@ def export_vmd(folder,target,transform,label):
from mmd_tools.core.vmd.importer import BoneConverter
from .mapping import A
import numpy as np
- bpy.ops.wm.open_mainfile(filepath=str(folder/'animation.blend'),load_ui=False)
+ bpy.ops.wm.open_mainfile(filepath=io_path(folder/'animation.blend'),load_ui=False)
arm=next(o for o in bpy.context.scene.objects if o.type=='ARMATURE')
- info=json.loads((folder/'bake.json').read_text(encoding='utf8'))
- rig=json.loads((folder/'pmx-rig.json').read_text(encoding='utf8'))
+ info=json.loads(Path(io_path(folder/'bake.json')).read_text(encoding='utf8'))
+ rig=json.loads(Path(io_path(folder/'pmx-rig.json')).read_text(encoding='utf8'))
names=set(info['keyed_bones']);compensate={}
# Native PMX grant/cancel rules still run in MMD, even when the Blender
# bake muted them. Cancel that contribution instead of applying it twice.
@@ -83,7 +84,7 @@ def export_vmd(folder,target,transform,label):
needed=set(names)
needed.update(arm.pose.bones[n].mmd_bone.additional_transform_bone for n in compensate)
sample_bones=[pb for pb in arm.pose.bones if pb.name in needed]
- scale=json.loads((folder/'import.json').read_text(encoding='utf8')).get('mmd_import_scale',.08)
+ scale=json.loads(Path(io_path(folder/'import.json')).read_text(encoding='utf8')).get('mmd_import_scale',.08)
converters={pb.name:BoneConverter(pb,1./scale,invert=True) for pb in sample_bones}
ik=set()
for pb in arm.pose.bones:
@@ -101,7 +102,7 @@ def export_vmd(folder,target,transform,label):
temp=target.with_name('.'+target.stem+'-'+uuid.uuid4().hex+'.partial.vmd')
previous={};linear=bytes([20]*4+[20]*4+[107]*4+[107]*4)*4
try:
- with temp.open('wb') as f:
+ with open(io_path(temp),'wb') as f:
f.write(b'Vocaloid Motion Data 0002'.ljust(30,b'\0'))
# The header is informational; bone names remain strict and exact.
title=label.encode('cp932',errors='replace')[:20]
@@ -148,5 +149,5 @@ def export_vmd(folder,target,transform,label):
f.write(struct.pack('<4I',0,0,0,0)) # morph, camera, light, shadow
f.write(struct.pack('<IIBI',1,0,1,len(ik_names)))
for name in ik_names:f.write(name+b'\0') # disable IK: retain baked FK contacts
- temp.replace(target)
- finally:temp.unlink(missing_ok=True)
+ Path(io_path(temp)).replace(io_path(target))
+ finally:Path(io_path(temp)).unlink(missing_ok=True)