File size: 10,365 Bytes
0ac31aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff1e50
0ac31aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff1e50
 
 
0ac31aa
 
 
 
 
 
eff1e50
0ac31aa
 
 
 
 
 
 
 
 
eff1e50
0ac31aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff1e50
 
 
 
 
 
 
 
 
 
0ac31aa
 
 
 
eff1e50
 
 
 
0ac31aa
 
 
 
 
 
 
 
 
 
eff1e50
0ac31aa
eff1e50
0ac31aa
 
eff1e50
0ac31aa
eff1e50
 
0ac31aa
 
 
 
 
 
 
 
eff1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ac31aa
 
 
 
 
 
 
eff1e50
 
0ac31aa
 
eff1e50
 
0ac31aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff1e50
 
 
 
 
 
 
 
0ac31aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""
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  # [T, J, 3] Euler angles (degrees)
    root_positions: np.ndarray  # [T, 3]
    fps: float
    num_frames: int
    rotation_order: str  # e.g., 'ZYX'
    local_translations: np.ndarray | None = None  # [T, J, 3] per-frame local translations (if available)


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()

    # Split into HIERARCHY and MOTION sections
    parts = content.split('MOTION')
    if len(parts) != 2:
        raise ValueError(f"Invalid BVH format in {filepath}")

    hierarchy_str = parts[0]
    motion_str = parts[1]

    # Parse hierarchy
    joint_names, parent_indices, rest_offsets, channels_per_joint, rotation_order = (
        _parse_hierarchy(hierarchy_str)
    )

    # Parse motion data
    num_frames, frame_time, motion_data = _parse_motion(motion_str)
    fps = 1.0 / frame_time if frame_time > 0 else 30.0

    # Extract rotations and root positions from channel data
    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
    )

    # Build skeleton graph
    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 = []  # list of (num_channels, has_position)
    rotation_order = 'ZYX'  # default

    lines = hierarchy_str.strip().split('\n')
    parent_stack = [-1]  # stack of parent indices
    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'):
            # End effector — we'll add it as a leaf joint
            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))

            # Detect rotation order from channel names
            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

    # Parse frame data
    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)

    # Track which non-root joints have position channels
    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 joint: extract position (3) + rotation (3)
            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:
            # Non-root with position channels
            rotations[:, joint_idx, :] = motion_data[:, col + 3:col + 6]
            joint_has_pos[joint_idx] = True
            has_per_joint_positions = True
            col += num_ch
        else:
            # Rotation only
            rotations[:, joint_idx, :] = motion_data[:, col:col + 3]
            col += num_ch

        joint_idx += 1

    # Build per-joint local translations if any non-root joint has position channels
    local_translations = None
    if has_per_joint_positions:
        local_translations = np.zeros((T, num_joints, 3), dtype=np.float32)
        # Fill with rest_offsets as default
        if rest_offsets is not None:
            for j in range(num_joints):
                local_translations[:, j, :] = rest_offsets[j]
        # Overwrite with per-frame position data where available
        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)

    # Interpolate rotations [T, J, 3]
    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])

    # Interpolate root positions [T, 3]
    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])

    # Interpolate local translations if present [T, J, 3]
    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]

    # Remap indices
    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