io_mesh_uv_layout: speed up png export with OIIO (x7)
[blender-addons.git] / io_scene_fbx / fbx2json.py
blob526e61ee0403dff8ee6f8363d6b5d860538cd10e
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: GPL-2.0-or-later
4 # Script copyright (C) 2006-2012, assimp team
5 # Script copyright (C) 2013 Blender Foundation
7 """
8 Usage
9 =====
11 fbx2json [FILES]...
13 This script will write a JSON file for each FBX argument given.
16 Output
17 ======
19 The JSON data is formatted into a list of nested lists of 4 items:
21 ``[id, [data, ...], "data_types", [subtree, ...]]``
23 Where each list may be empty, and the items in
24 the subtree are formatted the same way.
26 data_types is a string, aligned with data that spesifies a type
27 for each property.
29 The types are as follows:
31 * 'Y': - INT16
32 * 'C': - BOOL
33 * 'I': - INT32
34 * 'F': - FLOAT32
35 * 'D': - FLOAT64
36 * 'L': - INT64
37 * 'R': - BYTES
38 * 'S': - STRING
39 * 'f': - FLOAT32_ARRAY
40 * 'i': - INT32_ARRAY
41 * 'd': - FLOAT64_ARRAY
42 * 'l': - INT64_ARRAY
43 * 'b': - BOOL ARRAY
44 * 'c': - BYTE ARRAY
46 Note that key:value pairs aren't used since the id's are not
47 ensured to be unique.
48 """
51 # ----------------------------------------------------------------------------
52 # FBX Binary Parser
54 from struct import unpack
55 import array
56 import zlib
58 # at the end of each nested block, there is a NUL record to indicate
59 # that the sub-scope exists (i.e. to distinguish between P: and P : {})
60 _BLOCK_SENTINEL_LENGTH = ...
61 _BLOCK_SENTINEL_DATA = ...
62 read_fbx_elem_uint = ...
63 _IS_BIG_ENDIAN = (__import__("sys").byteorder != 'little')
64 _HEAD_MAGIC = b'Kaydara FBX Binary\x20\x20\x00\x1a\x00'
65 from collections import namedtuple
66 FBXElem = namedtuple("FBXElem", ("id", "props", "props_type", "elems"))
67 del namedtuple
70 def read_uint(read):
71 return unpack(b'<I', read(4))[0]
74 def read_uint64(read):
75 return unpack(b'<Q', read(8))[0]
78 def read_ubyte(read):
79 return unpack(b'B', read(1))[0]
82 def read_string_ubyte(read):
83 size = read_ubyte(read)
84 data = read(size)
85 return data
88 def unpack_array(read, array_type, array_stride, array_byteswap):
89 length = read_uint(read)
90 encoding = read_uint(read)
91 comp_len = read_uint(read)
93 data = read(comp_len)
95 if encoding == 0:
96 pass
97 elif encoding == 1:
98 data = zlib.decompress(data)
100 assert(length * array_stride == len(data))
102 data_array = array.array(array_type, data)
103 if array_byteswap and _IS_BIG_ENDIAN:
104 data_array.byteswap()
105 return data_array
108 read_data_dict = {
109 b'Y'[0]: lambda read: unpack(b'<h', read(2))[0], # 16 bit int
110 b'C'[0]: lambda read: unpack(b'?', read(1))[0], # 1 bit bool (yes/no)
111 b'I'[0]: lambda read: unpack(b'<i', read(4))[0], # 32 bit int
112 b'F'[0]: lambda read: unpack(b'<f', read(4))[0], # 32 bit float
113 b'D'[0]: lambda read: unpack(b'<d', read(8))[0], # 64 bit float
114 b'L'[0]: lambda read: unpack(b'<q', read(8))[0], # 64 bit int
115 b'R'[0]: lambda read: read(read_uint(read)), # binary data
116 b'S'[0]: lambda read: read(read_uint(read)), # string data
117 b'f'[0]: lambda read: unpack_array(read, 'f', 4, False), # array (float)
118 b'i'[0]: lambda read: unpack_array(read, 'i', 4, True), # array (int)
119 b'd'[0]: lambda read: unpack_array(read, 'd', 8, False), # array (double)
120 b'l'[0]: lambda read: unpack_array(read, 'q', 8, True), # array (long)
121 b'b'[0]: lambda read: unpack_array(read, 'b', 1, False), # array (bool)
122 b'c'[0]: lambda read: unpack_array(read, 'B', 1, False), # array (ubyte)
126 # FBX 7500 (aka FBX2016) introduces incompatible changes at binary level:
127 # * The NULL block marking end of nested stuff switches from 13 bytes long to 25 bytes long.
128 # * The FBX element metadata (end_offset, prop_count and prop_length) switch from uint32 to uint64.
129 def init_version(fbx_version):
130 global _BLOCK_SENTINEL_LENGTH, _BLOCK_SENTINEL_DATA, read_fbx_elem_uint
132 assert(_BLOCK_SENTINEL_LENGTH == ...)
133 assert(_BLOCK_SENTINEL_DATA == ...)
135 if fbx_version < 7500:
136 _BLOCK_SENTINEL_LENGTH = 13
137 read_fbx_elem_uint = read_uint
138 else:
139 _BLOCK_SENTINEL_LENGTH = 25
140 read_fbx_elem_uint = read_uint64
141 _BLOCK_SENTINEL_DATA = (b'\0' * _BLOCK_SENTINEL_LENGTH)
144 def read_elem(read, tell, use_namedtuple):
145 # [0] the offset at which this block ends
146 # [1] the number of properties in the scope
147 # [2] the length of the property list
148 end_offset = read_fbx_elem_uint(read)
149 if end_offset == 0:
150 return None
152 prop_count = read_fbx_elem_uint(read)
153 prop_length = read_fbx_elem_uint(read)
155 elem_id = read_string_ubyte(read) # elem name of the scope/key
156 elem_props_type = bytearray(prop_count) # elem property types
157 elem_props_data = [None] * prop_count # elem properties (if any)
158 elem_subtree = [] # elem children (if any)
160 for i in range(prop_count):
161 data_type = read(1)[0]
162 elem_props_data[i] = read_data_dict[data_type](read)
163 elem_props_type[i] = data_type
165 if tell() < end_offset:
166 while tell() < (end_offset - _BLOCK_SENTINEL_LENGTH):
167 elem_subtree.append(read_elem(read, tell, use_namedtuple))
169 if read(_BLOCK_SENTINEL_LENGTH) != _BLOCK_SENTINEL_DATA:
170 raise IOError("failed to read nested block sentinel, "
171 "expected all bytes to be 0")
173 if tell() != end_offset:
174 raise IOError("scope length not reached, something is wrong")
176 args = (elem_id, elem_props_data, elem_props_type, elem_subtree)
177 return FBXElem(*args) if use_namedtuple else args
180 def parse_version(fn):
182 Return the FBX version,
183 if the file isn't a binary FBX return zero.
185 with open(fn, 'rb') as f:
186 read = f.read
188 if read(len(_HEAD_MAGIC)) != _HEAD_MAGIC:
189 return 0
191 return read_uint(read)
194 def parse(fn, use_namedtuple=True):
195 root_elems = []
197 with open(fn, 'rb') as f:
198 read = f.read
199 tell = f.tell
201 if read(len(_HEAD_MAGIC)) != _HEAD_MAGIC:
202 raise IOError("Invalid header")
204 fbx_version = read_uint(read)
205 init_version(fbx_version)
207 while True:
208 elem = read_elem(read, tell, use_namedtuple)
209 if elem is None:
210 break
211 root_elems.append(elem)
213 args = (b'', [], bytearray(0), root_elems)
214 return FBXElem(*args) if use_namedtuple else args, fbx_version
217 # ----------------------------------------------------------------------------
218 # Inline Modules
220 # pyfbx.data_types
221 data_types = type(array)("data_types")
222 data_types.__dict__.update(
223 dict(
224 INT16 = b'Y'[0],
225 BOOL = b'C'[0],
226 INT32 = b'I'[0],
227 FLOAT32 = b'F'[0],
228 FLOAT64 = b'D'[0],
229 INT64 = b'L'[0],
230 BYTES = b'R'[0],
231 STRING = b'S'[0],
232 FLOAT32_ARRAY = b'f'[0],
233 INT32_ARRAY = b'i'[0],
234 FLOAT64_ARRAY = b'd'[0],
235 INT64_ARRAY = b'l'[0],
236 BOOL_ARRAY = b'b'[0],
237 BYTE_ARRAY = b'c'[0],
240 # pyfbx.parse_bin
241 parse_bin = type(array)("parse_bin")
242 parse_bin.__dict__.update(
243 dict(
244 parse = parse
248 # ----------------------------------------------------------------------------
249 # JSON Converter
250 # from pyfbx import parse_bin, data_types
251 import json
252 import array
255 def fbx2json_property_as_string(prop, prop_type):
256 if prop_type == data_types.STRING:
257 prop_str = prop.decode('utf-8')
258 prop_str = prop_str.replace('\x00\x01', '::')
259 return json.dumps(prop_str)
260 else:
261 prop_py_type = type(prop)
262 if prop_py_type == bytes:
263 return json.dumps(repr(prop)[2:-1])
264 elif prop_py_type == bool:
265 return json.dumps(prop)
266 elif prop_py_type == array.array:
267 return repr(list(prop))
269 return repr(prop)
272 def fbx2json_properties_as_string(fbx_elem):
273 return ", ".join(fbx2json_property_as_string(*prop_item)
274 for prop_item in zip(fbx_elem.props,
275 fbx_elem.props_type))
278 def fbx2json_recurse(fw, fbx_elem, ident, is_last):
279 fbx_elem_id = fbx_elem.id.decode('utf-8')
280 fw('%s["%s", ' % (ident, fbx_elem_id))
281 fw('[%s], ' % fbx2json_properties_as_string(fbx_elem))
282 fw('"%s", ' % (fbx_elem.props_type.decode('ascii')))
284 fw('[')
285 if fbx_elem.elems:
286 fw('\n')
287 ident_sub = ident + " "
288 for fbx_elem_sub in fbx_elem.elems:
289 fbx2json_recurse(fw, fbx_elem_sub, ident_sub,
290 fbx_elem_sub is fbx_elem.elems[-1])
291 fw(']')
293 fw(']%s' % ('' if is_last else ',\n'))
296 def fbx2json(fn):
297 import os
299 fn_json = "%s.json" % os.path.splitext(fn)[0]
300 print("Writing: %r " % fn_json, end="")
301 fbx_root_elem, fbx_version = parse(fn, use_namedtuple=True)
302 print("(Version %d) ..." % fbx_version)
304 with open(fn_json, 'w', encoding="ascii", errors='xmlcharrefreplace') as f:
305 fw = f.write
306 fw('[\n')
307 ident_sub = " "
308 for fbx_elem_sub in fbx_root_elem.elems:
309 fbx2json_recurse(f.write, fbx_elem_sub, ident_sub,
310 fbx_elem_sub is fbx_root_elem.elems[-1])
311 fw(']\n')
314 # ----------------------------------------------------------------------------
315 # Command Line
317 def main():
318 import sys
320 if "--help" in sys.argv:
321 print(__doc__)
322 return
324 for arg in sys.argv[1:]:
325 try:
326 fbx2json(arg)
327 except:
328 print("Failed to convert %r, error:" % arg)
330 import traceback
331 traceback.print_exc()
334 if __name__ == "__main__":
335 main()