core.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. """
  2. PyAssimp
  3. This is the main-module of PyAssimp.
  4. """
  5. import sys
  6. if sys.version_info < (2,6):
  7. raise RuntimeError('pyassimp: need python 2.6 or newer')
  8. # xrange was renamed range in Python 3 and the original range from Python 2 was removed.
  9. # To keep compatibility with both Python 2 and 3, xrange is set to range for version 3.0 and up.
  10. if sys.version_info >= (3,0):
  11. xrange = range
  12. try: import numpy
  13. except ImportError: numpy = None
  14. import logging
  15. import ctypes
  16. logger = logging.getLogger("pyassimp")
  17. # attach default null handler to logger so it doesn't complain
  18. # even if you don't attach another handler to logger
  19. logger.addHandler(logging.NullHandler())
  20. from . import structs
  21. from . import helper
  22. from . import postprocess
  23. from .errors import AssimpError
  24. class AssimpLib(object):
  25. """
  26. Assimp-Singleton
  27. """
  28. load, load_mem, export, export_blob, release, dll = helper.search_library()
  29. _assimp_lib = AssimpLib()
  30. def make_tuple(ai_obj, type = None):
  31. res = None
  32. #notes:
  33. # ai_obj._fields_ = [ ("attr", c_type), ... ]
  34. # getattr(ai_obj, e[0]).__class__ == float
  35. if isinstance(ai_obj, structs.Matrix4x4):
  36. if numpy:
  37. res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((4,4))
  38. #import pdb;pdb.set_trace()
  39. else:
  40. res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_]
  41. res = [res[i:i+4] for i in xrange(0,16,4)]
  42. elif isinstance(ai_obj, structs.Matrix3x3):
  43. if numpy:
  44. res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((3,3))
  45. else:
  46. res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_]
  47. res = [res[i:i+3] for i in xrange(0,9,3)]
  48. else:
  49. if numpy:
  50. res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_])
  51. else:
  52. res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_]
  53. return res
  54. # Returns unicode object for Python 2, and str object for Python 3.
  55. def _convert_assimp_string(assimp_string):
  56. if sys.version_info >= (3, 0):
  57. return str(assimp_string.data, errors='ignore')
  58. else:
  59. return unicode(assimp_string.data, errors='ignore')
  60. # It is faster and more correct to have an init function for each assimp class
  61. def _init_face(aiFace):
  62. aiFace.indices = [aiFace.mIndices[i] for i in range(aiFace.mNumIndices)]
  63. assimp_struct_inits = { structs.Face : _init_face }
  64. def call_init(obj, caller = None):
  65. if helper.hasattr_silent(obj,'contents'): #pointer
  66. _init(obj.contents, obj, caller)
  67. else:
  68. _init(obj,parent=caller)
  69. def _is_init_type(obj):
  70. if obj and helper.hasattr_silent(obj,'contents'): #pointer
  71. return _is_init_type(obj[0])
  72. # null-pointer case that arises when we reach a mesh attribute
  73. # like mBitangents which use mNumVertices rather than mNumBitangents
  74. # so it breaks the 'is iterable' check.
  75. # Basically:
  76. # FIXME!
  77. elif not bool(obj):
  78. return False
  79. tname = obj.__class__.__name__
  80. return not (tname[:2] == 'c_' or tname == 'Structure' \
  81. or tname == 'POINTER') and not isinstance(obj, (int, str, bytes))
  82. def _init(self, target = None, parent = None):
  83. """
  84. Custom initialize() for C structs, adds safely accessible member functionality.
  85. :param target: set the object which receive the added methods. Useful when manipulating
  86. pointers, to skip the intermediate 'contents' deferencing.
  87. """
  88. if not target:
  89. target = self
  90. dirself = dir(self)
  91. for m in dirself:
  92. if m.startswith("_"):
  93. continue
  94. if m.startswith('mNum'):
  95. if 'm' + m[4:] in dirself:
  96. continue # will be processed later on
  97. else:
  98. name = m[1:].lower()
  99. obj = getattr(self, m)
  100. setattr(target, name, obj)
  101. continue
  102. if m == 'mName':
  103. target.name = str(_convert_assimp_string(self.mName))
  104. target.__class__.__repr__ = lambda x: str(x.__class__) + "(" + getattr(x, 'name','') + ")"
  105. target.__class__.__str__ = lambda x: getattr(x, 'name', '')
  106. continue
  107. name = m[1:].lower()
  108. obj = getattr(self, m)
  109. # Create tuples
  110. if isinstance(obj, structs.assimp_structs_as_tuple):
  111. setattr(target, name, make_tuple(obj))
  112. logger.debug(str(self) + ": Added array " + str(getattr(target, name)) + " as self." + name.lower())
  113. continue
  114. if m.startswith('m') and len(m) > 1 and m[1].upper() == m[1]:
  115. if name == "parent":
  116. setattr(target, name, parent)
  117. logger.debug("Added a parent as self." + name)
  118. continue
  119. if helper.hasattr_silent(self, 'mNum' + m[1:]):
  120. length = getattr(self, 'mNum' + m[1:])
  121. # -> special case: properties are
  122. # stored as a dict.
  123. if m == 'mProperties':
  124. setattr(target, name, _get_properties(obj, length))
  125. continue
  126. if not length: # empty!
  127. setattr(target, name, [])
  128. logger.debug(str(self) + ": " + name + " is an empty list.")
  129. continue
  130. try:
  131. if obj._type_ in structs.assimp_structs_as_tuple:
  132. if numpy:
  133. setattr(target, name, numpy.array([make_tuple(obj[i]) for i in range(length)], dtype=numpy.float32))
  134. logger.debug(str(self) + ": Added an array of numpy arrays (type "+ str(type(obj)) + ") as self." + name)
  135. else:
  136. setattr(target, name, [make_tuple(obj[i]) for i in range(length)])
  137. logger.debug(str(self) + ": Added a list of lists (type "+ str(type(obj)) + ") as self." + name)
  138. else:
  139. setattr(target, name, [obj[i] for i in range(length)]) #TODO: maybe not necessary to recreate an array?
  140. logger.debug(str(self) + ": Added list of " + str(obj) + " " + name + " as self." + name + " (type: " + str(type(obj)) + ")")
  141. # initialize array elements
  142. try:
  143. init = assimp_struct_inits[type(obj[0])]
  144. except KeyError:
  145. if _is_init_type(obj[0]):
  146. for e in getattr(target, name):
  147. call_init(e, target)
  148. else:
  149. for e in getattr(target, name):
  150. init(e)
  151. except IndexError:
  152. logger.error("in " + str(self) +" : mismatch between mNum" + name + " and the actual amount of data in m" + name + ". This may be due to version mismatch between libassimp and pyassimp. Quitting now.")
  153. sys.exit(1)
  154. except ValueError as e:
  155. logger.error("In " + str(self) + "->" + name + ": " + str(e) + ". Quitting now.")
  156. if "setting an array element with a sequence" in str(e):
  157. logger.error("Note that pyassimp does not currently "
  158. "support meshes with mixed triangles "
  159. "and quads. Try to load your mesh with"
  160. " a post-processing to triangulate your"
  161. " faces.")
  162. raise e
  163. else: # starts with 'm' but not iterable
  164. setattr(target, name, obj)
  165. logger.debug("Added " + name + " as self." + name + " (type: " + str(type(obj)) + ")")
  166. if _is_init_type(obj):
  167. call_init(obj, target)
  168. if isinstance(self, structs.Mesh):
  169. _finalize_mesh(self, target)
  170. if isinstance(self, structs.Texture):
  171. _finalize_texture(self, target)
  172. if isinstance(self, structs.Metadata):
  173. _finalize_metadata(self, target)
  174. return self
  175. def pythonize_assimp(type, obj, scene):
  176. """ This method modify the Assimp data structures
  177. to make them easier to work with in Python.
  178. Supported operations:
  179. - MESH: replace a list of mesh IDs by reference to these meshes
  180. - ADDTRANSFORMATION: add a reference to an object's transformation taken from their associated node.
  181. :param type: the type of modification to operate (cf above)
  182. :param obj: the input object to modify
  183. :param scene: a reference to the whole scene
  184. """
  185. if type == "MESH":
  186. meshes = []
  187. for i in obj:
  188. meshes.append(scene.meshes[i])
  189. return meshes
  190. if type == "ADDTRANSFORMATION":
  191. def getnode(node, name):
  192. if node.name == name: return node
  193. for child in node.children:
  194. n = getnode(child, name)
  195. if n: return n
  196. node = getnode(scene.rootnode, obj.name)
  197. if not node:
  198. raise AssimpError("Object " + str(obj) + " has no associated node!")
  199. setattr(obj, "transformation", node.transformation)
  200. def recur_pythonize(node, scene):
  201. '''
  202. Recursively call pythonize_assimp on
  203. nodes tree to apply several post-processing to
  204. pythonize the assimp datastructures.
  205. '''
  206. node.meshes = pythonize_assimp("MESH", node.meshes, scene)
  207. for mesh in node.meshes:
  208. mesh.material = scene.materials[mesh.materialindex]
  209. for cam in scene.cameras:
  210. pythonize_assimp("ADDTRANSFORMATION", cam, scene)
  211. for c in node.children:
  212. recur_pythonize(c, scene)
  213. def load(filename,
  214. file_type = None,
  215. processing = postprocess.aiProcess_Triangulate):
  216. '''
  217. Load a model into a scene. On failure throws AssimpError.
  218. Arguments
  219. ---------
  220. filename: Either a filename or a file object to load model from.
  221. If a file object is passed, file_type MUST be specified
  222. Otherwise Assimp has no idea which importer to use.
  223. This is named 'filename' so as to not break legacy code.
  224. processing: assimp postprocessing parameters. Verbose keywords are imported
  225. from postprocessing, and the parameters can be combined bitwise to
  226. generate the final processing value. Note that the default value will
  227. triangulate quad faces. Example of generating other possible values:
  228. processing = (pyassimp.postprocess.aiProcess_Triangulate |
  229. pyassimp.postprocess.aiProcess_OptimizeMeshes)
  230. file_type: string of file extension, such as 'stl'
  231. Returns
  232. ---------
  233. Scene object with model data
  234. '''
  235. if hasattr(filename, 'read'):
  236. # This is the case where a file object has been passed to load.
  237. # It is calling the following function:
  238. # const aiScene* aiImportFileFromMemory(const char* pBuffer,
  239. # unsigned int pLength,
  240. # unsigned int pFlags,
  241. # const char* pHint)
  242. if file_type is None:
  243. raise AssimpError('File type must be specified when passing file objects!')
  244. data = filename.read()
  245. model = _assimp_lib.load_mem(data,
  246. len(data),
  247. processing,
  248. file_type)
  249. else:
  250. # a filename string has been passed
  251. model = _assimp_lib.load(filename.encode(sys.getfilesystemencoding()), processing)
  252. if not model:
  253. raise AssimpError('Could not import file!')
  254. scene = _init(model.contents)
  255. recur_pythonize(scene.rootnode, scene)
  256. return scene
  257. def export(scene,
  258. filename,
  259. file_type = None,
  260. processing = postprocess.aiProcess_Triangulate):
  261. '''
  262. Export a scene. On failure throws AssimpError.
  263. Arguments
  264. ---------
  265. scene: scene to export.
  266. filename: Filename that the scene should be exported to.
  267. file_type: string of file exporter to use. For example "collada".
  268. processing: assimp postprocessing parameters. Verbose keywords are imported
  269. from postprocessing, and the parameters can be combined bitwise to
  270. generate the final processing value. Note that the default value will
  271. triangulate quad faces. Example of generating other possible values:
  272. processing = (pyassimp.postprocess.aiProcess_Triangulate |
  273. pyassimp.postprocess.aiProcess_OptimizeMeshes)
  274. '''
  275. exportStatus = _assimp_lib.export(ctypes.pointer(scene), file_type.encode("ascii"), filename.encode(sys.getfilesystemencoding()), processing)
  276. if exportStatus != 0:
  277. raise AssimpError('Could not export scene!')
  278. def export_blob(scene,
  279. file_type = None,
  280. processing = postprocess.aiProcess_Triangulate):
  281. '''
  282. Export a scene and return a blob in the correct format. On failure throws AssimpError.
  283. Arguments
  284. ---------
  285. scene: scene to export.
  286. file_type: string of file exporter to use. For example "collada".
  287. processing: assimp postprocessing parameters. Verbose keywords are imported
  288. from postprocessing, and the parameters can be combined bitwise to
  289. generate the final processing value. Note that the default value will
  290. triangulate quad faces. Example of generating other possible values:
  291. processing = (pyassimp.postprocess.aiProcess_Triangulate |
  292. pyassimp.postprocess.aiProcess_OptimizeMeshes)
  293. Returns
  294. ---------
  295. Pointer to structs.ExportDataBlob
  296. '''
  297. exportBlobPtr = _assimp_lib.export_blob(ctypes.pointer(scene), file_type.encode("ascii"), processing)
  298. if exportBlobPtr == 0:
  299. raise AssimpError('Could not export scene to blob!')
  300. return exportBlobPtr
  301. def release(scene):
  302. _assimp_lib.release(ctypes.pointer(scene))
  303. def _finalize_texture(tex, target):
  304. setattr(target, "achformathint", tex.achFormatHint)
  305. if numpy:
  306. data = numpy.array([make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)])
  307. else:
  308. data = [make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)]
  309. setattr(target, "data", data)
  310. def _finalize_mesh(mesh, target):
  311. """ Building of meshes is a bit specific.
  312. We override here the various datasets that can
  313. not be process as regular fields.
  314. For instance, the length of the normals array is
  315. mNumVertices (no mNumNormals is available)
  316. """
  317. nb_vertices = getattr(mesh, "mNumVertices")
  318. def fill(name):
  319. mAttr = getattr(mesh, name)
  320. if numpy:
  321. if mAttr:
  322. data = numpy.array([make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)], dtype=numpy.float32)
  323. setattr(target, name[1:].lower(), data)
  324. else:
  325. setattr(target, name[1:].lower(), numpy.array([], dtype="float32"))
  326. else:
  327. if mAttr:
  328. data = [make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)]
  329. setattr(target, name[1:].lower(), data)
  330. else:
  331. setattr(target, name[1:].lower(), [])
  332. def fillarray(name):
  333. mAttr = getattr(mesh, name)
  334. data = []
  335. for index, mSubAttr in enumerate(mAttr):
  336. if mSubAttr:
  337. data.append([make_tuple(getattr(mesh, name)[index][i]) for i in range(nb_vertices)])
  338. if numpy:
  339. setattr(target, name[1:].lower(), numpy.array(data, dtype=numpy.float32))
  340. else:
  341. setattr(target, name[1:].lower(), data)
  342. fill("mNormals")
  343. fill("mTangents")
  344. fill("mBitangents")
  345. fillarray("mColors")
  346. fillarray("mTextureCoords")
  347. # prepare faces
  348. if numpy:
  349. faces = numpy.array([f.indices for f in target.faces], dtype=numpy.int32)
  350. else:
  351. faces = [f.indices for f in target.faces]
  352. setattr(target, 'faces', faces)
  353. def _init_metadata_entry(entry):
  354. entry.type = entry.mType
  355. if entry.type == structs.MetadataEntry.AI_BOOL:
  356. entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_bool)).contents.value
  357. elif entry.type == structs.MetadataEntry.AI_INT32:
  358. entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_int32)).contents.value
  359. elif entry.type == structs.MetadataEntry.AI_UINT64:
  360. entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_uint64)).contents.value
  361. elif entry.type == structs.MetadataEntry.AI_FLOAT:
  362. entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_float)).contents.value
  363. elif entry.type == structs.MetadataEntry.AI_DOUBLE:
  364. entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_double)).contents.value
  365. elif entry.type == structs.MetadataEntry.AI_AISTRING:
  366. assimp_string = ctypes.cast(entry.mData, ctypes.POINTER(structs.String)).contents
  367. entry.data = _convert_assimp_string(assimp_string)
  368. elif entry.type == structs.MetadataEntry.AI_AIVECTOR3D:
  369. assimp_vector = ctypes.cast(entry.mData, ctypes.POINTER(structs.Vector3D)).contents
  370. entry.data = make_tuple(assimp_vector)
  371. return entry
  372. def _finalize_metadata(metadata, target):
  373. """ Building the metadata object is a bit specific.
  374. Firstly, there are two separate arrays: one with metadata keys and one
  375. with metadata values, and there are no corresponding mNum* attributes,
  376. so the C arrays are not converted to Python arrays using the generic
  377. code in the _init function.
  378. Secondly, a metadata entry value has to be cast according to declared
  379. metadata entry type.
  380. """
  381. length = metadata.mNumProperties
  382. setattr(target, 'keys', [str(_convert_assimp_string(metadata.mKeys[i])) for i in range(length)])
  383. setattr(target, 'values', [_init_metadata_entry(metadata.mValues[i]) for i in range(length)])
  384. class PropertyGetter(dict):
  385. def __getitem__(self, key):
  386. semantic = 0
  387. if isinstance(key, tuple):
  388. key, semantic = key
  389. return dict.__getitem__(self, (key, semantic))
  390. def keys(self):
  391. for k in dict.keys(self):
  392. yield k[0]
  393. def __iter__(self):
  394. return self.keys()
  395. def items(self):
  396. for k, v in dict.items(self):
  397. yield k[0], v
  398. def _get_properties(properties, length):
  399. """
  400. Convenience Function to get the material properties as a dict
  401. and values in a python format.
  402. """
  403. result = {}
  404. #read all properties
  405. for p in [properties[i] for i in range(length)]:
  406. #the name
  407. p = p.contents
  408. key = str(_convert_assimp_string(p.mKey))
  409. key = (key.split('.')[1], p.mSemantic)
  410. #the data
  411. if p.mType == 1:
  412. arr = ctypes.cast(p.mData,
  413. ctypes.POINTER(ctypes.c_float * int(p.mDataLength/ctypes.sizeof(ctypes.c_float)))
  414. ).contents
  415. value = [x for x in arr]
  416. elif p.mType == 3: #string can't be an array
  417. value = _convert_assimp_string(ctypes.cast(p.mData, ctypes.POINTER(structs.MaterialPropertyString)).contents)
  418. elif p.mType == 4:
  419. arr = ctypes.cast(p.mData,
  420. ctypes.POINTER(ctypes.c_int * int(p.mDataLength/ctypes.sizeof(ctypes.c_int)))
  421. ).contents
  422. value = [x for x in arr]
  423. else:
  424. value = p.mData[:p.mDataLength]
  425. if len(value) == 1:
  426. [value] = value
  427. result[key] = value
  428. return PropertyGetter(result)
  429. def decompose_matrix(matrix):
  430. if not isinstance(matrix, structs.Matrix4x4):
  431. raise AssimpError("pyassimp.decompose_matrix failed: Not a Matrix4x4!")
  432. scaling = structs.Vector3D()
  433. rotation = structs.Quaternion()
  434. position = structs.Vector3D()
  435. _assimp_lib.dll.aiDecomposeMatrix(ctypes.pointer(matrix),
  436. ctypes.byref(scaling),
  437. ctypes.byref(rotation),
  438. ctypes.byref(position))
  439. return scaling._init(), rotation._init(), position._init()