CuraStackBuilder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. from UM.ConfigurationErrorMessage import ConfigurationErrorMessage
  5. from UM.Logger import Logger
  6. from UM.Settings.Interfaces import DefinitionContainerInterface
  7. from UM.Settings.InstanceContainer import InstanceContainer
  8. from cura.Machines.ContainerTree import ContainerTree
  9. from .GlobalStack import GlobalStack
  10. from .ExtruderStack import ExtruderStack
  11. class CuraStackBuilder:
  12. """Contains helper functions to create new machines."""
  13. @classmethod
  14. def createMachine(cls, name: str, definition_id: str, machine_extruder_count: Optional[int] = None) -> Optional[GlobalStack]:
  15. """Create a new instance of a machine.
  16. :param name: The name of the new machine.
  17. :param definition_id: The ID of the machine definition to use.
  18. :param machine_extruder_count: The number of extruders in the machine.
  19. :return: The new global stack or None if an error occurred.
  20. """
  21. from cura.CuraApplication import CuraApplication
  22. application = CuraApplication.getInstance()
  23. registry = application.getContainerRegistry()
  24. container_tree = ContainerTree.getInstance()
  25. definitions = registry.findDefinitionContainers(id = definition_id)
  26. if not definitions:
  27. ConfigurationErrorMessage.getInstance().addFaultyContainers(definition_id)
  28. Logger.log("w", "Definition {definition} was not found!", definition = definition_id)
  29. return None
  30. machine_definition = definitions[0]
  31. machine_node = container_tree.machines[machine_definition.getId()]
  32. generated_name = registry.createUniqueName("machine", "", name, machine_definition.getName())
  33. # Make sure the new name does not collide with any definition or (quality) profile
  34. # createUniqueName() only looks at other stacks, but not at definitions or quality profiles
  35. # Note that we don't go for uniqueName() immediately because that function matches with ignore_case set to true
  36. if registry.findContainersMetadata(id = generated_name):
  37. generated_name = registry.uniqueName(generated_name)
  38. new_global_stack = cls.createGlobalStack(
  39. new_stack_id = generated_name,
  40. definition = machine_definition,
  41. variant_container = application.empty_variant_container,
  42. material_container = application.empty_material_container,
  43. quality_container = machine_node.preferredGlobalQuality().container,
  44. )
  45. new_global_stack.setName(generated_name)
  46. # Create ExtruderStacks
  47. extruder_dict = machine_definition.getMetaDataEntry("machine_extruder_trains")
  48. for position in extruder_dict:
  49. try:
  50. cls.createExtruderStackWithDefaultSetup(new_global_stack, position)
  51. except IndexError as e:
  52. Logger.logException("e", "Failed to create an extruder stack for position {pos}: {err}".format(pos = position, err = str(e)))
  53. return None
  54. # If given, set the machine_extruder_count when creating the machine, or else the extruderList used bellow will
  55. # not return the correct extruder list (since by default, the machine_extruder_count is 1) in machines with
  56. # settable number of extruders.
  57. if machine_extruder_count and 0 <= machine_extruder_count <= len(extruder_dict):
  58. new_global_stack.setProperty("machine_extruder_count", "value", machine_extruder_count)
  59. # Only register the extruders if we're sure that all of them are correct.
  60. for new_extruder in new_global_stack.extruderList:
  61. registry.addContainer(new_extruder)
  62. # Register the global stack after the extruder stacks are created. This prevents the registry from adding another
  63. # extruder stack because the global stack didn't have one yet (which is enforced since Cura 3.1).
  64. registry.addContainer(new_global_stack)
  65. return new_global_stack
  66. @classmethod
  67. def createExtruderStackWithDefaultSetup(cls, global_stack: "GlobalStack", extruder_position: int) -> None:
  68. """Create a default Extruder Stack
  69. :param global_stack: The global stack this extruder refers to.
  70. :param extruder_position: The position of the current extruder.
  71. """
  72. from cura.CuraApplication import CuraApplication
  73. application = CuraApplication.getInstance()
  74. registry = application.getContainerRegistry()
  75. # Get the extruder definition.
  76. extruder_definition_dict = global_stack.getMetaDataEntry("machine_extruder_trains")
  77. extruder_definition_id = extruder_definition_dict[str(extruder_position)]
  78. try:
  79. extruder_definition = registry.findDefinitionContainers(id = extruder_definition_id)[0]
  80. except IndexError:
  81. # It still needs to break, but we want to know what extruder ID made it break.
  82. msg = "Unable to find extruder definition with the id [%s]" % extruder_definition_id
  83. Logger.logException("e", msg)
  84. raise IndexError(msg)
  85. # Find out what filament diameter we need.
  86. approximate_diameter = round(extruder_definition.getProperty("material_diameter", "value")) # Can't be modified by definition changes since we are just initialising the stack here.
  87. # Find the preferred containers.
  88. machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
  89. extruder_variant_node = machine_node.variants.get(machine_node.preferred_variant_name)
  90. if not extruder_variant_node:
  91. Logger.log("w", "Could not find preferred nozzle {nozzle_name}. Falling back to {fallback}.".format(nozzle_name = machine_node.preferred_variant_name, fallback = next(iter(machine_node.variants))))
  92. extruder_variant_node = next(iter(machine_node.variants.values()))
  93. extruder_variant_container = extruder_variant_node.container
  94. material_node = extruder_variant_node.preferredMaterial(approximate_diameter)
  95. material_container = material_node.container
  96. quality_node = material_node.preferredQuality()
  97. new_extruder_id = registry.uniqueName(extruder_definition_id)
  98. new_extruder = cls.createExtruderStack(
  99. new_extruder_id,
  100. extruder_definition = extruder_definition,
  101. machine_definition_id = global_stack.definition.getId(),
  102. position = extruder_position,
  103. variant_container = extruder_variant_container,
  104. material_container = material_container,
  105. quality_container = quality_node.container
  106. )
  107. new_extruder.setNextStack(global_stack)
  108. registry.addContainer(new_extruder)
  109. @classmethod
  110. def createExtruderStack(cls, new_stack_id: str, extruder_definition: DefinitionContainerInterface,
  111. machine_definition_id: str,
  112. position: int,
  113. variant_container: "InstanceContainer",
  114. material_container: "InstanceContainer",
  115. quality_container: "InstanceContainer") -> ExtruderStack:
  116. """Create a new Extruder stack
  117. :param new_stack_id: The ID of the new stack.
  118. :param extruder_definition: The definition to base the new stack on.
  119. :param machine_definition_id: The ID of the machine definition to use for the user container.
  120. :param position: The position the extruder occupies in the machine.
  121. :param variant_container: The variant selected for the current extruder.
  122. :param material_container: The material selected for the current extruder.
  123. :param quality_container: The quality selected for the current extruder.
  124. :return: A new Extruder stack instance with the specified parameters.
  125. """
  126. from cura.CuraApplication import CuraApplication
  127. application = CuraApplication.getInstance()
  128. registry = application.getContainerRegistry()
  129. stack = ExtruderStack(new_stack_id)
  130. stack.setName(extruder_definition.getName())
  131. stack.setDefinition(extruder_definition)
  132. stack.setMetaDataEntry("position", str(position))
  133. user_container = cls.createUserChangesContainer(new_stack_id + "_user", machine_definition_id, new_stack_id,
  134. is_global_stack = False)
  135. stack.definitionChanges = cls.createDefinitionChangesContainer(stack, new_stack_id + "_settings")
  136. stack.variant = variant_container
  137. stack.material = material_container
  138. stack.quality = quality_container
  139. stack.intent = application.empty_intent_container
  140. stack.qualityChanges = application.empty_quality_changes_container
  141. stack.userChanges = user_container
  142. # Only add the created containers to the registry after we have set all the other
  143. # properties. This makes the create operation more transactional, since any problems
  144. # setting properties will not result in incomplete containers being added.
  145. registry.addContainer(user_container)
  146. return stack
  147. @classmethod
  148. def createGlobalStack(cls, new_stack_id: str, definition: DefinitionContainerInterface,
  149. variant_container: "InstanceContainer",
  150. material_container: "InstanceContainer",
  151. quality_container: "InstanceContainer") -> GlobalStack:
  152. """Create a new Global stack
  153. :param new_stack_id: The ID of the new stack.
  154. :param definition: The definition to base the new stack on.
  155. :param variant_container: The variant selected for the current stack.
  156. :param material_container: The material selected for the current stack.
  157. :param quality_container: The quality selected for the current stack.
  158. :return: A new Global stack instance with the specified parameters.
  159. """
  160. from cura.CuraApplication import CuraApplication
  161. application = CuraApplication.getInstance()
  162. registry = application.getContainerRegistry()
  163. stack = GlobalStack(new_stack_id)
  164. stack.setDefinition(definition)
  165. # Create user container
  166. user_container = cls.createUserChangesContainer(new_stack_id + "_user", definition.getId(), new_stack_id,
  167. is_global_stack = True)
  168. stack.definitionChanges = cls.createDefinitionChangesContainer(stack, new_stack_id + "_settings")
  169. stack.variant = variant_container
  170. stack.material = material_container
  171. stack.quality = quality_container
  172. stack.intent = application.empty_intent_container
  173. stack.qualityChanges = application.empty_quality_changes_container
  174. stack.userChanges = user_container
  175. registry.addContainer(user_container)
  176. return stack
  177. @classmethod
  178. def createUserChangesContainer(cls, container_name: str, definition_id: str, stack_id: str,
  179. is_global_stack: bool) -> "InstanceContainer":
  180. from cura.CuraApplication import CuraApplication
  181. application = CuraApplication.getInstance()
  182. registry = application.getContainerRegistry()
  183. unique_container_name = registry.uniqueName(container_name)
  184. container = InstanceContainer(unique_container_name)
  185. container.setDefinition(definition_id)
  186. container.setMetaDataEntry("type", "user")
  187. container.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  188. metadata_key_to_add = "machine" if is_global_stack else "extruder"
  189. container.setMetaDataEntry(metadata_key_to_add, stack_id)
  190. return container
  191. @classmethod
  192. def createDefinitionChangesContainer(cls, container_stack, container_name):
  193. from cura.CuraApplication import CuraApplication
  194. application = CuraApplication.getInstance()
  195. registry = application.getContainerRegistry()
  196. unique_container_name = registry.uniqueName(container_name)
  197. definition_changes_container = InstanceContainer(unique_container_name)
  198. definition_changes_container.setDefinition(container_stack.getBottom().getId())
  199. definition_changes_container.setMetaDataEntry("type", "definition_changes")
  200. definition_changes_container.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  201. registry.addContainer(definition_changes_container)
  202. container_stack.definitionChanges = definition_changes_container
  203. return definition_changes_container