geometry.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 (Default = True)
  91. :type scene: bool
  92. :rtype: dict
  93. """
  94. logger.debug("Geometry().copy(scene=%s)", scene)
  95. dispatch = {
  96. True: self._scene_format,
  97. False: self._geometry_format
  98. }
  99. data = dispatch[scene]()
  100. try:
  101. data[constants.MATERIALS] = self[constants.MATERIALS].copy()
  102. except KeyError:
  103. logger.debug("No materials to copy")
  104. return data
  105. def copy_textures(self):
  106. """Copy the textures to the destination directory."""
  107. logger.debug("Geometry().copy_textures()")
  108. if self.options.get(constants.COPY_TEXTURES):
  109. texture_registration = self.register_textures()
  110. if texture_registration:
  111. logger.info("%s has registered textures", self.node)
  112. io.copy_registered_textures(
  113. os.path.dirname(self.scene.filepath),
  114. texture_registration)
  115. def parse(self):
  116. """Parse the current node"""
  117. logger.debug("Geometry().parse()")
  118. if self[constants.TYPE] == constants.GEOMETRY.title():
  119. logger.info("Parsing Geometry format")
  120. self._parse_geometry()
  121. else:
  122. logger.info("Parsing BufferGeometry format")
  123. self._parse_buffer_geometry()
  124. def register_textures(self):
  125. """Obtain a texture registration object.
  126. :rtype: dict
  127. """
  128. logger.debug("Geometry().register_textures()")
  129. return api.mesh.texture_registration(self.node)
  130. def write(self, filepath=None):
  131. """Write the geometry definitions to disk. Uses the
  132. desitnation path of the scene.
  133. :param filepath: optional output file path (Default=None)
  134. :type filepath: str
  135. """
  136. logger.debug("Geometry().write(filepath=%s)", filepath)
  137. filepath = filepath or self.scene.filepath
  138. io.dump(filepath, self.copy(scene=False),
  139. options=self.scene.options)
  140. if self.options.get(constants.MAPS):
  141. logger.info("Copying textures for %s", self.node)
  142. self.copy_textures()
  143. def write_animation(self, filepath):
  144. """Write the animation definitions to a separate file
  145. on disk. This helps optimize the geometry file size.
  146. :param filepath: destination path
  147. :type filepath: str
  148. """
  149. logger.debug("Geometry().write_animation(%s)", filepath)
  150. for key in (constants.MORPH_TARGETS, constants.ANIMATION):
  151. try:
  152. data = self[key]
  153. break
  154. except KeyError:
  155. pass
  156. else:
  157. logger.info("%s has no animation data", self.node)
  158. return
  159. filepath = os.path.join(filepath, self.animation_filename)
  160. if filepath:
  161. logger.info("Dumping animation data to %s", filepath)
  162. io.dump(filepath, data, options=self.scene.options)
  163. return filepath
  164. else:
  165. logger.warning("Could not determine a filepath for "\
  166. "animation data. Nothing written to disk.")
  167. def _component_data(self):
  168. """Query the component data only
  169. :rtype: dict
  170. """
  171. logger.debug("Geometry()._component_data()")
  172. if self[constants.TYPE] != constants.GEOMETRY.title():
  173. return self[constants.ATTRIBUTES]
  174. components = [constants.VERTICES, constants.FACES,
  175. constants.UVS, constants.COLORS,
  176. constants.NORMALS, constants.BONES,
  177. constants.SKIN_WEIGHTS,
  178. constants.SKIN_INDICES, constants.NAME,
  179. constants.INFLUENCES_PER_VERTEX]
  180. data = {}
  181. anim_components = [constants.MORPH_TARGETS, constants.ANIMATION]
  182. if self.options.get(constants.EMBED_ANIMATION):
  183. components.extend(anim_components)
  184. else:
  185. for component in anim_components:
  186. try:
  187. self[component]
  188. except KeyError:
  189. pass
  190. else:
  191. data[component] = os.path.basename(
  192. self.animation_filename)
  193. break
  194. else:
  195. logger.info("No animation data found for %s", self.node)
  196. for component in components:
  197. try:
  198. data[component] = self[component]
  199. except KeyError:
  200. logger.debug("Component %s not found", component)
  201. return data
  202. def _geometry_format(self):
  203. """Three.Geometry formatted definitions
  204. :rtype: dict
  205. """
  206. data = self._component_data()
  207. if self[constants.TYPE] != constants.GEOMETRY.title():
  208. data = {constants.ATTRIBUTES: data}
  209. data[constants.METADATA] = {
  210. constants.TYPE: self[constants.TYPE]
  211. }
  212. data[constants.METADATA].update(self.metadata)
  213. return data
  214. def _buffer_geometry_metadata(self, metadata):
  215. """Three.BufferGeometry metadata
  216. :rtype: dict
  217. """
  218. for key, value in self[constants.ATTRIBUTES].items():
  219. size = value[constants.ITEM_SIZE]
  220. array = value[constants.ARRAY]
  221. metadata[key] = len(array)/size
  222. def _geometry_metadata(self, metadata):
  223. """Three.Geometry metadat
  224. :rtype: dict
  225. """
  226. skip = (constants.TYPE, constants.FACES, constants.UUID,
  227. constants.ANIMATION, constants.SKIN_INDICES,
  228. constants.SKIN_WEIGHTS, constants.NAME,
  229. constants.INFLUENCES_PER_VERTEX)
  230. vectors = (constants.VERTICES, constants.NORMALS)
  231. for key in self.keys():
  232. if key in vectors:
  233. try:
  234. metadata[key] = int(len(self[key])/3)
  235. except KeyError:
  236. pass
  237. continue
  238. if key in skip: continue
  239. metadata[key] = len(self[key])
  240. faces = self.face_count
  241. if faces > 0:
  242. metadata[constants.FACES] = faces
  243. def _scene_format(self):
  244. """Format the output for Scene compatability
  245. :rtype: dict
  246. """
  247. data = {
  248. constants.UUID: self[constants.UUID],
  249. constants.TYPE: self[constants.TYPE]
  250. }
  251. component_data = self._component_data()
  252. if self[constants.TYPE] == constants.GEOMETRY.title():
  253. data[constants.DATA] = component_data
  254. data[constants.DATA].update({
  255. constants.METADATA: self.metadata
  256. })
  257. else:
  258. if self.options[constants.EMBED_GEOMETRY]:
  259. data[constants.DATA] = {
  260. constants.ATTRIBUTES: component_data
  261. }
  262. else:
  263. data[constants.ATTRIBUTES] = component_data
  264. data[constants.METADATA] = self.metadata
  265. data[constants.NAME] = self[constants.NAME]
  266. return data
  267. def _parse_buffer_geometry(self):
  268. """Parse the geometry to Three.BufferGeometry specs"""
  269. self[constants.ATTRIBUTES] = {}
  270. options_vertices = self.options.get(constants.VERTICES)
  271. option_normals = self.options.get(constants.NORMALS)
  272. option_uvs = self.options.get(constants.UVS)
  273. pos_tuple = (constants.POSITION, options_vertices,
  274. api.mesh.buffer_position, 3)
  275. uvs_tuple = (constants.UV, option_uvs,
  276. api.mesh.buffer_uv, 2)
  277. normals_tuple = (constants.NORMAL, option_normals,
  278. api.mesh.buffer_normal, 3)
  279. dispatch = (pos_tuple, uvs_tuple, normals_tuple)
  280. for key, option, func, size in dispatch:
  281. if not option:
  282. continue
  283. array = func(self.node, self.options) or []
  284. if not array:
  285. logger.warning("No array could be made for %s", key)
  286. continue
  287. self[constants.ATTRIBUTES][key] = {
  288. constants.ITEM_SIZE: size,
  289. constants.TYPE: constants.FLOAT_32,
  290. constants.ARRAY: array
  291. }
  292. def _parse_geometry(self):
  293. """Parse the geometry to Three.Geometry specs"""
  294. if self.options.get(constants.VERTICES):
  295. logger.info("Parsing %s", constants.VERTICES)
  296. self[constants.VERTICES] = api.mesh.vertices(
  297. self.node, self.options) or []
  298. if self.options.get(constants.NORMALS):
  299. logger.info("Parsing %s", constants.NORMALS)
  300. self[constants.NORMALS] = api.mesh.normals(
  301. self.node, self.options) or []
  302. if self.options.get(constants.COLORS):
  303. logger.info("Parsing %s", constants.COLORS)
  304. self[constants.COLORS] = api.mesh.vertex_colors(
  305. self.node) or []
  306. if self.options.get(constants.FACE_MATERIALS):
  307. logger.info("Parsing %s", constants.FACE_MATERIALS)
  308. self[constants.MATERIALS] = api.mesh.materials(
  309. self.node, self.options) or []
  310. if self.options.get(constants.UVS):
  311. logger.info("Parsing %s", constants.UVS)
  312. self[constants.UVS] = api.mesh.uvs(
  313. self.node, self.options) or []
  314. if self.options.get(constants.FACES):
  315. logger.info("Parsing %s", constants.FACES)
  316. self[constants.FACES] = api.mesh.faces(
  317. self.node, self.options) or []
  318. no_anim = (None, False, constants.OFF)
  319. if self.options.get(constants.ANIMATION) not in no_anim:
  320. logger.info("Parsing %s", constants.ANIMATION)
  321. self[constants.ANIMATION] = api.mesh.skeletal_animation(
  322. self.node, self.options) or []
  323. #@TODO: considering making bones data implied when
  324. # querying skinning data
  325. bone_map = {}
  326. if self.options.get(constants.BONES):
  327. logger.info("Parsing %s", constants.BONES)
  328. bones, bone_map = api.mesh.bones(self.node, self.options)
  329. self[constants.BONES] = bones
  330. if self.options.get(constants.SKINNING):
  331. logger.info("Parsing %s", constants.SKINNING)
  332. influences = self.options.get(
  333. constants.INFLUENCES_PER_VERTEX, 2)
  334. self[constants.INFLUENCES_PER_VERTEX] = influences
  335. self[constants.SKIN_INDICES] = api.mesh.skin_indices(
  336. self.node, bone_map, influences)
  337. self[constants.SKIN_WEIGHTS] = api.mesh.skin_weights(
  338. self.node, bone_map, influences)
  339. if self.options.get(constants.MORPH_TARGETS):
  340. logger.info("Parsing %s", constants.MORPH_TARGETS)
  341. self[constants.MORPH_TARGETS] = api.mesh.morph_targets(
  342. self.node, self.options)