scene.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import os
  2. from .. import constants, logger
  3. from . import (
  4. base_classes,
  5. texture,
  6. material,
  7. geometry,
  8. object as object_,
  9. utilities,
  10. io,
  11. api
  12. )
  13. class Scene(base_classes.BaseScene):
  14. """Class that handles the contruction of a Three scene"""
  15. _defaults = {
  16. constants.METADATA: constants.DEFAULT_METADATA.copy(),
  17. constants.GEOMETRIES: [],
  18. constants.MATERIALS: [],
  19. constants.IMAGES: [],
  20. constants.TEXTURES: []
  21. }
  22. def __init__(self, filepath, options=None):
  23. logger.debug("Scene().__init__(%s, %s)", filepath, options)
  24. base_classes.BaseScene.__init__(self, filepath, options or {})
  25. source_file = api.scene_name()
  26. if source_file:
  27. self[constants.METADATA][constants.SOURCE_FILE] = source_file
  28. @property
  29. def valid_types(self):
  30. """
  31. :return: list of valid node types
  32. """
  33. valid_types = [api.constants.MESH]
  34. if self.options.get(constants.CAMERAS):
  35. logger.info("Adding cameras to valid object types")
  36. valid_types.append(api.constants.CAMERA)
  37. if self.options.get(constants.LIGHTS):
  38. logger.info("Adding lights to valid object types")
  39. valid_types.append(api.constants.LAMP)
  40. return valid_types
  41. def geometry(self, value):
  42. """Find a geometry node that matches either a name
  43. or uuid value.
  44. :param value: name or uuid
  45. :type value: str
  46. """
  47. logger.debug("Scene().geometry(%s)", value)
  48. return _find_node(value, self[constants.GEOMETRIES])
  49. def image(self, value):
  50. """Find a image node that matches either a name
  51. or uuid value.
  52. :param value: name or uuid
  53. :type value: str
  54. """
  55. logger.debug("Scene().image%s)", value)
  56. return _find_node(value, self[constants.IMAGES])
  57. def material(self, value):
  58. """Find a material node that matches either a name
  59. or uuid value.
  60. :param value: name or uuid
  61. :type value: str
  62. """
  63. logger.debug("Scene().material(%s)", value)
  64. return _find_node(value, self[constants.MATERIALS])
  65. def parse(self):
  66. """Execute the parsing of the scene"""
  67. logger.debug("Scene().parse()")
  68. if self.options.get(constants.MAPS):
  69. self._parse_textures()
  70. if self.options.get(constants.MATERIALS):
  71. self._parse_materials()
  72. self._parse_geometries()
  73. self._parse_objects()
  74. def texture(self, value):
  75. """Find a texture node that matches either a name
  76. or uuid value.
  77. :param value: name or uuid
  78. :type value: str
  79. """
  80. logger.debug("Scene().texture(%s)", value)
  81. return _find_node(value, self[constants.TEXTURES])
  82. def write(self):
  83. """Write the parsed scene to disk."""
  84. logger.debug("Scene().write()")
  85. data = {}
  86. embed_anim = self.options.get(constants.EMBED_ANIMATION, True)
  87. embed = self.options.get(constants.EMBED_GEOMETRY, True)
  88. compression = self.options.get(constants.COMPRESSION)
  89. extension = constants.EXTENSIONS.get(
  90. compression,
  91. constants.EXTENSIONS[constants.JSON])
  92. export_dir = os.path.dirname(self.filepath)
  93. for key, value in self.items():
  94. if key == constants.GEOMETRIES:
  95. geometries = []
  96. for geom in value:
  97. if not embed_anim:
  98. geom.write_animation(export_dir)
  99. geom_data = geom.copy()
  100. if embed:
  101. geometries.append(geom_data)
  102. continue
  103. geo_type = geom_data[constants.TYPE].lower()
  104. if geo_type == constants.GEOMETRY.lower():
  105. geom_data.pop(constants.DATA)
  106. elif geo_type == constants.BUFFER_GEOMETRY.lower():
  107. geom_data.pop(constants.ATTRIBUTES)
  108. geom_data.pop(constants.METADATA)
  109. url = 'geometry.%s%s' % (geom.node, extension)
  110. geometry_file = os.path.join(export_dir, url)
  111. geom.write(filepath=geometry_file)
  112. geom_data[constants.URL] = os.path.basename(url)
  113. geometries.append(geom_data)
  114. data[key] = geometries
  115. elif isinstance(value, list):
  116. data[key] = []
  117. for each in value:
  118. data[key].append(each.copy())
  119. elif isinstance(value, dict):
  120. data[key] = value.copy()
  121. io.dump(self.filepath, data, options=self.options)
  122. if self.options.get(constants.COPY_TEXTURES):
  123. for geo in self[constants.GEOMETRIES]:
  124. logger.info("Copying textures from %s", geo.node)
  125. geo.copy_textures()
  126. def _parse_geometries(self):
  127. """Locate all geometry nodes and parse them"""
  128. logger.debug("Scene()._parse_geometries()")
  129. # this is an important step. please refer to the doc string
  130. # on the function for more information
  131. api.object.prep_meshes(self.options)
  132. geometries = []
  133. # now iterate over all the extracted mesh nodes and parse each one
  134. for mesh in api.object.extracted_meshes():
  135. logger.info("Parsing geometry %s", mesh)
  136. geo = geometry.Geometry(mesh, self)
  137. geo.parse()
  138. geometries.append(geo)
  139. logger.info("Added %d geometry nodes", len(geometries))
  140. self[constants.GEOMETRIES] = geometries
  141. def _parse_materials(self):
  142. """Locate all non-orphaned materials and parse them"""
  143. logger.debug("Scene()._parse_materials()")
  144. materials = []
  145. for material_name in api.material.used_materials():
  146. logger.info("Parsing material %s", material_name)
  147. materials.append(material.Material(material_name, parent=self))
  148. logger.info("Added %d material nodes", len(materials))
  149. self[constants.MATERIALS] = materials
  150. def _parse_objects(self):
  151. """Locate all valid objects in the scene and parse them"""
  152. logger.debug("Scene()._parse_objects()")
  153. try:
  154. scene_name = self[constants.METADATA][constants.SOURCE_FILE]
  155. except KeyError:
  156. scene_name = constants.SCENE
  157. self[constants.OBJECT] = object_.Object(None, parent=self)
  158. self[constants.OBJECT][constants.TYPE] = constants.SCENE.title()
  159. self[constants.UUID] = utilities.id_from_name(scene_name)
  160. objects = []
  161. for node in api.object.assemblies(self.valid_types, self.options):
  162. logger.info("Parsing object %s", node)
  163. obj = object_.Object(node, parent=self[constants.OBJECT])
  164. objects.append(obj)
  165. logger.info("Added %d object nodes", len(objects))
  166. self[constants.OBJECT][constants.CHILDREN] = objects
  167. def _parse_textures(self):
  168. """Locate all non-orphaned textures and parse them"""
  169. logger.debug("Scene()._parse_textures()")
  170. textures = []
  171. for texture_name in api.texture.textures():
  172. logger.info("Parsing texture %s", texture_name)
  173. tex_inst = texture.Texture(texture_name, self)
  174. textures.append(tex_inst)
  175. logger.info("Added %d texture nodes", len(textures))
  176. self[constants.TEXTURES] = textures
  177. def _find_node(value, manifest):
  178. """Find a node that matches either a name
  179. or uuid value.
  180. :param value: name or uuid
  181. :param manifest: manifest of nodes to search
  182. :type value: str
  183. :type manifest: list
  184. """
  185. for index in manifest:
  186. uuid = index.get(constants.UUID) == value
  187. name = index.node == value
  188. if uuid or name:
  189. return index
  190. else:
  191. logger.debug("No matching node for %s", value)