PrintInformation.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
  4. from UM.FlameProfiler import pyqtSlot
  5. from UM.Application import Application
  6. from UM.Logger import Logger
  7. from UM.Qt.Duration import Duration
  8. from UM.Preferences import Preferences
  9. from UM.Settings.ContainerRegistry import ContainerRegistry
  10. from cura.Settings.ExtruderManager import ExtruderManager
  11. import math
  12. import os.path
  13. import unicodedata
  14. import json
  15. from UM.i18n import i18nCatalog
  16. catalog = i18nCatalog("cura")
  17. ## A class for processing and calculating minimum, current and maximum print time as well as managing the job name
  18. #
  19. # This class contains all the logic relating to calculation and slicing for the
  20. # time/quality slider concept. It is a rather tricky combination of event handling
  21. # and state management. The logic behind this is as follows:
  22. #
  23. # - A scene change or setting change event happens.
  24. # We track what the source was of the change, either a scene change, a setting change, an active machine change or something else.
  25. # - This triggers a new slice with the current settings - this is the "current settings pass".
  26. # - When the slice is done, we update the current print time and material amount.
  27. # - If the source of the slice was not a Setting change, we start the second slice pass, the "low quality settings pass". Otherwise we stop here.
  28. # - When that is done, we update the minimum print time and start the final slice pass, the "Extra Fine settings pass".
  29. # - When the Extra Fine pass is done, we update the maximum print time.
  30. #
  31. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  32. # This job name is requested by the JobSpecs qml file.
  33. class PrintInformation(QObject):
  34. class SlicePass:
  35. CurrentSettings = 1
  36. LowQualitySettings = 2
  37. HighQualitySettings = 3
  38. class SliceReason:
  39. SceneChanged = 1
  40. SettingChanged = 2
  41. ActiveMachineChanged = 3
  42. Other = 4
  43. def __init__(self, parent = None):
  44. super().__init__(parent)
  45. self._current_print_time = Duration(None, self)
  46. self._print_times_per_feature = {
  47. "none": Duration(None, self),
  48. "inset_0": Duration(None, self),
  49. "inset_x": Duration(None, self),
  50. "skin": Duration(None, self),
  51. "support": Duration(None, self),
  52. "skirt": Duration(None, self),
  53. "infill": Duration(None, self),
  54. "support_infill": Duration(None, self),
  55. "travel": Duration(None, self),
  56. "retract": Duration(None, self),
  57. "support_interface": Duration(None, self)
  58. }
  59. self._material_lengths = []
  60. self._material_weights = []
  61. self._material_costs = []
  62. self._pre_sliced = False
  63. self._backend = Application.getInstance().getBackend()
  64. if self._backend:
  65. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  66. self._job_name = ""
  67. self._abbr_machine = ""
  68. Application.getInstance().globalContainerStackChanged.connect(self._setAbbreviatedMachineName)
  69. Application.getInstance().fileLoaded.connect(self.setJobName)
  70. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  71. self._active_material_container = None
  72. Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
  73. self._onActiveMaterialChanged()
  74. self._material_amounts = []
  75. currentPrintTimeChanged = pyqtSignal()
  76. preSlicedChanged = pyqtSignal()
  77. @pyqtProperty(bool, notify=preSlicedChanged)
  78. def preSliced(self):
  79. return self._pre_sliced
  80. def setPreSliced(self, pre_sliced):
  81. self._pre_sliced = pre_sliced
  82. self.preSlicedChanged.emit()
  83. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  84. def currentPrintTime(self):
  85. return self._current_print_time
  86. @pyqtProperty("QVariantMap", notify = currentPrintTimeChanged)
  87. def printTimesPerFeature(self):
  88. return self._print_times_per_feature
  89. materialLengthsChanged = pyqtSignal()
  90. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  91. def materialLengths(self):
  92. return self._material_lengths
  93. materialWeightsChanged = pyqtSignal()
  94. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  95. def materialWeights(self):
  96. return self._material_weights
  97. materialCostsChanged = pyqtSignal()
  98. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  99. def materialCosts(self):
  100. return self._material_costs
  101. def _onPrintDurationMessage(self, time_per_feature, material_amounts):
  102. total_time = 0
  103. for feature, time in time_per_feature.items():
  104. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  105. self._print_times_per_feature[feature].setDuration(0)
  106. Logger.log("w", "Received NaN for print duration message")
  107. continue
  108. total_time += time
  109. self._print_times_per_feature[feature].setDuration(time)
  110. self._current_print_time.setDuration(total_time)
  111. self.currentPrintTimeChanged.emit()
  112. self._material_amounts = material_amounts
  113. self._calculateInformation()
  114. def _calculateInformation(self):
  115. if Application.getInstance().getGlobalContainerStack() is None:
  116. return
  117. # Material amount is sent as an amount of mm^3, so calculate length from that
  118. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  119. self._material_lengths = []
  120. self._material_weights = []
  121. self._material_costs = []
  122. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  123. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  124. for index, amount in enumerate(self._material_amounts):
  125. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  126. # list comprehension filtering to solve this for us.
  127. material = None
  128. if extruder_stacks: # Multi extrusion machine
  129. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  130. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  131. material = extruder_stack.findContainer({"type": "material"})
  132. else: # Machine with no extruder stacks
  133. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  134. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  135. weight = float(amount) * float(density) / 1000
  136. cost = 0
  137. if material:
  138. material_guid = material.getMetaDataEntry("GUID")
  139. if material_guid in material_preference_values:
  140. material_values = material_preference_values[material_guid]
  141. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  142. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  143. if weight_per_spool != 0:
  144. cost = cost_per_spool * weight / weight_per_spool
  145. else:
  146. cost = 0
  147. if radius != 0:
  148. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  149. else:
  150. length = 0
  151. self._material_weights.append(weight)
  152. self._material_lengths.append(length)
  153. self._material_costs.append(cost)
  154. self.materialLengthsChanged.emit()
  155. self.materialWeightsChanged.emit()
  156. self.materialCostsChanged.emit()
  157. def _onPreferencesChanged(self, preference):
  158. if preference != "cura/material_settings":
  159. return
  160. self._calculateInformation()
  161. def _onActiveMaterialChanged(self):
  162. if self._active_material_container:
  163. try:
  164. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  165. except TypeError: #pyQtSignal gives a TypeError when disconnecting from something that is already disconnected.
  166. pass
  167. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  168. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  169. if active_material_containers:
  170. self._active_material_container = active_material_containers[0]
  171. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  172. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  173. self._calculateInformation()
  174. @pyqtSlot(str)
  175. def setJobName(self, name):
  176. # Ensure that we don't use entire path but only filename
  177. name = os.path.basename(name)
  178. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  179. # extension. This cuts the extension off if necessary.
  180. name = os.path.splitext(name)[0]
  181. name = self.createJobName(name)
  182. if self._job_name != name and (self._job_name == "" or name == ""):
  183. self._job_name = name
  184. self.jobNameChanged.emit()
  185. jobNameChanged = pyqtSignal()
  186. @pyqtProperty(str, notify = jobNameChanged)
  187. def jobName(self):
  188. return self._job_name
  189. @pyqtSlot(str, result = str)
  190. def createJobName(self, base_name):
  191. if base_name == "":
  192. return ""
  193. base_name = self._stripAccents(base_name)
  194. self._setAbbreviatedMachineName()
  195. if self._pre_sliced:
  196. return catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  197. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  198. # Don't add abbreviation if it already has the exact same abbreviation.
  199. if base_name.startswith(self._abbr_machine + "_"):
  200. return base_name
  201. return self._abbr_machine + "_" + base_name
  202. else:
  203. return base_name
  204. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  205. # Called each time the global stack is switched
  206. def _setAbbreviatedMachineName(self):
  207. global_container_stack = Application.getInstance().getGlobalContainerStack()
  208. if not global_container_stack:
  209. self._abbr_machine = ""
  210. return
  211. global_stack_name = global_container_stack.getName()
  212. split_name = global_stack_name.split(" ")
  213. abbr_machine = ""
  214. for word in split_name:
  215. if word.lower() == "ultimaker":
  216. abbr_machine += "UM"
  217. elif word.isdigit():
  218. abbr_machine += word
  219. else:
  220. abbr_machine += self._stripAccents(word.strip("()[]{}#").upper())[0]
  221. self._abbr_machine = abbr_machine
  222. ## Utility method that strips accents from characters (eg: â -> a)
  223. def _stripAccents(self, str):
  224. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')