SolidView.py 18 KB

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