core.py 20 KB

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