geometry.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import os
  2. from .. import constants, logger
  3. from . import base_classes, io, api
  4. FORMAT_VERSION = 3
  5. class Geometry(base_classes.BaseNode):
  6. """Class that wraps a single mesh/geometry node."""
  7. def __init__(self, node, parent=None):
  8. logger.debug("Geometry().__init__(%s)", node)
  9. #@TODO: maybe better to have `three` constants for
  10. # strings that are specific to `three` properties
  11. geo_type = constants.GEOMETRY.title()
  12. if parent.options.get(constants.GEOMETRY_TYPE):
  13. opt_type = parent.options[constants.GEOMETRY_TYPE]
  14. if opt_type == constants.BUFFER_GEOMETRY:
  15. geo_type = constants.BUFFER_GEOMETRY
  16. elif opt_type != constants.GEOMETRY:
  17. logger.error("Unknown geometry type %s", opt_type)
  18. logger.info("Setting %s to '%s'", node, geo_type)
  19. self._defaults[constants.TYPE] = geo_type
  20. base_classes.BaseNode.__init__(self, node,
  21. parent=parent,
  22. type=geo_type)
  23. @property
  24. def animation_filename(self):
  25. """Calculate the file name for the animation file
  26. :return: base name for the file
  27. """
  28. compression = self.options.get(constants.COMPRESSION)
  29. if compression in (None, constants.NONE):
  30. ext = constants.JSON
  31. elif compression == constants.MSGPACK:
  32. ext = constants.PACK
  33. key = ''
  34. for key in (constants.MORPH_TARGETS, constants.ANIMATION):
  35. try:
  36. self[key]
  37. break
  38. except KeyError:
  39. pass
  40. else:
  41. logger.info("%s has no animation data", self.node)
  42. return
  43. return '%s.%s.%s' % (self.node, key, ext)
  44. @property
  45. def face_count(self):
  46. """Parse the bit masks of the `faces` array.
  47. :rtype: int
  48. """
  49. try:
  50. faces = self[constants.FACES]
  51. except KeyError:
  52. logger.debug("No parsed faces found")
  53. return 0
  54. length = len(faces)
  55. offset = 0
  56. bitset = lambda x, y: x & (1 << y)
  57. face_count = 0
  58. masks = (constants.MASK[constants.UVS],
  59. constants.MASK[constants.NORMALS],
  60. constants.MASK[constants.COLORS])
  61. while offset < length:
  62. bit = faces[offset]
  63. offset += 1
  64. face_count += 1
  65. is_quad = bitset(bit, constants.MASK[constants.QUAD])
  66. vector = 4 if is_quad else 3
  67. offset += vector
  68. if bitset(bit, constants.MASK[constants.MATERIALS]):
  69. offset += 1
  70. for mask in masks:
  71. if bitset(bit, mask):
  72. offset += vector
  73. return face_count
  74. @property
  75. def metadata(self):
  76. """Metadata for the current node.
  77. :rtype: dict
  78. """
  79. metadata = {
  80. constants.GENERATOR: constants.THREE,
  81. constants.VERSION: FORMAT_VERSION
  82. }
  83. if self[constants.TYPE] == constants.GEOMETRY.title():
  84. self._geometry_metadata(metadata)
  85. else:
  86. self._buffer_geometry_metadata(metadata)
  87. return metadata
  88. def copy(self, scene=True):
  89. """Copy the geometry definitions to a standard dictionary.
  90. :param scene: toggle for scene formatting
  91. (Default value = True)
  92. :type scene: bool
  93. :rtype: dict
  94. """
  95. logger.debug("Geometry().copy(scene=%s)", scene)
  96. dispatch = {
  97. True: self._scene_format,
  98. False: self._geometry_format
  99. }
  100. data = dispatch[scene]()
  101. try:
  102. data[constants.MATERIALS] = self[constants.MATERIALS].copy()
  103. except KeyError:
  104. logger.debug("No materials to copy")
  105. return data
  106. def copy_textures(self):
  107. """Copy the textures to the destination directory."""
  108. logger.debug("Geometry().copy_textures()")
  109. if self.options.get(constants.COPY_TEXTURES):
  110. texture_registration = self.register_textures()
  111. if texture_registration:
  112. logger.info("%s has registered textures", self.node)
  113. io.copy_registered_textures(
  114. os.path.dirname(self.scene.filepath),
  115. texture_registration)
  116. def parse(self):
  117. """Parse the current node"""
  118. logger.debug("Geometry().parse()")
  119. if self[constants.TYPE] == constants.GEOMETRY.title():
  120. logger.info("Parsing Geometry format")
  121. self._parse_geometry()
  122. else:
  123. logger.info("Parsing BufferGeometry format")
  124. self._parse_buffer_geometry()
  125. def register_textures(self):
  126. """Obtain a texture registration object.
  127. :rtype: dict
  128. """
  129. logger.debug("Geometry().register_textures()")
  130. return api.mesh.texture_registration(self.node)
  131. def write(self, filepath=None):
  132. """Write the geometry definitions to disk. Uses the
  133. desitnation path of the scene.
  134. :param filepath: optional output file path
  135. (Default value = None)
  136. :type filepath: str
  137. """
  138. logger.debug("Geometry().write(filepath=%s)", filepath)
  139. filepath = filepath or self.scene.filepath
  140. io.dump(filepath, self.copy(scene=False),
  141. options=self.scene.options)
  142. if self.options.get(constants.MAPS):
  143. logger.info("Copying textures for %s", self.node)
  144. self.copy_textures()
  145. def write_animation(self, filepath):
  146. """Write the animation definitions to a separate file
  147. on disk. This helps optimize the geometry file size.
  148. :param filepath: destination path
  149. :type filepath: str
  150. """
  151. logger.debug("Geometry().write_animation(%s)", filepath)
  152. for key in (constants.MORPH_TARGETS, constants.ANIMATION):
  153. try:
  154. data = self[key]
  155. break
  156. except KeyError:
  157. pass
  158. else:
  159. logger.info("%s has no animation data", self.node)
  160. return
  161. filepath = os.path.join(filepath, self.animation_filename)
  162. if filepath:
  163. logger.info("Dumping animation data to %s", filepath)
  164. io.dump(filepath, data, options=self.scene.options)
  165. return filepath
  166. else:
  167. logger.warning("Could not determine a filepath for "\
  168. "animation data. Nothing written to disk.")
  169. def _component_data(self):
  170. """Query the component data only
  171. :rtype: dict
  172. """
  173. logger.debug("Geometry()._component_data()")
  174. if self[constants.TYPE] != constants.GEOMETRY.title():
  175. return self[constants.ATTRIBUTES]
  176. components = [constants.VERTICES, constants.FACES,
  177. constants.UVS, constants.COLORS,
  178. constants.NORMALS, constants.BONES,
  179. constants.SKIN_WEIGHTS,
  180. constants.SKIN_INDICES, constants.NAME,
  181. constants.INFLUENCES_PER_VERTEX]
  182. data = {}
  183. anim_components = [constants.MORPH_TARGETS, constants.ANIMATION]
  184. if self.options.get(constants.EMBED_ANIMATION):
  185. components.extend(anim_components)
  186. else:
  187. for component in anim_components:
  188. try:
  189. self[component]
  190. except KeyError:
  191. pass
  192. else:
  193. data[component] = os.path.basename(
  194. self.animation_filename)
  195. break
  196. else:
  197. logger.info("No animation data found for %s", self.node)
  198. for component in components:
  199. try:
  200. data[component] = self[component]
  201. except KeyError:
  202. logger.debug("Component %s not found", component)
  203. return data
  204. def _geometry_format(self):
  205. """Three.Geometry formatted definitions
  206. :rtype: dict
  207. """
  208. data = self._component_data()
  209. if self[constants.TYPE] != constants.GEOMETRY.title():
  210. data = {constants.ATTRIBUTES: data}
  211. data[constants.METADATA] = {
  212. constants.TYPE: self[constants.TYPE]
  213. }
  214. data[constants.METADATA].update(self.metadata)
  215. return data
  216. def _buffer_geometry_metadata(self, metadata):
  217. """Three.BufferGeometry metadata
  218. :rtype: dict
  219. """
  220. for key, value in self[constants.ATTRIBUTES].items():
  221. size = value[constants.ITEM_SIZE]
  222. array = value[constants.ARRAY]
  223. metadata[key] = len(array)/size
  224. def _geometry_metadata(self, metadata):
  225. """Three.Geometry metadat
  226. :rtype: dict
  227. """
  228. skip = (constants.TYPE, constants.FACES, constants.UUID,
  229. constants.ANIMATION, constants.SKIN_INDICES,
  230. constants.SKIN_WEIGHTS, constants.NAME,
  231. constants.INFLUENCES_PER_VERTEX)
  232. vectors = (constants.VERTICES, constants.NORMALS)
  233. for key in self.keys():
  234. if key in vectors:
  235. try:
  236. metadata[key] = int(len(self[key])/3)
  237. except KeyError:
  238. pass
  239. continue
  240. if key in skip: continue
  241. metadata[key] = len(self[key])
  242. faces = self.face_count
  243. if faces > 0:
  244. metadata[constants.FACES] = faces
  245. def _scene_format(self):
  246. """Format the output for Scene compatability
  247. :rtype: dict
  248. """
  249. data = {
  250. constants.UUID: self[constants.UUID],
  251. constants.TYPE: self[constants.TYPE]
  252. }
  253. component_data = self._component_data()
  254. if self[constants.TYPE] == constants.GEOMETRY.title():
  255. data[constants.DATA] = component_data
  256. data[constants.DATA].update({
  257. constants.METADATA: self.metadata
  258. })
  259. else:
  260. if self.options[constants.EMBED_GEOMETRY]:
  261. data[constants.DATA] = {
  262. constants.ATTRIBUTES: component_data
  263. }
  264. else:
  265. data[constants.ATTRIBUTES] = component_data
  266. data[constants.METADATA] = self.metadata
  267. data[constants.NAME] = self[constants.NAME]
  268. return data
  269. def _parse_buffer_geometry(self):
  270. """Parse the geometry to Three.BufferGeometry specs"""
  271. self[constants.ATTRIBUTES] = {}
  272. options_vertices = self.options.get(constants.VERTICES)
  273. option_normals = self.options.get(constants.NORMALS)
  274. option_uvs = self.options.get(constants.UVS)
  275. pos_tuple = (constants.POSITION, options_vertices,
  276. api.mesh.buffer_position, 3)
  277. uvs_tuple = (constants.UV, option_uvs,
  278. api.mesh.buffer_uv, 2)
  279. normals_tuple = (constants.NORMAL, option_normals,
  280. api.mesh.buffer_normal, 3)
  281. dispatch = (pos_tuple, uvs_tuple, normals_tuple)
  282. for key, option, func, size in dispatch:
  283. if not option:
  284. continue
  285. array = func(self.node, self.options) or []
  286. if not array:
  287. logger.warning("No array could be made for %s", key)
  288. continue
  289. self[constants.ATTRIBUTES][key] = {
  290. constants.ITEM_SIZE: size,
  291. constants.TYPE: constants.FLOAT_32,
  292. constants.ARRAY: array
  293. }
  294. def _parse_geometry(self):
  295. """Parse the geometry to Three.Geometry specs"""
  296. if self.options.get(constants.VERTICES):
  297. logger.info("Parsing %s", constants.VERTICES)
  298. self[constants.VERTICES] = api.mesh.vertices(
  299. self.node, self.options) or []
  300. if self.options.get(constants.NORMALS):
  301. logger.info("Parsing %s", constants.NORMALS)
  302. self[constants.NORMALS] = api.mesh.normals(
  303. self.node, self.options) or []
  304. if self.options.get(constants.COLORS):
  305. logger.info("Parsing %s", constants.COLORS)
  306. self[constants.COLORS] = api.mesh.vertex_colors(
  307. self.node) or []
  308. if self.options.get(constants.FACE_MATERIALS):
  309. logger.info("Parsing %s", constants.FACE_MATERIALS)
  310. self[constants.MATERIALS] = api.mesh.materials(
  311. self.node, self.options) or []
  312. if self.options.get(constants.UVS):
  313. logger.info("Parsing %s", constants.UVS)
  314. self[constants.UVS] = api.mesh.uvs(
  315. self.node, self.options) or []
  316. if self.options.get(constants.FACES):
  317. logger.info("Parsing %s", constants.FACES)
  318. self[constants.FACES] = api.mesh.faces(
  319. self.node, self.options) or []
  320. no_anim = (None, False, constants.OFF)
  321. if self.options.get(constants.ANIMATION) not in no_anim:
  322. logger.info("Parsing %s", constants.ANIMATION)
  323. self[constants.ANIMATION] = api.mesh.skeletal_animation(
  324. self.node, self.options) or []
  325. #@TODO: considering making bones data implied when
  326. # querying skinning data
  327. bone_map = {}
  328. if self.options.get(constants.BONES):
  329. logger.info("Parsing %s", constants.BONES)
  330. bones, bone_map = api.mesh.bones(self.node, self.options)
  331. self[constants.BONES] = bones
  332. if self.options.get(constants.SKINNING):
  333. logger.info("Parsing %s", constants.SKINNING)
  334. influences = self.options.get(
  335. constants.INFLUENCES_PER_VERTEX, 2)
  336. self[constants.INFLUENCES_PER_VERTEX] = influences
  337. self[constants.SKIN_INDICES] = api.mesh.skin_indices(
  338. self.node, bone_map, influences)
  339. self[constants.SKIN_WEIGHTS] = api.mesh.skin_weights(
  340. self.node, bone_map, influences)
  341. if self.options.get(constants.MORPH_TARGETS):
  342. logger.info("Parsing %s", constants.MORPH_TARGETS)
  343. self[constants.MORPH_TARGETS] = api.mesh.morph_targets(
  344. self.node, self.options)