SolidView.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os.path
  4. from UM.View.View import View
  5. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  6. from UM.Scene.Selection import Selection
  7. from UM.Resources import Resources
  8. from PyQt5.QtGui import QOpenGLContext, QDesktopServices, QImage
  9. from PyQt5.QtCore import QSize, QUrl
  10. import numpy as np
  11. import time
  12. from UM.Application import Application
  13. from UM.Logger import Logger
  14. from UM.Message import Message
  15. from UM.Math.Color import Color
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Platform import Platform
  18. from UM.Event import Event
  19. from UM.View.RenderBatch import RenderBatch
  20. from UM.View.GL.OpenGL import OpenGL
  21. from UM.i18n import i18nCatalog
  22. from cura.Settings.ExtruderManager import ExtruderManager
  23. from cura import XRayPass
  24. import math
  25. catalog = i18nCatalog("cura")
  26. class SolidView(View):
  27. """Standard view for mesh models."""
  28. _show_xray_warning_preference = "view/show_xray_warning"
  29. def __init__(self):
  30. super().__init__()
  31. application = Application.getInstance()
  32. application.getPreferences().addPreference("view/show_overhang", True)
  33. application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  34. self._enabled_shader = None
  35. self._disabled_shader = None
  36. self._non_printing_shader = None
  37. self._support_mesh_shader = None
  38. self._xray_shader = None
  39. self._xray_pass = None
  40. self._xray_composite_shader = None
  41. self._composite_pass = None
  42. self._extruders_model = None
  43. self._theme = None
  44. self._support_angle = self._retrieveSupportAngle()
  45. self._lowest_printable_height = self._retrieveLowestPrintHeight()
  46. self._global_stack = None
  47. self._old_composite_shader = None
  48. self._old_layer_bindings = None
  49. self._next_xray_checking_time = time.time()
  50. self._xray_checking_update_time = 30.0 # seconds
  51. self._xray_warning_cooldown = 60 * 10 # reshow Model error message every 10 minutes
  52. self._xray_warning_message = Message(
  53. catalog.i18nc("@info:status", "The highlighted areas indicate either missing or extraneous surfaces. Fix your model and open it again into Cura."),
  54. lifetime = 60 * 5, # leave message for 5 minutes
  55. title = catalog.i18nc("@info:title", "Model Errors"),
  56. option_text = catalog.i18nc("@info:option_text", "Do not show this message again"),
  57. option_state = False,
  58. message_type=Message.MessageType.WARNING
  59. )
  60. self._xray_warning_message.optionToggled.connect(self._onDontAskMeAgain)
  61. application.getPreferences().addPreference(self._show_xray_warning_preference, True)
  62. self._xray_warning_message.addAction("manifold", catalog.i18nc("@action:button", "Learn more"), "[no_icon]", "[no_description]",
  63. button_style = Message.ActionButtonStyle.LINK,
  64. button_align = Message.ActionButtonAlignment.ALIGN_LEFT)
  65. self._xray_warning_message.actionTriggered.connect(self._onNonManifoldLearnMoreClicked)
  66. application.engineCreatedSignal.connect(self._onGlobalContainerChanged)
  67. def _onDontAskMeAgain(self, checked: bool) -> None:
  68. Application.getInstance().getPreferences().setValue(self._show_xray_warning_preference, not checked)
  69. def _onNonManifoldLearnMoreClicked(self, action, message) -> None:
  70. QDesktopServices.openUrl(QUrl("https://support.ultimaker.com/hc/en-us/articles/360014055959"))
  71. def _onGlobalContainerChanged(self) -> None:
  72. if self._global_stack:
  73. try:
  74. self._global_stack.propertyChanged.disconnect(self._onPropertyChanged)
  75. except TypeError:
  76. pass
  77. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  78. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  79. self._global_stack = Application.getInstance().getGlobalContainerStack()
  80. if self._global_stack:
  81. self._global_stack.propertyChanged.connect(self._onPropertyChanged)
  82. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  83. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  84. # Force re-evaluation:
  85. self._support_angle = self._retrieveSupportAngle()
  86. self._lowest_printable_height = self._retrieveLowestPrintHeight()
  87. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  88. if property_name != "value":
  89. return
  90. # As the rendering is called a *lot* we really, dont want to re-evaluate the property every time. So we store em!
  91. if key == "support_angle":
  92. self._support_angle = self._retrieveSupportAngle()
  93. elif key == "layer_height_0" or key == "slicing_tolerance":
  94. self._lowest_printable_height = self._retrieveLowestPrintHeight()
  95. def _retrieveSupportAngle(self) -> float:
  96. global_container_stack = Application.getInstance().getGlobalContainerStack()
  97. if global_container_stack:
  98. support_extruder_nr = int(global_container_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  99. try:
  100. support_angle_stack = global_container_stack.extruderList[support_extruder_nr]
  101. except IndexError:
  102. pass
  103. else:
  104. angle = support_angle_stack.getProperty("support_angle", "value")
  105. if angle is not None:
  106. return angle
  107. return 90.0
  108. def _retrieveLowestPrintHeight(self) -> float:
  109. min_height = 0.0
  110. for extruder in Application.getInstance().getExtruderManager().getActiveExtruderStacks():
  111. init_layer_height = extruder.getProperty("layer_height_0", "value")
  112. tolerance_setting = extruder.getProperty("slicing_tolerance", "value")
  113. if tolerance_setting == "middle":
  114. init_layer_height /= 2.0
  115. min_height = max(min_height, init_layer_height)
  116. return min_height
  117. def _checkSetup(self):
  118. if not self._extruders_model:
  119. self._extruders_model = Application.getInstance().getExtrudersModel()
  120. if not self._theme:
  121. self._theme = Application.getInstance().getTheme()
  122. if not self._enabled_shader:
  123. self._enabled_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "overhang.shader"))
  124. self._enabled_shader.setUniformValue("u_overhangColor", Color(*self._theme.getColor("model_overhang").getRgb()))
  125. self._enabled_shader.setUniformValue("u_renderError", 0.0)
  126. if not self._disabled_shader:
  127. self._disabled_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "striped.shader"))
  128. self._disabled_shader.setUniformValue("u_diffuseColor1", Color(*self._theme.getColor("model_unslicable").getRgb()))
  129. self._disabled_shader.setUniformValue("u_diffuseColor2", Color(*self._theme.getColor("model_unslicable_alt").getRgb()))
  130. self._disabled_shader.setUniformValue("u_width", 50.0)
  131. if not self._non_printing_shader:
  132. self._non_printing_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "transparent_object.shader"))
  133. self._non_printing_shader.setUniformValue("u_diffuseColor", Color(*self._theme.getColor("model_non_printing").getRgb()))
  134. self._non_printing_shader.setUniformValue("u_opacity", 0.6)
  135. if not self._support_mesh_shader:
  136. self._support_mesh_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "striped.shader"))
  137. self._support_mesh_shader.setUniformValue("u_vertical_stripes", True)
  138. self._support_mesh_shader.setUniformValue("u_width", 5.0)
  139. if not Application.getInstance().getPreferences().getValue(self._show_xray_warning_preference):
  140. self._xray_shader = None
  141. self._xray_composite_shader = None
  142. if self._composite_pass and 'xray' in self._composite_pass.getLayerBindings():
  143. self._composite_pass.setLayerBindings(self._old_layer_bindings)
  144. self._composite_pass.setCompositeShader(self._old_composite_shader)
  145. self._old_layer_bindings = None
  146. self._old_composite_shader = None
  147. self._enabled_shader.setUniformValue("u_renderError", 0.0) # We don't want any error markers!.
  148. self._xray_warning_message.hide()
  149. else:
  150. if not self._xray_shader:
  151. self._xray_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "xray.shader"))
  152. if not self._xray_composite_shader:
  153. self._xray_composite_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "xray_composite.shader"))
  154. theme = Application.getInstance().getTheme()
  155. self._xray_composite_shader.setUniformValue("u_background_color", Color(*theme.getColor("viewport_background").getRgb()))
  156. self._xray_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
  157. self._xray_composite_shader.setUniformValue("u_flat_error_color_mix", 0.) # Don't show flat error color in solid-view.
  158. renderer = self.getRenderer()
  159. if not self._composite_pass or not 'xray' in self._composite_pass.getLayerBindings():
  160. # Currently the RenderPass constructor requires a size > 0
  161. # This should be fixed in RenderPass's constructor.
  162. self._xray_pass = XRayPass.XRayPass(1, 1)
  163. self._enabled_shader.setUniformValue("u_renderError", 1.0) # We don't want any error markers!.
  164. renderer.addRenderPass(self._xray_pass)
  165. if not self._composite_pass:
  166. self._composite_pass = self.getRenderer().getRenderPass("composite")
  167. self._old_layer_bindings = self._composite_pass.getLayerBindings()
  168. self._composite_pass.setLayerBindings(["default", "selection", "xray"])
  169. self._old_composite_shader = self._composite_pass.getCompositeShader()
  170. self._composite_pass.setCompositeShader(self._xray_composite_shader)
  171. def beginRendering(self):
  172. scene = self.getController().getScene()
  173. renderer = self.getRenderer()
  174. self._checkSetup()
  175. global_container_stack = Application.getInstance().getGlobalContainerStack()
  176. if global_container_stack:
  177. if Application.getInstance().getPreferences().getValue("view/show_overhang"):
  178. # Make sure the overhang angle is valid before passing it to the shader
  179. if self._support_angle >= 0 and self._support_angle <= 90:
  180. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(90 - self._support_angle)))
  181. else:
  182. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(0))) #Overhang angle of 0 causes no area at all to be marked as overhang.
  183. else:
  184. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(0)))
  185. self._enabled_shader.setUniformValue("u_lowestPrintableHeight", self._lowest_printable_height)
  186. disabled_batch = renderer.createRenderBatch(shader = self._disabled_shader)
  187. normal_object_batch = renderer.createRenderBatch(shader = self._enabled_shader)
  188. renderer.addRenderBatch(disabled_batch)
  189. renderer.addRenderBatch(normal_object_batch)
  190. for node in DepthFirstIterator(scene.getRoot()):
  191. if node.render(renderer):
  192. continue
  193. if node.getMeshData() and node.isVisible():
  194. uniforms = {}
  195. shade_factor = 1.0
  196. per_mesh_stack = node.callDecoration("getStack")
  197. extruder_index = node.callDecoration("getActiveExtruderPosition")
  198. if extruder_index is None:
  199. extruder_index = "0"
  200. extruder_index = int(extruder_index)
  201. try:
  202. material_color = self._extruders_model.getItem(extruder_index)["color"]
  203. except KeyError:
  204. material_color = self._extruders_model.defaultColors[0]
  205. if extruder_index != ExtruderManager.getInstance().activeExtruderIndex:
  206. # Shade objects that are printed with the non-active extruder 25% darker
  207. shade_factor = 0.6
  208. try:
  209. # Colors are passed as rgb hex strings (eg "#ffffff"), and the shader needs
  210. # an rgba list of floats (eg [1.0, 1.0, 1.0, 1.0])
  211. uniforms["diffuse_color"] = [
  212. shade_factor * int(material_color[1:3], 16) / 255,
  213. shade_factor * int(material_color[3:5], 16) / 255,
  214. shade_factor * int(material_color[5:7], 16) / 255,
  215. 1.0
  216. ]
  217. # Color the currently selected face-id. (Disable for now.)
  218. #face = Selection.getHoverFace()
  219. uniforms["hover_face"] = -1 #if not face or node != face[0] else face[1]
  220. except ValueError:
  221. pass
  222. if node.callDecoration("isNonPrintingMesh"):
  223. if per_mesh_stack and (node.callDecoration("isInfillMesh") or node.callDecoration("isCuttingMesh")):
  224. renderer.queueNode(node, shader = self._non_printing_shader, uniforms = uniforms, transparent = True)
  225. else:
  226. renderer.queueNode(node, shader = self._non_printing_shader, transparent = True)
  227. elif getattr(node, "_outside_buildarea", False):
  228. disabled_batch.addItem(node.getWorldTransformation(copy = False), node.getMeshData(), normal_transformation = node.getCachedNormalMatrix())
  229. elif per_mesh_stack and node.callDecoration("isSupportMesh"):
  230. # Render support meshes with a vertical stripe that is darker
  231. shade_factor = 0.6
  232. uniforms["diffuse_color_2"] = [
  233. uniforms["diffuse_color"][0] * shade_factor,
  234. uniforms["diffuse_color"][1] * shade_factor,
  235. uniforms["diffuse_color"][2] * shade_factor,
  236. 1.0
  237. ]
  238. renderer.queueNode(node, shader = self._support_mesh_shader, uniforms = uniforms)
  239. else:
  240. normal_object_batch.addItem(node.getWorldTransformation(copy=False), node.getMeshData(), uniforms=uniforms, normal_transformation = node.getCachedNormalMatrix())
  241. if node.callDecoration("isGroup") and Selection.isSelected(node):
  242. renderer.queueNode(scene.getRoot(), mesh = node.getBoundingBoxMesh(), mode = RenderBatch.RenderMode.LineLoop)
  243. def endRendering(self):
  244. # check whether the xray overlay is showing badness
  245. if time.time() > self._next_xray_checking_time\
  246. and Application.getInstance().getPreferences().getValue(self._show_xray_warning_preference):
  247. self._next_xray_checking_time = time.time() + self._xray_checking_update_time
  248. xray_img = self._xray_pass.getOutput()
  249. xray_img = xray_img.convertToFormat(QImage.Format_RGB888)
  250. # We can't just read the image since the pixels are aligned to internal memory positions.
  251. # xray_img.byteCount() != xray_img.width() * xray_img.height() * 3
  252. # The byte count is a little higher sometimes. We need to check the data per line, but fast using Numpy.
  253. # See https://stackoverflow.com/questions/5810970/get-raw-data-from-qimage for a description of the problem.
  254. # We can't use that solution though, since it doesn't perform well in Python.
  255. class QImageArrayView:
  256. """
  257. Class that ducktypes to be a Numpy ndarray.
  258. """
  259. def __init__(self, qimage):
  260. bits_pointer = qimage.bits()
  261. if bits_pointer is None: # If this happens before there is a window.
  262. self.__array_interface__ = {
  263. "shape": (0, 0),
  264. "typestr": "|u4",
  265. "data": (0, False),
  266. "strides": (1, 3),
  267. "version": 3
  268. }
  269. else:
  270. self.__array_interface__ = {
  271. "shape": (qimage.height(), qimage.width()),
  272. "typestr": "|u4", # Use 4 bytes per pixel rather than 3, since Numpy doesn't support 3.
  273. "data": (int(bits_pointer), False),
  274. "strides": (qimage.bytesPerLine(), 3), # This does the magic: For each line, skip the correct number of bytes. Bytes per pixel is always 3 due to QImage.Format.Format_RGB888.
  275. "version": 3
  276. }
  277. array = np.asarray(QImageArrayView(xray_img)).view(np.dtype({
  278. "r": (np.uint8, 0, "red"),
  279. "g": (np.uint8, 1, "green"),
  280. "b": (np.uint8, 2, "blue"),
  281. "a": (np.uint8, 3, "alpha") # Never filled since QImage was reformatted to RGB888.
  282. }), np.recarray)
  283. if np.any(np.mod(array.r, 2)):
  284. self._next_xray_checking_time = time.time() + self._xray_warning_cooldown
  285. self._xray_warning_message.show()
  286. Logger.log("i", "X-Ray overlay found non-manifold pixels.")
  287. def event(self, event):
  288. if event.type == Event.ViewDeactivateEvent:
  289. if self._composite_pass and 'xray' in self._composite_pass.getLayerBindings():
  290. self.getRenderer().removeRenderPass(self._xray_pass)
  291. self._composite_pass.setLayerBindings(self._old_layer_bindings)
  292. self._composite_pass.setCompositeShader(self._old_composite_shader)
  293. self._xray_warning_message.hide()