| """ |
| BVH file parser for extracting skeleton structure and motion data. |
| |
| Handles arbitrary BVH files from different sources (Mixamo, LAFAN1, Truebones, etc.) |
| and converts them into our unified SkeletonGraph + motion tensor format. |
| """ |
|
|
| import numpy as np |
| import re |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Optional |
|
|
| from .skeleton_graph import SkeletonGraph, normalize_joint_name |
|
|
|
|
| @dataclass |
| class BVHData: |
| """Parsed BVH data.""" |
| skeleton: SkeletonGraph |
| rotations: np.ndarray |
| root_positions: np.ndarray |
| fps: float |
| num_frames: int |
| rotation_order: str |
| local_translations: np.ndarray | None = None |
|
|
|
|
| def parse_bvh(filepath: str | Path) -> BVHData: |
| """ |
| Parse a BVH file into skeleton structure + motion data. |
| |
| Returns: |
| BVHData with skeleton graph, rotations, root positions, and metadata. |
| """ |
| filepath = Path(filepath) |
| with open(filepath, 'r') as f: |
| content = f.read() |
|
|
| |
| parts = content.split('MOTION') |
| if len(parts) != 2: |
| raise ValueError(f"Invalid BVH format in {filepath}") |
|
|
| hierarchy_str = parts[0] |
| motion_str = parts[1] |
|
|
| |
| joint_names, parent_indices, rest_offsets, channels_per_joint, rotation_order = ( |
| _parse_hierarchy(hierarchy_str) |
| ) |
|
|
| |
| num_frames, frame_time, motion_data = _parse_motion(motion_str) |
| fps = 1.0 / frame_time if frame_time > 0 else 30.0 |
|
|
| |
| rest_offsets_arr = np.array(rest_offsets, dtype=np.float32) |
| rotations, root_positions, local_translations = _extract_motion_channels( |
| motion_data, channels_per_joint, len(joint_names), rest_offsets_arr |
| ) |
|
|
| |
| skeleton = SkeletonGraph( |
| joint_names=joint_names, |
| parent_indices=parent_indices, |
| rest_offsets=rest_offsets_arr, |
| ) |
|
|
| return BVHData( |
| skeleton=skeleton, |
| rotations=rotations, |
| root_positions=root_positions, |
| fps=fps, |
| num_frames=num_frames, |
| rotation_order=rotation_order, |
| local_translations=local_translations, |
| ) |
|
|
|
|
| def _parse_hierarchy(hierarchy_str: str): |
| """Parse BVH HIERARCHY section.""" |
| joint_names = [] |
| parent_indices = [] |
| rest_offsets = [] |
| channels_per_joint = [] |
| rotation_order = 'ZYX' |
|
|
| lines = hierarchy_str.strip().split('\n') |
| parent_stack = [-1] |
| current_joint_idx = -1 |
|
|
| for line in lines: |
| line = line.strip() |
|
|
| if line.startswith('ROOT') or line.startswith('JOINT'): |
| name = line.split()[-1] |
| current_joint_idx = len(joint_names) |
| joint_names.append(name) |
| parent_indices.append(parent_stack[-1]) |
|
|
| elif line.startswith('End Site'): |
| |
| parent_idx = current_joint_idx |
| name = f"{joint_names[parent_idx]}_end" |
| current_joint_idx = len(joint_names) |
| joint_names.append(name) |
| parent_indices.append(parent_idx) |
| channels_per_joint.append((0, False)) |
|
|
| elif line.startswith('OFFSET'): |
| vals = [float(x) for x in line.split()[1:4]] |
| rest_offsets.append(vals) |
|
|
| elif line.startswith('CHANNELS'): |
| parts = line.split() |
| num_ch = int(parts[1]) |
| ch_names = parts[2:] |
| has_position = any('position' in c.lower() for c in ch_names) |
| channels_per_joint.append((num_ch, has_position)) |
|
|
| |
| rot_channels = [c for c in ch_names if 'rotation' in c.lower()] |
| if rot_channels: |
| rotation_order = ''.join( |
| c[0].upper() for c in rot_channels |
| ) |
|
|
| elif line == '{': |
| parent_stack.append(current_joint_idx) |
|
|
| elif line == '}': |
| parent_stack.pop() |
| if parent_stack: |
| current_joint_idx = parent_stack[-1] |
|
|
| return joint_names, parent_indices, rest_offsets, channels_per_joint, rotation_order |
|
|
|
|
| def _parse_motion(motion_str: str): |
| """Parse BVH MOTION section.""" |
| lines = motion_str.strip().split('\n') |
|
|
| num_frames = 0 |
| frame_time = 1.0 / 30.0 |
| data_start = 0 |
|
|
| for i, line in enumerate(lines): |
| line = line.strip() |
| if line.startswith('Frames:'): |
| num_frames = int(line.split(':')[1].strip()) |
| elif line.startswith('Frame Time:'): |
| frame_time = float(line.split(':')[1].strip()) |
| elif line and not line.startswith('Frames') and not line.startswith('Frame'): |
| data_start = i |
| break |
|
|
| |
| motion_data = [] |
| for line in lines[data_start:]: |
| line = line.strip() |
| if line: |
| values = [float(x) for x in line.split()] |
| motion_data.append(values) |
|
|
| motion_data = np.array(motion_data, dtype=np.float32) |
|
|
| if len(motion_data) != num_frames and len(motion_data) > 0: |
| num_frames = len(motion_data) |
|
|
| return num_frames, frame_time, motion_data |
|
|
|
|
| def _extract_motion_channels( |
| motion_data: np.ndarray, |
| channels_per_joint: list[tuple[int, bool]], |
| num_joints: int, |
| rest_offsets: np.ndarray = None, |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]: |
| """Extract per-joint rotations, root positions, and local translations. |
| |
| Returns: |
| rotations: [T, J, 3] Euler angles |
| root_positions: [T, 3] |
| local_translations: [T, J, 3] or None — per-frame local translations |
| for joints that have position channels. None if only root has positions. |
| """ |
| T = len(motion_data) |
| rotations = np.zeros((T, num_joints, 3), dtype=np.float32) |
| root_positions = np.zeros((T, 3), dtype=np.float32) |
|
|
| |
| has_per_joint_positions = False |
| joint_has_pos = [False] * num_joints |
|
|
| col = 0 |
| joint_idx = 0 |
|
|
| for num_ch, has_position in channels_per_joint: |
| if num_ch == 0: |
| joint_idx += 1 |
| continue |
|
|
| if has_position and joint_idx == 0: |
| |
| root_positions = motion_data[:, col:col + 3].copy() |
| rotations[:, 0, :] = motion_data[:, col + 3:col + 6] |
| joint_has_pos[0] = True |
| col += num_ch |
| elif has_position: |
| |
| rotations[:, joint_idx, :] = motion_data[:, col + 3:col + 6] |
| joint_has_pos[joint_idx] = True |
| has_per_joint_positions = True |
| col += num_ch |
| else: |
| |
| rotations[:, joint_idx, :] = motion_data[:, col:col + 3] |
| col += num_ch |
|
|
| joint_idx += 1 |
|
|
| |
| local_translations = None |
| if has_per_joint_positions: |
| local_translations = np.zeros((T, num_joints, 3), dtype=np.float32) |
| |
| if rest_offsets is not None: |
| for j in range(num_joints): |
| local_translations[:, j, :] = rest_offsets[j] |
| |
| col = 0 |
| joint_idx = 0 |
| for num_ch, has_position in channels_per_joint: |
| if num_ch == 0: |
| joint_idx += 1 |
| continue |
| if has_position and joint_idx > 0: |
| local_translations[:, joint_idx, :] = motion_data[:, col:col + 3] |
| col += num_ch |
| joint_idx += 1 |
|
|
| return rotations, root_positions, local_translations |
|
|
|
|
| def resample_motion( |
| rotations: np.ndarray, |
| root_positions: np.ndarray, |
| source_fps: float, |
| target_fps: float = 20.0, |
| local_translations: np.ndarray = None, |
| ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]: |
| """Resample motion to target FPS via linear interpolation.""" |
| if abs(source_fps - target_fps) < 0.5: |
| if local_translations is not None: |
| return rotations, root_positions, local_translations |
| return rotations, root_positions |
|
|
| T_src = len(rotations) |
| duration = T_src / source_fps |
| T_tgt = int(duration * target_fps) |
|
|
| src_times = np.linspace(0, duration, T_src) |
| tgt_times = np.linspace(0, duration, T_tgt) |
|
|
| |
| J = rotations.shape[1] |
| new_rots = np.zeros((T_tgt, J, 3), dtype=np.float32) |
| for j in range(J): |
| for d in range(3): |
| new_rots[:, j, d] = np.interp(tgt_times, src_times, rotations[:, j, d]) |
|
|
| |
| new_pos = np.zeros((T_tgt, 3), dtype=np.float32) |
| for d in range(3): |
| new_pos[:, d] = np.interp(tgt_times, src_times, root_positions[:, d]) |
|
|
| |
| if local_translations is not None: |
| new_trans = np.zeros((T_tgt, J, 3), dtype=np.float32) |
| for j in range(J): |
| for d in range(3): |
| new_trans[:, j, d] = np.interp(tgt_times, src_times, local_translations[:, j, d]) |
| return new_rots, new_pos, new_trans |
|
|
| return new_rots, new_pos |
|
|
|
|
| def remove_end_sites( |
| joint_names: list[str], |
| parent_indices: list[int], |
| rest_offsets: np.ndarray, |
| rotations: np.ndarray, |
| ) -> tuple[list[str], list[int], np.ndarray, np.ndarray]: |
| """Remove End Site joints (they have no channels / zero rotations).""" |
| keep_mask = [not name.endswith('_end') for name in joint_names] |
| keep_indices = [i for i, k in enumerate(keep_mask) if k] |
|
|
| |
| old_to_new = {old: new for new, old in enumerate(keep_indices)} |
| old_to_new[-1] = -1 |
|
|
| new_names = [joint_names[i] for i in keep_indices] |
| new_parents = [old_to_new.get(parent_indices[i], -1) for i in keep_indices] |
| new_offsets = rest_offsets[keep_indices] |
| new_rotations = rotations[:, keep_indices, :] |
|
|
| return new_names, new_parents, new_offsets, new_rotations |
|
|