geometry.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import os
  2. from .. import constants
  3. from . import base_classes, io, logger, api
  4. FORMAT_VERSION = 3
  5. class Geometry(base_classes.BaseNode):
  6. def __init__(self, node, parent=None):
  7. logger.debug('Geometry().__init__(%s)', node)
  8. #@TODO: maybe better to have `three` constants for
  9. # strings that are specific to `three` properties
  10. geo_type = constants.GEOMETRY.title()
  11. if parent.options.get(constants.GEOMETRY_TYPE):
  12. opt_type = parent.options[constants.GEOMETRY_TYPE]
  13. if opt_type == constants.BUFFER_GEOMETRY:
  14. geo_type = constants.BUFFER_GEOMETRY
  15. elif opt_type != constants.GEOMETRY:
  16. logger.error('Unknown geometry type %s', opt_type)
  17. logger.info('Setting %s to "%s"', node, geo_type)
  18. self._defaults[constants.TYPE] = geo_type
  19. base_classes.BaseNode.__init__(self, node, parent=parent,
  20. type=geo_type)
  21. @property
  22. def animation_filename(self):
  23. compression = self.options.get(constants.COMPRESSION)
  24. if compression in (None, constants.NONE):
  25. ext = constants.JSON
  26. elif compression == constants.MSGPACK:
  27. ext = constants.PACK
  28. for key in (constants.MORPH_TARGETS, constants.ANIMATION):
  29. try:
  30. self[key]
  31. break
  32. except KeyError:
  33. pass
  34. else:
  35. logger.info('%s has no animation data', self.node)
  36. return
  37. return '%s.%s.%s' % (self.node, key, ext)
  38. @property
  39. def face_count(self):
  40. try:
  41. faces = self[constants.FACES]
  42. except KeyError:
  43. logger.debug('No parsed faces found')
  44. return 0
  45. length = len(faces)
  46. offset = 0
  47. bitset = lambda x,y: x & ( 1 << y )
  48. face_count = 0
  49. while offset < length:
  50. bit = faces[offset]
  51. offset += 1
  52. face_count += 1
  53. is_quad = bitset(bit, constants.MASK[constants.QUAD])
  54. has_material = bitset(bit, constants.MASK[constants.MATERIALS])
  55. has_uv = bitset(bit, constants.MASK[constants.UVS])
  56. has_normal = bitset(bit, constants.MASK[constants.NORMALS])
  57. has_color = bitset(bit, constants.MASK[constants.COLORS])
  58. vector = 4 if is_quad else 3
  59. offset += vector
  60. if has_material:
  61. offset += 1
  62. if has_uv:
  63. offset += vector
  64. if has_normal:
  65. offset += vector
  66. if has_color:
  67. offset += vector
  68. return face_count
  69. @property
  70. def metadata(self):
  71. metadata = {
  72. constants.GENERATOR: constants.THREE,
  73. constants.VERSION: FORMAT_VERSION
  74. }
  75. if self[constants.TYPE] == constants.GEOMETRY.title():
  76. self.__geometry_metadata(metadata)
  77. else:
  78. self.__buffer_geometry_metadata(metadata)
  79. return metadata
  80. def copy(self, scene=True):
  81. logger.debug('Geometry().copy(scene=%s)', scene)
  82. dispatch = {
  83. True: self._scene_format,
  84. False: self._geometry_format
  85. }
  86. data = dispatch[scene]()
  87. try:
  88. data[constants.MATERIALS] = self[constants.MATERIALS].copy()
  89. except KeyError:
  90. logger.debug('No materials to copy')
  91. pass
  92. return data
  93. def copy_textures(self):
  94. logger.debug('Geometry().copy_textures()')
  95. if self.options.get(constants.COPY_TEXTURES):
  96. texture_registration = self.register_textures()
  97. if texture_registration:
  98. logger.info('%s has registered textures', self.node)
  99. io.copy_registered_textures(
  100. os.path.dirname(self.scene.filepath),
  101. texture_registration)
  102. def parse(self):
  103. logger.debug('Geometry().parse()')
  104. if self[constants.TYPE] == constants.GEOMETRY.title():
  105. logger.info('Parsing Geometry format')
  106. self.__parse_geometry()
  107. else:
  108. logger.info('Parsing BufferGeometry format')
  109. self.__parse_buffer_geometry()
  110. def register_textures(self):
  111. logger.debug('Geometry().register_textures()')
  112. return api.mesh.texture_registration(self.node)
  113. def write(self, filepath=None):
  114. logger.debug('Geometry().write(filepath=%s)', filepath)
  115. filepath = filepath or self.scene.filepath
  116. io.dump(filepath, self.copy(scene=False),
  117. options=self.scene.options)
  118. if self.options.get(constants.MAPS):
  119. logger.info('Copying textures for %s', self.node)
  120. self.copy_textures()
  121. def write_animation(self, filepath):
  122. logger.debug('Geometry().write_animation(%s)', filepath)
  123. for key in (constants.MORPH_TARGETS, constants.ANIMATION):
  124. try:
  125. data = self[key]
  126. break
  127. except KeyError:
  128. pass
  129. else:
  130. logger.info('%s has no animation data', self.node)
  131. return
  132. filepath = os.path.join(filepath, self.animation_filename)
  133. if filepath:
  134. logger.info('Dumping animation data to %s', filepath)
  135. io.dump(filepath, data, options=self.scene.options)
  136. return filepath
  137. else:
  138. logger.warning('Could not determine a filepath for '\
  139. 'animation data. Nothing written to disk.')
  140. def _component_data(self):
  141. logger.debug('Geometry()._component_data()')
  142. if self[constants.TYPE] != constants.GEOMETRY.title():
  143. return self[constants.ATTRIBUTES]
  144. components = [constants.VERTICES, constants.FACES,
  145. constants.UVS, constants.COLORS, constants.NORMALS,
  146. constants.BONES, constants.SKIN_WEIGHTS,
  147. constants.SKIN_INDICES, constants.NAME]
  148. data = {}
  149. anim_components = [constants.MORPH_TARGETS, constants.ANIMATION]
  150. if self.options.get(constants.EMBED_ANIMATION):
  151. components.extend(anim_components)
  152. else:
  153. for component in anim_components:
  154. try:
  155. self[component]
  156. except KeyError:
  157. pass
  158. else:
  159. data[component] = os.path.basename(
  160. self.animation_filename)
  161. else:
  162. logger.info('No animation data found for %s', self.node)
  163. for component in components:
  164. try:
  165. data[component] = self[component]
  166. except KeyError:
  167. logger.debug('Component %s not found', component)
  168. pass
  169. return data
  170. def _geometry_format(self):
  171. data = self._component_data()
  172. if self[constants.TYPE] != constants.GEOMETRY.title():
  173. data = {constants.ATTRIBUTES: data}
  174. data[constants.METADATA] = {
  175. constants.TYPE: self[constants.TYPE]
  176. }
  177. data[constants.METADATA].update(self.metadata)
  178. return data
  179. def __buffer_geometry_metadata(self, metadata):
  180. for key, value in self[constants.ATTRIBUTES].items():
  181. size = value[constants.ITEM_SIZE]
  182. array = value[constants.ARRAY]
  183. metadata[key] = len(array)/size
  184. def __geometry_metadata(self, metadata):
  185. skip = (constants.TYPE, constants.FACES, constants.UUID,
  186. constants.ANIMATION, constants.SKIN_INDICES,
  187. constants.SKIN_WEIGHTS, constants.NAME)
  188. vectors = (constants.VERTICES, constants.NORMALS)
  189. for key in self.keys():
  190. if key in vectors:
  191. try:
  192. metadata[key] = int(len(self[key])/3)
  193. except KeyError:
  194. pass
  195. continue
  196. if key in skip: continue
  197. metadata[key] = len(self[key])
  198. faces = self.face_count
  199. if faces > 0:
  200. metadata[constants.FACES] = faces
  201. def _scene_format(self):
  202. data = {
  203. constants.UUID: self[constants.UUID],
  204. constants.TYPE: self[constants.TYPE]
  205. }
  206. component_data = self._component_data()
  207. if self[constants.TYPE] == constants.GEOMETRY.title():
  208. data[constants.DATA] = component_data
  209. data[constants.DATA].update({
  210. constants.METADATA: self.metadata
  211. })
  212. else:
  213. if self.options[constants.EMBED_GEOMETRY]:
  214. data[constants.DATA] = {
  215. constants.ATTRIBUTES: component_data
  216. }
  217. else:
  218. data[constants.ATTRIBUTES] = component_data
  219. data.update({constants.METADATA: self.metadata})
  220. data[constants.NAME] = self[constants.NAME]
  221. return data
  222. def __parse_buffer_geometry(self):
  223. self[constants.ATTRIBUTES] = {}
  224. options_vertices = self.options.get(constants.VERTICES)
  225. option_normals = self.options.get(constants.NORMALS)
  226. option_uvs = self.options.get(constants.UVS)
  227. dispatch = (
  228. (constants.POSITION, options_vertices,
  229. api.mesh.buffer_position, 3),
  230. (constants.UV, option_uvs, api.mesh.buffer_uv, 2),
  231. (constants.NORMAL, option_normals,
  232. api.mesh.buffer_normal, 3)
  233. )
  234. for key, option, func, size in dispatch:
  235. if not option:
  236. continue
  237. array = func(self.node, self.options)
  238. if not array:
  239. logger.warning('No array could be made for %s', key)
  240. continue
  241. self[constants.ATTRIBUTES][key] = {
  242. constants.ITEM_SIZE: size,
  243. constants.TYPE: constants.FLOAT_32,
  244. constants.ARRAY: array
  245. }
  246. def __parse_geometry(self):
  247. if self.options.get(constants.VERTICES):
  248. logger.info('Parsing %s', constants.VERTICES)
  249. self[constants.VERTICES] = api.mesh.vertices(
  250. self.node, self.options)
  251. if self.options.get(constants.FACES):
  252. logger.info('Parsing %s', constants.FACES)
  253. self[constants.FACES] = api.mesh.faces(
  254. self.node, self.options)
  255. if self.options.get(constants.NORMALS):
  256. logger.info('Parsing %s', constants.NORMALS)
  257. self[constants.NORMALS] = api.mesh.normals(
  258. self.node, self.options)
  259. if self.options.get(constants.COLORS):
  260. logger.info('Parsing %s', constants.COLORS)
  261. self[constants.COLORS] = api.mesh.vertex_colors(self.node)
  262. if self.options.get(constants.FACE_MATERIALS):
  263. logger.info('Parsing %s', constants.FACE_MATERIALS)
  264. self[constants.MATERIALS] = api.mesh.materials(
  265. self.node, self.options)
  266. if self.options.get(constants.UVS):
  267. logger.info('Parsing %s', constants.UVS)
  268. self[constants.UVS] = api.mesh.uvs(self.node, self.options)
  269. if self.options.get(constants.ANIMATION):
  270. logger.info('Parsing %s', constants.ANIMATION)
  271. self[constants.ANIMATION] = api.mesh.animation(
  272. self.node, self.options)
  273. if self.options.get(constants.BONES):
  274. logger.info('Parsing %s', constants.BONES)
  275. self[constants.BONES] = api.mesh.bones(self.node)
  276. if self.options.get(constants.SKINNING):
  277. logger.info('Parsing %s', constants.SKINNING)
  278. self[constants.SKIN_INDICES] = api.mesh.skin_indices(self.node)
  279. self[constants.SKIN_WEIGHTS] = api.mesh.skin_weights(self.node)
  280. if self.options.get(constants.MORPH_TARGETS):
  281. logger.info('Parsing %s', constants.MORPH_TARGETS)
  282. self[constants.MORPH_TARGETS] = api.mesh.morph_targets(
  283. self.node, self.options)