Tevior commited on
Commit
9b97d00
·
verified ·
1 Parent(s): 71aab22

Upload src/data/fbx_reader.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/data/fbx_reader.py +392 -0
src/data/fbx_reader.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Minimal pure-Python FBX binary reader for extracting skeleton animation data.
3
+
4
+ Parses FBX binary format to extract:
5
+ - Node hierarchy (skeleton tree)
6
+ - Animation curves (rotation, translation per bone)
7
+ - Rest pose (bind pose)
8
+
9
+ Then converts to our BVH-like internal format for further processing.
10
+
11
+ Reference: https://code.blender.org/2013/08/fbx-binary-file-format-specification/
12
+ """
13
+
14
+ import struct
15
+ import zlib
16
+ import numpy as np
17
+ from pathlib import Path
18
+ from dataclasses import dataclass, field
19
+ from typing import Optional, Any
20
+
21
+
22
+ # ============================================================
23
+ # FBX Binary Parser
24
+ # ============================================================
25
+
26
+ @dataclass
27
+ class FBXNode:
28
+ name: str
29
+ properties: list = field(default_factory=list)
30
+ children: list = field(default_factory=list)
31
+
32
+ def find(self, name: str) -> Optional['FBXNode']:
33
+ for c in self.children:
34
+ if c.name == name:
35
+ return c
36
+ return None
37
+
38
+ def find_all(self, name: str) -> list['FBXNode']:
39
+ return [c for c in self.children if c.name == name]
40
+
41
+
42
+ def read_fbx(filepath: str | Path) -> FBXNode:
43
+ """Read an FBX binary file and return the root node."""
44
+ with open(filepath, 'rb') as f:
45
+ data = f.read()
46
+
47
+ # Check magic
48
+ magic = b'Kaydara FBX Binary \x00'
49
+ if not data[:len(magic)] == magic:
50
+ raise ValueError("Not a valid FBX binary file")
51
+
52
+ # Version
53
+ version = struct.unpack_from('<I', data, 23)[0]
54
+
55
+ # Parse nodes
56
+ offset = 27
57
+ root = FBXNode(name='__root__')
58
+
59
+ if version >= 7500:
60
+ sentinel_size = 25 # 64-bit offsets
61
+ else:
62
+ sentinel_size = 13 # 32-bit offsets
63
+
64
+ while offset < len(data) - sentinel_size:
65
+ node, offset = _read_node(data, offset, version)
66
+ if node is None:
67
+ break
68
+ root.children.append(node)
69
+
70
+ return root
71
+
72
+
73
+ def _read_node(data: bytes, offset: int, version: int) -> tuple[Optional[FBXNode], int]:
74
+ """Read a single FBX node."""
75
+ if version >= 7500:
76
+ end_offset = struct.unpack_from('<Q', data, offset)[0]
77
+ num_props = struct.unpack_from('<Q', data, offset + 8)[0]
78
+ props_len = struct.unpack_from('<Q', data, offset + 16)[0]
79
+ name_len = data[offset + 24]
80
+ name = data[offset + 25:offset + 25 + name_len].decode('ascii', errors='replace')
81
+ offset = offset + 25 + name_len
82
+ else:
83
+ end_offset = struct.unpack_from('<I', data, offset)[0]
84
+ num_props = struct.unpack_from('<I', data, offset + 4)[0]
85
+ props_len = struct.unpack_from('<I', data, offset + 8)[0]
86
+ name_len = data[offset + 12]
87
+ name = data[offset + 13:offset + 13 + name_len].decode('ascii', errors='replace')
88
+ offset = offset + 13 + name_len
89
+
90
+ if end_offset == 0:
91
+ return None, offset
92
+
93
+ # Read properties
94
+ props = []
95
+ props_end = offset + props_len
96
+ for _ in range(num_props):
97
+ prop, offset = _read_property(data, offset)
98
+ props.append(prop)
99
+
100
+ node = FBXNode(name=name, properties=props)
101
+
102
+ # Read children
103
+ sentinel = b'\x00' * (25 if version >= 7500 else 13)
104
+ while offset < end_offset:
105
+ if data[offset:offset + len(sentinel)] == sentinel:
106
+ offset += len(sentinel)
107
+ break
108
+ child, offset = _read_node(data, offset, version)
109
+ if child is None:
110
+ break
111
+ node.children.append(child)
112
+
113
+ offset = max(offset, end_offset)
114
+ return node, offset
115
+
116
+
117
+ def _read_property(data: bytes, offset: int) -> tuple[Any, int]:
118
+ """Read a single FBX property value."""
119
+ type_code = chr(data[offset])
120
+ offset += 1
121
+
122
+ if type_code == 'Y': # int16
123
+ val = struct.unpack_from('<h', data, offset)[0]
124
+ return val, offset + 2
125
+ elif type_code == 'C': # bool
126
+ val = data[offset] != 0
127
+ return val, offset + 1
128
+ elif type_code == 'I': # int32
129
+ val = struct.unpack_from('<i', data, offset)[0]
130
+ return val, offset + 4
131
+ elif type_code == 'F': # float32
132
+ val = struct.unpack_from('<f', data, offset)[0]
133
+ return val, offset + 4
134
+ elif type_code == 'D': # float64
135
+ val = struct.unpack_from('<d', data, offset)[0]
136
+ return val, offset + 8
137
+ elif type_code == 'L': # int64
138
+ val = struct.unpack_from('<q', data, offset)[0]
139
+ return val, offset + 8
140
+ elif type_code == 'S': # string
141
+ length = struct.unpack_from('<I', data, offset)[0]
142
+ val = data[offset + 4:offset + 4 + length].decode('utf-8', errors='replace')
143
+ return val, offset + 4 + length
144
+ elif type_code == 'R': # raw bytes
145
+ length = struct.unpack_from('<I', data, offset)[0]
146
+ val = data[offset + 4:offset + 4 + length]
147
+ return val, offset + 4 + length
148
+ elif type_code in ('f', 'd', 'l', 'i', 'b'):
149
+ # Array types
150
+ arr_len = struct.unpack_from('<I', data, offset)[0]
151
+ encoding = struct.unpack_from('<I', data, offset + 4)[0]
152
+ comp_len = struct.unpack_from('<I', data, offset + 8)[0]
153
+ offset += 12
154
+
155
+ raw = data[offset:offset + comp_len]
156
+ if encoding == 1:
157
+ raw = zlib.decompress(raw)
158
+
159
+ dtype_map = {'f': '<f4', 'd': '<f8', 'l': '<i8', 'i': '<i4', 'b': 'bool'}
160
+ arr = np.frombuffer(raw, dtype=dtype_map[type_code])[:arr_len]
161
+ return arr, offset + comp_len
162
+ else:
163
+ raise ValueError(f"Unknown FBX property type: {type_code}")
164
+
165
+
166
+ # ============================================================
167
+ # FBX → Skeleton + Animation extraction
168
+ # ============================================================
169
+
170
+ def extract_skeleton_and_animation(fbx_root: FBXNode) -> dict:
171
+ """
172
+ Extract skeleton hierarchy and animation data from parsed FBX.
173
+
174
+ Returns dict with:
175
+ - joint_names: list[str]
176
+ - parent_indices: list[int]
177
+ - rest_offsets: [J, 3]
178
+ - rotations: [T, J, 3] Euler degrees
179
+ - root_positions: [T, 3]
180
+ - fps: float
181
+ """
182
+ objects = fbx_root.find('Objects')
183
+ if objects is None:
184
+ raise ValueError("No Objects section in FBX")
185
+
186
+ # Find all Model nodes (bones/joints)
187
+ models = {}
188
+ for node in objects.children:
189
+ if node.name == 'Model':
190
+ model_id = node.properties[0] if node.properties else None
191
+ model_name = str(node.properties[1]).split('\x00')[0] if len(node.properties) > 1 else ''
192
+ model_type = str(node.properties[2]) if len(node.properties) > 2 else ''
193
+
194
+ if 'LimbNode' in model_type or 'Root' in model_type or 'Null' in model_type:
195
+ # Extract local translation
196
+ local_trans = np.zeros(3)
197
+ props70 = node.find('Properties70')
198
+ if props70:
199
+ for p in props70.children:
200
+ if p.name == 'P' and p.properties and str(p.properties[0]) == 'Lcl Translation':
201
+ local_trans = np.array([
202
+ float(p.properties[4]),
203
+ float(p.properties[5]),
204
+ float(p.properties[6]),
205
+ ])
206
+
207
+ models[model_id] = {
208
+ 'name': model_name,
209
+ 'type': model_type,
210
+ 'translation': local_trans,
211
+ }
212
+
213
+ # Find connections to build parent-child hierarchy
214
+ connections = fbx_root.find('Connections')
215
+ parent_map = {} # child_id → parent_id
216
+ if connections:
217
+ for c in connections.children:
218
+ if c.name == 'C' and c.properties and str(c.properties[0]) == 'OO':
219
+ child_id = c.properties[1]
220
+ parent_id = c.properties[2]
221
+ if child_id in models and parent_id in models:
222
+ parent_map[child_id] = parent_id
223
+
224
+ # Build ordered joint list (BFS from roots)
225
+ roots = [mid for mid in models if mid not in parent_map]
226
+ if not roots:
227
+ raise ValueError("No root bones found")
228
+
229
+ joint_names = []
230
+ parent_indices = []
231
+ rest_offsets = []
232
+ id_to_idx = {}
233
+
234
+ queue = [(rid, -1) for rid in roots]
235
+ while queue:
236
+ mid, pidx = queue.pop(0)
237
+ idx = len(joint_names)
238
+ id_to_idx[mid] = idx
239
+ joint_names.append(models[mid]['name'])
240
+ parent_indices.append(pidx)
241
+ rest_offsets.append(models[mid]['translation'])
242
+
243
+ # Find children
244
+ for child_id, par_id in parent_map.items():
245
+ if par_id == mid:
246
+ queue.append((child_id, idx))
247
+
248
+ rest_offsets = np.array(rest_offsets, dtype=np.float32)
249
+
250
+ # Extract animation curves
251
+ anim_layers = []
252
+ for node in objects.children:
253
+ if node.name == 'AnimationLayer':
254
+ anim_layers.append(node)
255
+
256
+ # Find AnimationCurveNode → Model connections
257
+ anim_curve_nodes = {}
258
+ for node in objects.children:
259
+ if node.name == 'AnimationCurveNode':
260
+ acn_id = node.properties[0] if node.properties else None
261
+ acn_name = str(node.properties[1]).split('\x00')[0] if len(node.properties) > 1 else ''
262
+ anim_curve_nodes[acn_id] = {'name': acn_name, 'curves': {}}
263
+
264
+ # Find AnimationCurve data
265
+ anim_curves = {}
266
+ for node in objects.children:
267
+ if node.name == 'AnimationCurve':
268
+ ac_id = node.properties[0] if node.properties else None
269
+ key_time = None
270
+ key_value = None
271
+ for child in node.children:
272
+ if child.name == 'KeyTime' and child.properties:
273
+ key_time = child.properties[0]
274
+ elif child.name == 'KeyValueFloat' and child.properties:
275
+ key_value = child.properties[0]
276
+ if key_time is not None and key_value is not None:
277
+ anim_curves[ac_id] = {
278
+ 'times': np.array(key_time, dtype=np.int64),
279
+ 'values': np.array(key_value, dtype=np.float64),
280
+ }
281
+
282
+ # Link curves to bones via connections
283
+ # Connection: AnimationCurve → AnimationCurveNode → Model
284
+ acn_to_model = {} # acn_id → (model_id, property_name)
285
+ ac_to_acn = {} # ac_id → (acn_id, channel_idx)
286
+
287
+ if connections:
288
+ for c in connections.children:
289
+ if c.name == 'C' and len(c.properties) >= 3:
290
+ ctype = str(c.properties[0])
291
+ child_id = c.properties[1]
292
+ parent_id = c.properties[2]
293
+
294
+ if ctype == 'OO':
295
+ if child_id in anim_curve_nodes and parent_id in models:
296
+ prop_name = anim_curve_nodes[child_id]['name']
297
+ acn_to_model[child_id] = (parent_id, prop_name)
298
+ elif child_id in anim_curves and parent_id in anim_curve_nodes:
299
+ ac_to_acn[child_id] = parent_id
300
+ elif ctype == 'OP':
301
+ if child_id in anim_curves and parent_id in anim_curve_nodes:
302
+ channel = str(c.properties[3]) if len(c.properties) > 3 else ''
303
+ ac_to_acn[child_id] = parent_id
304
+ anim_curve_nodes[parent_id]['curves'][channel] = child_id
305
+
306
+ # Determine frame count and FPS
307
+ all_times = set()
308
+ for ac_id, ac_data in anim_curves.items():
309
+ for t in ac_data['times']:
310
+ all_times.add(int(t))
311
+
312
+ if not all_times:
313
+ # No animation, return rest pose
314
+ return {
315
+ 'joint_names': joint_names,
316
+ 'parent_indices': parent_indices,
317
+ 'rest_offsets': rest_offsets,
318
+ 'rotations': np.zeros((1, len(joint_names), 3), dtype=np.float32),
319
+ 'root_positions': rest_offsets[0:1].copy(),
320
+ 'fps': 30.0,
321
+ }
322
+
323
+ sorted_times = sorted(all_times)
324
+ fbx_ticks_per_sec = 46186158000 # FBX time unit
325
+ if len(sorted_times) > 1:
326
+ dt = sorted_times[1] - sorted_times[0]
327
+ fps = fbx_ticks_per_sec / dt if dt > 0 else 30.0
328
+ else:
329
+ fps = 30.0
330
+
331
+ T = len(sorted_times)
332
+ time_to_frame = {t: i for i, t in enumerate(sorted_times)}
333
+
334
+ # Build rotation and position arrays
335
+ J = len(joint_names)
336
+ rotations = np.zeros((T, J, 3), dtype=np.float64)
337
+ positions = np.tile(rest_offsets, (T, 1, 1)).astype(np.float64)
338
+
339
+ for acn_id, acn_data in anim_curve_nodes.items():
340
+ if acn_id not in acn_to_model:
341
+ continue
342
+ model_id, prop_name = acn_to_model[acn_id]
343
+ if model_id not in id_to_idx:
344
+ continue
345
+ j = id_to_idx[model_id]
346
+
347
+ for channel_key, ac_id in acn_data['curves'].items():
348
+ if ac_id not in anim_curves:
349
+ continue
350
+ ac_data = anim_curves[ac_id]
351
+
352
+ # Determine axis
353
+ axis = -1
354
+ ck = channel_key.lower()
355
+ if 'x' in ck or ck == 'd|x':
356
+ axis = 0
357
+ elif 'y' in ck or ck == 'd|y':
358
+ axis = 1
359
+ elif 'z' in ck or ck == 'd|z':
360
+ axis = 2
361
+
362
+ if axis < 0:
363
+ continue
364
+
365
+ # Fill in values
366
+ for t_val, v_val in zip(ac_data['times'], ac_data['values']):
367
+ t_int = int(t_val)
368
+ if t_int in time_to_frame:
369
+ f = time_to_frame[t_int]
370
+ if 'rotation' in prop_name.lower() or 'Lcl Rotation' in prop_name:
371
+ rotations[f, j, axis] = v_val
372
+ elif 'translation' in prop_name.lower() or 'Lcl Translation' in prop_name:
373
+ positions[f, j, axis] = v_val
374
+
375
+ root_positions = positions[:, 0, :]
376
+
377
+ return {
378
+ 'joint_names': joint_names,
379
+ 'parent_indices': parent_indices,
380
+ 'rest_offsets': rest_offsets,
381
+ 'rotations': rotations.astype(np.float32),
382
+ 'root_positions': root_positions.astype(np.float32),
383
+ 'fps': float(fps),
384
+ }
385
+
386
+
387
+ def fbx_to_bvh_data(filepath: str | Path) -> dict:
388
+ """
389
+ High-level: read FBX file and return data compatible with our BVH pipeline.
390
+ """
391
+ fbx_root = read_fbx(filepath)
392
+ return extract_skeleton_and_animation(fbx_root)