StartSliceJob.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. # Copyright (c) 2024 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import uuid
  4. import os
  5. import numpy
  6. from string import Formatter
  7. from enum import IntEnum
  8. import time
  9. from typing import Any, cast, Dict, List, Optional, Set, Tuple
  10. import re
  11. import pyArcus as Arcus # For typing.
  12. from PyQt6.QtCore import QCoreApplication
  13. from UM.Job import Job
  14. from UM.Logger import Logger
  15. from UM.Scene.SceneNode import SceneNode
  16. from UM.Settings.ContainerStack import ContainerStack #For typing.
  17. from UM.Settings.InstanceContainer import InstanceContainer
  18. from UM.Settings.Interfaces import ContainerInterface
  19. from UM.Settings.SettingDefinition import SettingDefinition
  20. from UM.Settings.SettingRelation import SettingRelation #For typing.
  21. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  22. from UM.Scene.Scene import Scene #For typing.
  23. from UM.Settings.Validator import ValidatorState
  24. from UM.Settings.SettingRelation import RelationType
  25. from UM.Settings.SettingFunction import SettingFunction
  26. from cura.CuraApplication import CuraApplication
  27. from cura.Scene.CuraSceneNode import CuraSceneNode
  28. from cura.OneAtATimeIterator import OneAtATimeIterator
  29. from cura.Settings.ExtruderManager import ExtruderManager
  30. from cura.CuraVersion import CuraVersion
  31. NON_PRINTING_MESH_SETTINGS = ["anti_overhang_mesh", "infill_mesh", "cutting_mesh"]
  32. class StartJobResult(IntEnum):
  33. Finished = 1
  34. Error = 2
  35. SettingError = 3
  36. NothingToSlice = 4
  37. MaterialIncompatible = 5
  38. BuildPlateError = 6
  39. ObjectSettingError = 7 #When an error occurs in per-object settings.
  40. ObjectsWithDisabledExtruder = 8
  41. class GcodeStartEndFormatter(Formatter):
  42. # Formatter class that handles token expansion in start/end gcode
  43. # Example of a start/end gcode string:
  44. # ```
  45. # M104 S{material_print_temperature_layer_0, 0} ;pre-heat
  46. # M140 S{material_bed_temperature_layer_0} ;heat bed
  47. # M204 P{acceleration_print, 0} T{acceleration_travel, 0}
  48. # M205 X{jerk_print, 0}
  49. # ```
  50. # Any expression between curly braces will be evaluated and replaced with the result, using the
  51. # context of the provided default extruder. If no default extruder is provided, the global stack
  52. # will be used. Alternatively, if the expression is formatted as "{[expression], [extruder_nr]}",
  53. # then the expression will be evaluated with the extruder stack of the specified extruder_nr.
  54. _extruder_regex = re.compile(r"^\s*(?P<expression>.*)\s*,\s*(?P<extruder_nr_expr>.*)\s*$")
  55. def __init__(self, all_extruder_settings: Dict[str, Any], default_extruder_nr: int = -1) -> None:
  56. super().__init__()
  57. self._all_extruder_settings: Dict[str, Any] = all_extruder_settings
  58. self._default_extruder_nr: int = default_extruder_nr
  59. def get_field(self, field_name, args: [str], kwargs: dict) -> Tuple[str, str]:
  60. # get_field method parses all fields in the format-string and parses them individually to the get_value method.
  61. # e.g. for a string "Hello {foo.bar}" would the complete field "foo.bar" would be passed to get_field, and then
  62. # the individual parts "foo" and "bar" would be passed to get_value. This poses a problem for us, because want
  63. # to parse the entire field as a single expression. To solve this, we override the get_field method and return
  64. # the entire field as the expression.
  65. return self.get_value(field_name, args, kwargs), field_name
  66. def get_value(self, expression: str, args: [str], kwargs: dict) -> str:
  67. # The following variables are not settings, but only become available after slicing.
  68. # when these variables are encountered, we return them as-is. They are replaced later
  69. # when the actual values are known.
  70. post_slice_data_variables = ["filament_cost", "print_time", "filament_amount", "filament_weight", "jobname"]
  71. if expression in post_slice_data_variables:
  72. return f"{{{expression}}}"
  73. extruder_nr = str(self._default_extruder_nr)
  74. # The settings may specify a specific extruder to use. This is done by
  75. # formatting the expression as "{expression}, {extruder_nr_expr}". If the
  76. # expression is formatted like this, we extract the extruder_nr and use
  77. # it to get the value from the correct extruder stack.
  78. match = self._extruder_regex.match(expression)
  79. if match:
  80. expression = match.group("expression")
  81. extruder_nr_expr = match.group("extruder_nr_expr")
  82. if extruder_nr_expr.isdigit():
  83. extruder_nr = extruder_nr_expr
  84. else:
  85. # We get the value of the extruder_nr_expr from `_all_extruder_settings` dictionary
  86. # rather than the global container stack. The `_all_extruder_settings["-1"]` is a
  87. # dict-representation of the global container stack, with additional properties such
  88. # as `initial_extruder_nr`. As users may enter such expressions we can't use the
  89. # global container stack.
  90. extruder_nr = str(self._all_extruder_settings["-1"].get(extruder_nr_expr, "-1"))
  91. if extruder_nr in self._all_extruder_settings:
  92. additional_variables = self._all_extruder_settings[extruder_nr].copy()
  93. else:
  94. Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
  95. additional_variables = self._all_extruder_settings["-1"].copy()
  96. # Add the arguments and keyword arguments to the additional settings. These
  97. # are currently _not_ used, but they are added for consistency with the
  98. # base Formatter class.
  99. for key, value in enumerate(args):
  100. additional_variables[key] = value
  101. for key, value in kwargs.items():
  102. additional_variables[key] = value
  103. if extruder_nr == "-1":
  104. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  105. else:
  106. container_stack = ExtruderManager.getInstance().getExtruderStack(extruder_nr)
  107. if not container_stack:
  108. Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
  109. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  110. setting_function = SettingFunction(expression)
  111. value = setting_function(container_stack, additional_variables=additional_variables)
  112. return value
  113. class StartSliceJob(Job):
  114. """Job class that builds up the message of scene data to send to CuraEngine."""
  115. def __init__(self, slice_message: Arcus.PythonMessage) -> None:
  116. super().__init__()
  117. self._scene: Scene = CuraApplication.getInstance().getController().getScene()
  118. self._slice_message: Arcus.PythonMessage = slice_message
  119. self._is_cancelled: bool = False
  120. self._build_plate_number: Optional[int] = None
  121. self._associated_disabled_extruders: Optional[str] = None
  122. # cache for all setting values from all stacks (global & extruder) for the current machine
  123. self._all_extruders_settings: Optional[Dict[str, Any]] = None
  124. def getSliceMessage(self) -> Arcus.PythonMessage:
  125. return self._slice_message
  126. def getAssociatedDisabledExtruders(self) -> Optional[str]:
  127. return self._associated_disabled_extruders
  128. def setBuildPlate(self, build_plate_number: int) -> None:
  129. self._build_plate_number = build_plate_number
  130. def _checkStackForErrors(self, stack: ContainerStack) -> bool:
  131. """Check if a stack has any errors."""
  132. """returns true if it has errors, false otherwise."""
  133. top_of_stack = cast(InstanceContainer, stack.getTop()) # Cache for efficiency.
  134. changed_setting_keys = top_of_stack.getAllKeys()
  135. # Add all relations to changed settings as well.
  136. for key in top_of_stack.getAllKeys():
  137. instance = top_of_stack.getInstance(key)
  138. if instance is None:
  139. continue
  140. self._addRelations(changed_setting_keys, instance.definition.relations)
  141. Job.yieldThread()
  142. for changed_setting_key in changed_setting_keys:
  143. if not stack.getProperty(changed_setting_key, "enabled"):
  144. continue
  145. validation_state = stack.getProperty(changed_setting_key, "validationState")
  146. if validation_state is None:
  147. definition = cast(SettingDefinition, stack.getSettingDefinition(changed_setting_key))
  148. validator_type = SettingDefinition.getValidatorForType(definition.type)
  149. if validator_type:
  150. validator = validator_type(changed_setting_key)
  151. validation_state = validator(stack)
  152. if validation_state in (
  153. ValidatorState.Exception, ValidatorState.MaximumError, ValidatorState.MinimumError, ValidatorState.Invalid):
  154. Logger.log("w", "Setting %s is not valid, but %s. Aborting slicing.", changed_setting_key, validation_state)
  155. return True
  156. Job.yieldThread()
  157. return False
  158. def run(self) -> None:
  159. """Runs the job that initiates the slicing."""
  160. if self._build_plate_number is None:
  161. self.setResult(StartJobResult.Error)
  162. return
  163. stack = CuraApplication.getInstance().getGlobalContainerStack()
  164. if not stack:
  165. self.setResult(StartJobResult.Error)
  166. return
  167. # Don't slice if there is a setting with an error value.
  168. if CuraApplication.getInstance().getMachineManager().stacksHaveErrors:
  169. self.setResult(StartJobResult.SettingError)
  170. return
  171. if CuraApplication.getInstance().getBuildVolume().hasErrors():
  172. self.setResult(StartJobResult.BuildPlateError)
  173. return
  174. # Wait for error checker to be done.
  175. while CuraApplication.getInstance().getMachineErrorChecker().needToWaitForResult:
  176. time.sleep(0.1)
  177. if CuraApplication.getInstance().getMachineErrorChecker().hasError:
  178. self.setResult(StartJobResult.SettingError)
  179. return
  180. # Don't slice if the buildplate or the nozzle type is incompatible with the materials
  181. if not CuraApplication.getInstance().getMachineManager().variantBuildplateCompatible and \
  182. not CuraApplication.getInstance().getMachineManager().variantBuildplateUsable:
  183. self.setResult(StartJobResult.MaterialIncompatible)
  184. return
  185. for extruder_stack in stack.extruderList:
  186. material = extruder_stack.findContainer({"type": "material"})
  187. if not extruder_stack.isEnabled:
  188. continue
  189. if material:
  190. if material.getMetaDataEntry("compatible") == False:
  191. self.setResult(StartJobResult.MaterialIncompatible)
  192. return
  193. # Don't slice if there is a per object setting with an error value.
  194. for node in DepthFirstIterator(self._scene.getRoot()):
  195. if not isinstance(node, CuraSceneNode) or not node.isSelectable():
  196. continue
  197. if self._checkStackForErrors(node.callDecoration("getStack")):
  198. self.setResult(StartJobResult.ObjectSettingError)
  199. return
  200. # Remove old layer data.
  201. for node in DepthFirstIterator(self._scene.getRoot()):
  202. if node.callDecoration("getLayerData") and node.callDecoration("getBuildPlateNumber") == self._build_plate_number:
  203. # Since we walk through all nodes in the scene, they always have a parent.
  204. cast(SceneNode, node.getParent()).removeChild(node)
  205. break
  206. # Get the objects in their groups to print.
  207. object_groups = []
  208. if stack.getProperty("print_sequence", "value") == "one_at_a_time":
  209. modifier_mesh_nodes = []
  210. for node in DepthFirstIterator(self._scene.getRoot()):
  211. build_plate_number = node.callDecoration("getBuildPlateNumber")
  212. if node.callDecoration("isNonPrintingMesh") and build_plate_number == self._build_plate_number:
  213. modifier_mesh_nodes.append(node)
  214. for node in OneAtATimeIterator(self._scene.getRoot()):
  215. temp_list = []
  216. # Filter on current build plate
  217. build_plate_number = node.callDecoration("getBuildPlateNumber")
  218. if build_plate_number is not None and build_plate_number != self._build_plate_number:
  219. continue
  220. children = node.getAllChildren()
  221. children.append(node)
  222. for child_node in children:
  223. mesh_data = child_node.getMeshData()
  224. if mesh_data and mesh_data.getVertices() is not None:
  225. temp_list.append(child_node)
  226. if temp_list:
  227. object_groups.append(temp_list + modifier_mesh_nodes)
  228. Job.yieldThread()
  229. if len(object_groups) == 0:
  230. Logger.log("w", "No objects suitable for one at a time found, or no correct order found")
  231. else:
  232. temp_list = []
  233. has_printing_mesh = False
  234. for node in DepthFirstIterator(self._scene.getRoot()):
  235. mesh_data = node.getMeshData()
  236. if node.callDecoration("isSliceable") and mesh_data and mesh_data.getVertices() is not None:
  237. is_non_printing_mesh = bool(node.callDecoration("isNonPrintingMesh"))
  238. # Find a reason not to add the node
  239. if node.callDecoration("getBuildPlateNumber") != self._build_plate_number:
  240. continue
  241. if getattr(node, "_outside_buildarea", False) and not is_non_printing_mesh:
  242. continue
  243. temp_list.append(node)
  244. if not is_non_printing_mesh:
  245. has_printing_mesh = True
  246. Job.yieldThread()
  247. # If the list doesn't have any model with suitable settings then clean the list
  248. # otherwise CuraEngine will crash
  249. if not has_printing_mesh:
  250. temp_list.clear()
  251. if temp_list:
  252. object_groups.append(temp_list)
  253. global_stack = CuraApplication.getInstance().getGlobalContainerStack()
  254. if not global_stack:
  255. return
  256. extruders_enabled = [stack.isEnabled for stack in global_stack.extruderList]
  257. filtered_object_groups = []
  258. has_model_with_disabled_extruders = False
  259. associated_disabled_extruders = set()
  260. for group in object_groups:
  261. stack = global_stack
  262. skip_group = False
  263. for node in group:
  264. # Only check if the printing extruder is enabled for printing meshes
  265. is_non_printing_mesh = node.callDecoration("evaluateIsNonPrintingMesh")
  266. extruder_position = int(node.callDecoration("getActiveExtruderPosition"))
  267. if not is_non_printing_mesh and not extruders_enabled[extruder_position]:
  268. skip_group = True
  269. has_model_with_disabled_extruders = True
  270. associated_disabled_extruders.add(extruder_position)
  271. if not skip_group:
  272. filtered_object_groups.append(group)
  273. if has_model_with_disabled_extruders:
  274. self.setResult(StartJobResult.ObjectsWithDisabledExtruder)
  275. associated_disabled_extruders = {p + 1 for p in associated_disabled_extruders}
  276. self._associated_disabled_extruders = ", ".join(map(str, sorted(associated_disabled_extruders)))
  277. return
  278. # There are cases when there is nothing to slice. This can happen due to one at a time slicing not being
  279. # able to find a possible sequence or because there are no objects on the build plate (or they are outside
  280. # the build volume)
  281. if not filtered_object_groups:
  282. self.setResult(StartJobResult.NothingToSlice)
  283. return
  284. self._buildGlobalSettingsMessage(stack)
  285. self._buildGlobalInheritsStackMessage(stack)
  286. user_id = uuid.getnode() # On all of Cura's supported platforms, this returns the MAC address which is pseudonymical information (!= anonymous).
  287. user_id %= 2 ** 16 # So to make it anonymous, apply a bitmask selecting only the last 16 bits. This prevents it from being traceable to a specific user but still gives somewhat of an idea of whether it's just the same user hitting the same crash over and over again, or if it's widespread.
  288. self._slice_message.sentry_id = f"{user_id}"
  289. self._slice_message.cura_version = CuraVersion
  290. # Add the project name to the message if the user allows for non-anonymous crash data collection.
  291. account = CuraApplication.getInstance().getCuraAPI().account
  292. if account and account.isLoggedIn and not CuraApplication.getInstance().getPreferences().getValue("info/anonymous_engine_crash_report"):
  293. self._slice_message.project_name = CuraApplication.getInstance().getPrintInformation().baseName
  294. self._slice_message.user_name = account.userName
  295. # Build messages for extruder stacks
  296. for extruder_stack in global_stack.extruderList:
  297. self._buildExtruderMessage(extruder_stack)
  298. for plugin in CuraApplication.getInstance().getBackendPlugins():
  299. if not plugin.usePlugin():
  300. continue
  301. for slot in plugin.getSupportedSlots():
  302. # Right now we just send the message for every slot that we support. A single plugin can support
  303. # multiple slots
  304. # In the future the frontend will need to decide what slots that a plugin actually supports should
  305. # also be used. For instance, if you have two plugins and each of them support a_generate and b_generate
  306. # only one of each can actually be used (eg; plugin 1 does both, plugin 1 does a_generate and 2 does
  307. # b_generate, etc).
  308. plugin_message = self._slice_message.addRepeatedMessage("engine_plugins")
  309. plugin_message.id = slot
  310. plugin_message.address = plugin.getAddress()
  311. plugin_message.port = plugin.getPort()
  312. plugin_message.plugin_name = plugin.getPluginId()
  313. plugin_message.plugin_version = plugin.getVersion()
  314. for group in filtered_object_groups:
  315. group_message = self._slice_message.addRepeatedMessage("object_lists")
  316. parent = group[0].getParent()
  317. if parent is not None and parent.callDecoration("isGroup"):
  318. self._handlePerObjectSettings(cast(CuraSceneNode, parent), group_message)
  319. for object in group:
  320. mesh_data = object.getMeshData()
  321. if mesh_data is None:
  322. continue
  323. rot_scale = object.getWorldTransformation().getTransposed().getData()[0:3, 0:3]
  324. translate = object.getWorldTransformation().getData()[:3, 3]
  325. # This effectively performs a limited form of MeshData.getTransformed that ignores normals.
  326. verts = mesh_data.getVertices()
  327. verts = verts.dot(rot_scale)
  328. verts += translate
  329. # Convert from Y up axes to Z up axes. Equals a 90 degree rotation.
  330. verts[:, [1, 2]] = verts[:, [2, 1]]
  331. verts[:, 1] *= -1
  332. obj = group_message.addRepeatedMessage("objects")
  333. obj.id = id(object)
  334. obj.name = object.getName()
  335. indices = mesh_data.getIndices()
  336. if indices is not None:
  337. flat_verts = numpy.take(verts, indices.flatten(), axis=0)
  338. else:
  339. flat_verts = numpy.array(verts)
  340. obj.vertices = flat_verts
  341. self._handlePerObjectSettings(cast(CuraSceneNode, object), obj)
  342. Job.yieldThread()
  343. self.setResult(StartJobResult.Finished)
  344. def cancel(self) -> None:
  345. super().cancel()
  346. self._is_cancelled = True
  347. def isCancelled(self) -> bool:
  348. return self._is_cancelled
  349. def setIsCancelled(self, value: bool):
  350. self._is_cancelled = value
  351. def _buildReplacementTokens(self, stack: ContainerStack) -> Dict[str, Any]:
  352. """Creates a dictionary of tokens to replace in g-code pieces.
  353. This indicates what should be replaced in the start and end g-codes.
  354. :param stack: The stack to get the settings from to replace the tokens with.
  355. :return: A dictionary of replacement tokens to the values they should be replaced with.
  356. """
  357. result = {}
  358. for key in stack.getAllKeys():
  359. result[key] = stack.getProperty(key, "value")
  360. Job.yieldThread()
  361. # Material identification in addition to non-human-readable GUID
  362. result["material_id"] = stack.material.getMetaDataEntry("base_file", "")
  363. result["material_type"] = stack.material.getMetaDataEntry("material", "")
  364. result["material_name"] = stack.material.getMetaDataEntry("name", "")
  365. result["material_brand"] = stack.material.getMetaDataEntry("brand", "")
  366. result["quality_name"] = stack.quality.getMetaDataEntry("name", "")
  367. result["quality_changes_name"] = stack.qualityChanges.getMetaDataEntry("name")
  368. # Renamed settings.
  369. result["print_bed_temperature"] = result["material_bed_temperature"]
  370. result["print_temperature"] = result["material_print_temperature"]
  371. result["travel_speed"] = result["speed_travel"]
  372. #Some extra settings.
  373. result["time"] = time.strftime("%H:%M:%S")
  374. result["date"] = time.strftime("%d-%m-%Y")
  375. result["day"] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][int(time.strftime("%w"))]
  376. result["initial_extruder_nr"] = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  377. return result
  378. def _cacheAllExtruderSettings(self):
  379. global_stack = cast(ContainerStack, CuraApplication.getInstance().getGlobalContainerStack())
  380. # NB: keys must be strings for the string formatter
  381. self._all_extruders_settings = {
  382. "-1": self._buildReplacementTokens(global_stack)
  383. }
  384. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  385. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  386. extruder_nr = extruder_stack.getProperty("extruder_nr", "value")
  387. self._all_extruders_settings[str(extruder_nr)] = self._buildReplacementTokens(extruder_stack)
  388. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  389. def _expandGcodeTokens(self, value: str, default_extruder_nr: int = -1) -> str:
  390. """Replace setting tokens in a piece of g-code.
  391. :param value: A piece of g-code to replace tokens in.
  392. :param default_extruder_nr: Stack nr to use when no stack nr is specified, defaults to the global stack
  393. """
  394. if not self._all_extruders_settings:
  395. self._cacheAllExtruderSettings()
  396. try:
  397. # Get "replacement-keys" for the extruders. In the formatter the settings stack is used to get the
  398. # replacement values for the setting-keys. However, the values for `material_id`, `material_type`,
  399. # etc are not in the settings stack.
  400. fmt = GcodeStartEndFormatter(self._all_extruders_settings, default_extruder_nr=default_extruder_nr)
  401. return str(fmt.format(value))
  402. except:
  403. Logger.logException("w", "Unable to do token replacement on start/end g-code")
  404. return str(value)
  405. def _buildExtruderMessage(self, stack: ContainerStack) -> None:
  406. """Create extruder message from stack"""
  407. message = self._slice_message.addRepeatedMessage("extruders")
  408. message.id = int(stack.getMetaDataEntry("position"))
  409. if not self._all_extruders_settings:
  410. self._cacheAllExtruderSettings()
  411. if self._all_extruders_settings is None:
  412. return
  413. extruder_nr = stack.getProperty("extruder_nr", "value")
  414. settings = self._all_extruders_settings[str(extruder_nr)].copy()
  415. # Also send the material GUID. This is a setting in fdmprinter, but we have no interface for it.
  416. settings["material_guid"] = stack.material.getMetaDataEntry("GUID", "")
  417. # Replace the setting tokens in start and end g-code.
  418. extruder_nr = stack.getProperty("extruder_nr", "value")
  419. settings["machine_extruder_start_code"] = self._expandGcodeTokens(settings["machine_extruder_start_code"], extruder_nr)
  420. settings["machine_extruder_end_code"] = self._expandGcodeTokens(settings["machine_extruder_end_code"], extruder_nr)
  421. global_definition = cast(ContainerInterface, cast(ContainerStack, stack.getNextStack()).getBottom())
  422. own_definition = cast(ContainerInterface, stack.getBottom())
  423. for key, value in settings.items():
  424. # Do not send settings that are not settable_per_extruder.
  425. # Since these can only be set in definition files, we only have to ask there.
  426. if not global_definition.getProperty(key, "settable_per_extruder") and \
  427. not own_definition.getProperty(key, "settable_per_extruder"):
  428. continue
  429. setting = message.getMessage("settings").addRepeatedMessage("settings")
  430. setting.name = key
  431. setting.value = str(value).encode("utf-8")
  432. Job.yieldThread()
  433. def _buildGlobalSettingsMessage(self, stack: ContainerStack) -> None:
  434. """Sends all global settings to the engine.
  435. The settings are taken from the global stack. This does not include any
  436. per-extruder settings or per-object settings.
  437. """
  438. if not self._all_extruders_settings:
  439. self._cacheAllExtruderSettings()
  440. if self._all_extruders_settings is None:
  441. return
  442. settings = self._all_extruders_settings["-1"].copy()
  443. # Pre-compute material material_bed_temp_prepend and material_print_temp_prepend
  444. start_gcode = settings["machine_start_gcode"]
  445. # Remove all the comments from the start g-code
  446. start_gcode = re.sub(r";.+?(\n|$)", "\n", start_gcode)
  447. bed_temperature_settings = ["material_bed_temperature", "material_bed_temperature_layer_0"]
  448. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(bed_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  449. settings["material_bed_temp_prepend"] = re.search(pattern, start_gcode) == None
  450. print_temperature_settings = ["material_print_temperature", "material_print_temperature_layer_0", "default_material_print_temperature", "material_initial_print_temperature", "material_final_print_temperature", "material_standby_temperature", "print_temperature"]
  451. pattern = r"\{(%s)(,\s?\w+)?\}" % "|".join(print_temperature_settings) # match {setting} as well as {setting, extruder_nr}
  452. settings["material_print_temp_prepend"] = re.search(pattern, start_gcode) is None
  453. # Replace the setting tokens in start and end g-code.
  454. # Use values from the first used extruder by default so we get the expected temperatures
  455. initial_extruder_nr = CuraApplication.getInstance().getExtruderManager().getInitialExtruderNr()
  456. settings["machine_start_gcode"] = self._expandGcodeTokens(settings["machine_start_gcode"], initial_extruder_nr)
  457. settings["machine_end_gcode"] = self._expandGcodeTokens(settings["machine_end_gcode"], initial_extruder_nr)
  458. # Manually add 'nozzle offsetting', since that is a metadata-entry instead for some reason.
  459. # NOTE: This probably needs to be an actual setting at some point.
  460. settings["nozzle_offsetting_for_disallowed_areas"] = CuraApplication.getInstance().getGlobalContainerStack().getMetaDataEntry("nozzle_offsetting_for_disallowed_areas", True)
  461. # Add all sub-messages for each individual setting.
  462. for key, value in settings.items():
  463. setting_message = self._slice_message.getMessage("global_settings").addRepeatedMessage("settings")
  464. setting_message.name = key
  465. setting_message.value = str(value).encode("utf-8")
  466. Job.yieldThread()
  467. def _buildGlobalInheritsStackMessage(self, stack: ContainerStack) -> None:
  468. """Sends for some settings which extruder they should fallback to if not set.
  469. This is only set for settings that have the limit_to_extruder
  470. property.
  471. :param stack: The global stack with all settings, from which to read the
  472. limit_to_extruder property.
  473. """
  474. for key in stack.getAllKeys():
  475. extruder_position = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  476. if extruder_position >= 0: # Set to a specific extruder.
  477. setting_extruder = self._slice_message.addRepeatedMessage("limit_to_extruder")
  478. setting_extruder.name = key
  479. setting_extruder.extruder = extruder_position
  480. Job.yieldThread()
  481. def _handlePerObjectSettings(self, node: CuraSceneNode, message: Arcus.PythonMessage):
  482. """Check if a node has per object settings and ensure that they are set correctly in the message
  483. :param node: Node to check.
  484. :param message: object_lists message to put the per object settings in
  485. """
  486. stack = node.callDecoration("getStack")
  487. # Check if the node has a stack attached to it and the stack has any settings in the top container.
  488. if not stack:
  489. return
  490. # Check all settings for relations, so we can also calculate the correct values for dependent settings.
  491. top_of_stack = stack.getTop() # Cache for efficiency.
  492. changed_setting_keys = top_of_stack.getAllKeys()
  493. # Add all relations to changed settings as well.
  494. for key in top_of_stack.getAllKeys():
  495. instance = top_of_stack.getInstance(key)
  496. self._addRelations(changed_setting_keys, instance.definition.relations)
  497. Job.yieldThread()
  498. # Ensure that the engine is aware what the build extruder is.
  499. changed_setting_keys.add("extruder_nr")
  500. # Get values for all changed settings
  501. for key in changed_setting_keys:
  502. setting = message.addRepeatedMessage("settings")
  503. setting.name = key
  504. extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
  505. # Check if limited to a specific extruder, but not overridden by per-object settings.
  506. if extruder >= 0 and key not in changed_setting_keys:
  507. limited_stack = ExtruderManager.getInstance().getActiveExtruderStacks()[extruder]
  508. else:
  509. limited_stack = stack
  510. setting.value = str(limited_stack.getProperty(key, "value")).encode("utf-8")
  511. Job.yieldThread()
  512. def _addRelations(self, relations_set: Set[str], relations: List[SettingRelation]):
  513. """Recursive function to put all settings that require each other for value changes in a list
  514. :param relations_set: Set of keys of settings that are influenced
  515. :param relations: list of relation objects that need to be checked.
  516. """
  517. for relation in filter(lambda r: r.role == "value" or r.role == "limit_to_extruder", relations):
  518. if relation.type == RelationType.RequiresTarget:
  519. continue
  520. relations_set.add(relation.target.key)
  521. self._addRelations(relations_set, relation.target.relations)