PlotCanvas.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # Author: Dennis Hayrullin (c) #
  4. # Date: 2016 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtCore
  8. import logging
  9. from flatcamGUI.VisPyCanvas import VisPyCanvas, time, Color
  10. from flatcamGUI.VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor
  11. from vispy.scene.visuals import InfiniteLine, Line
  12. import numpy as np
  13. from vispy.geometry import Rect
  14. log = logging.getLogger('base')
  15. class PlotCanvas(QtCore.QObject, VisPyCanvas):
  16. """
  17. Class handling the plotting area in the application.
  18. """
  19. def __init__(self, container, fcapp):
  20. """
  21. The constructor configures the VisPy figure that
  22. will contain all plots, creates the base axes and connects
  23. events to the plotting area.
  24. :param container: The parent container in which to draw plots.
  25. :rtype: PlotCanvas
  26. """
  27. super(PlotCanvas, self).__init__()
  28. # VisPyCanvas.__init__(self)
  29. # VisPyCanvas does not allow new attributes. Override.
  30. self.unfreeze()
  31. self.fcapp = fcapp
  32. # Parent container
  33. self.container = container
  34. settings = QtCore.QSettings("Open Source", "FlatCAM")
  35. if settings.contains("theme"):
  36. theme = settings.value('theme', type=str)
  37. else:
  38. theme = 'white'
  39. if theme == 'white':
  40. self.line_color = (0.3, 0.0, 0.0, 1.0)
  41. else:
  42. self.line_color = (0.4, 0.4, 0.4, 1.0)
  43. # workspace lines; I didn't use the rectangle because I didn't want to add another VisPy Node,
  44. # which might decrease performance
  45. self.b_line, self.r_line, self.t_line, self.l_line = None, None, None, None
  46. # <VisPyCanvas>
  47. self.create_native()
  48. self.native.setParent(self.fcapp.ui)
  49. # <QtCore.QObject>
  50. self.container.addWidget(self.native)
  51. # ## AXIS # ##
  52. self.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  53. parent=self.view.scene)
  54. self.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  55. parent=self.view.scene)
  56. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  57. # all CNC have a limited workspace
  58. self.draw_workspace()
  59. self.line_parent = None
  60. self.cursor_v_line = InfiniteLine(pos=None, color=self.line_color, vertical=True,
  61. parent=self.line_parent)
  62. self.cursor_h_line = InfiniteLine(pos=None, color=self.line_color, vertical=False,
  63. parent=self.line_parent)
  64. # if self.app.defaults['global_workspace'] is True:
  65. # if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  66. # self.wkspace_t = Line(pos=)
  67. self.shape_collections = []
  68. self.shape_collection = self.new_shape_collection()
  69. self.fcapp.pool_recreated.connect(self.on_pool_recreated)
  70. self.text_collection = self.new_text_collection()
  71. # TODO: Should be setting to show/hide CNC job annotations (global or per object)
  72. self.text_collection.enabled = True
  73. self.c = None
  74. self.big_cursor = None
  75. # Keep VisPy canvas happy by letting it be "frozen" again.
  76. self.freeze()
  77. self.graph_event_connect('mouse_wheel', self.on_mouse_scroll)
  78. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  79. # all CNC have a limited workspace
  80. def draw_workspace(self):
  81. a = np.empty((0, 0))
  82. a4p_in = np.array([(0, 0), (8.3, 0), (8.3, 11.7), (0, 11.7)])
  83. a4l_in = np.array([(0, 0), (11.7, 0), (11.7, 8.3), (0, 8.3)])
  84. a3p_in = np.array([(0, 0), (11.7, 0), (11.7, 16.5), (0, 16.5)])
  85. a3l_in = np.array([(0, 0), (16.5, 0), (16.5, 11.7), (0, 11.7)])
  86. a4p_mm = np.array([(0, 0), (210, 0), (210, 297), (0, 297)])
  87. a4l_mm = np.array([(0, 0), (297, 0), (297, 210), (0, 210)])
  88. a3p_mm = np.array([(0, 0), (297, 0), (297, 420), (0, 420)])
  89. a3l_mm = np.array([(0, 0), (420, 0), (420, 297), (0, 297)])
  90. if self.fcapp.defaults['units'].upper() == 'MM':
  91. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  92. a = a4p_mm
  93. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  94. a = a4l_mm
  95. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  96. a = a3p_mm
  97. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  98. a = a3l_mm
  99. else:
  100. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  101. a = a4p_in
  102. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  103. a = a4l_in
  104. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  105. a = a3p_in
  106. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  107. a = a3l_in
  108. self.delete_workspace()
  109. self.b_line = Line(pos=a[0:2], color=(0.70, 0.3, 0.3, 1.0),
  110. antialias=True, method='agg', parent=self.view.scene)
  111. self.r_line = Line(pos=a[1:3], color=(0.70, 0.3, 0.3, 1.0),
  112. antialias=True, method='agg', parent=self.view.scene)
  113. self.t_line = Line(pos=a[2:4], color=(0.70, 0.3, 0.3, 1.0),
  114. antialias=True, method='agg', parent=self.view.scene)
  115. self.l_line = Line(pos=np.array((a[0], a[3])), color=(0.70, 0.3, 0.3, 1.0),
  116. antialias=True, method='agg', parent=self.view.scene)
  117. if self.fcapp.defaults['global_workspace'] is False:
  118. self.delete_workspace()
  119. # delete the workspace lines from the plot by removing the parent
  120. def delete_workspace(self):
  121. try:
  122. self.b_line.parent = None
  123. self.r_line.parent = None
  124. self.t_line.parent = None
  125. self.l_line.parent = None
  126. except Exception:
  127. pass
  128. # redraw the workspace lines on the plot by readding them to the parent view.scene
  129. def restore_workspace(self):
  130. try:
  131. self.b_line.parent = self.view.scene
  132. self.r_line.parent = self.view.scene
  133. self.t_line.parent = self.view.scene
  134. self.l_line.parent = self.view.scene
  135. except Exception:
  136. pass
  137. def graph_event_connect(self, event_name, callback):
  138. return getattr(self.events, event_name).connect(callback)
  139. def graph_event_disconnect(self, event_name, callback=None):
  140. if callback is None:
  141. getattr(self.events, event_name).disconnect()
  142. else:
  143. getattr(self.events, event_name).disconnect(callback)
  144. def zoom(self, factor, center=None):
  145. """
  146. Zooms the plot by factor around a given
  147. center point. Takes care of re-drawing.
  148. :param factor: Number by which to scale the plot.
  149. :type factor: float
  150. :param center: Coordinates [x, y] of the point around which to scale the plot.
  151. :type center: list
  152. :return: None
  153. """
  154. self.view.camera.zoom(factor, center)
  155. def new_shape_group(self, shape_collection=None):
  156. if shape_collection:
  157. return ShapeGroup(shape_collection)
  158. return ShapeGroup(self.shape_collection)
  159. def new_shape_collection(self, **kwargs):
  160. # sc = ShapeCollection(parent=self.view.scene, pool=self.app.pool, **kwargs)
  161. # self.shape_collections.append(sc)
  162. # return sc
  163. return ShapeCollection(parent=self.view.scene, pool=self.fcapp.pool, **kwargs)
  164. def new_cursor(self, big=None):
  165. """
  166. Will create a mouse cursor pointer on canvas
  167. :param big: if True will create a mouse cursor made out of infinite lines
  168. :return: the mouse cursor object
  169. """
  170. if big is True:
  171. self.big_cursor = True
  172. self.c = CursorBig()
  173. # in case there are multiple new_cursor calls, best to disconnect first the signals
  174. try:
  175. self.c.mouse_state_updated.disconnect(self.on_mouse_state)
  176. except (TypeError, AttributeError):
  177. pass
  178. try:
  179. self.c.mouse_position_updated.disconnect(self.on_mouse_position)
  180. except (TypeError, AttributeError):
  181. pass
  182. self.c.mouse_state_updated.connect(self.on_mouse_state)
  183. self.c.mouse_position_updated.connect(self.on_mouse_position)
  184. else:
  185. self.big_cursor = False
  186. self.c = Cursor(pos=np.empty((0, 2)), parent=self.view.scene)
  187. self.c.antialias = 0
  188. return self.c
  189. def on_mouse_state(self, state):
  190. if state:
  191. self.cursor_h_line.parent = self.view.scene
  192. self.cursor_v_line.parent = self.view.scene
  193. else:
  194. self.cursor_h_line.parent = None
  195. self.cursor_v_line.parent = None
  196. def on_mouse_position(self, pos):
  197. # self.line_color = color
  198. self.cursor_h_line.set_data(pos=pos[1], color=self.line_color)
  199. self.cursor_v_line.set_data(pos=pos[0], color=self.line_color)
  200. self.view.scene.update()
  201. def on_mouse_scroll(self, event):
  202. # key modifiers
  203. modifiers = event.modifiers
  204. pan_delta_x = self.fcapp.defaults["global_gridx"]
  205. pan_delta_y = self.fcapp.defaults["global_gridy"]
  206. curr_pos = event.pos
  207. # Controlled pan by mouse wheel
  208. if 'Shift' in modifiers:
  209. p1 = np.array(curr_pos)[:2]
  210. if event.delta[1] > 0:
  211. curr_pos[0] -= pan_delta_x
  212. else:
  213. curr_pos[0] += pan_delta_x
  214. p2 = np.array(curr_pos)[:2]
  215. self.view.camera.pan(p2 - p1)
  216. elif 'Control' in modifiers:
  217. p1 = np.array(curr_pos)[:2]
  218. if event.delta[1] > 0:
  219. curr_pos[1] += pan_delta_y
  220. else:
  221. curr_pos[1] -= pan_delta_y
  222. p2 = np.array(curr_pos)[:2]
  223. self.view.camera.pan(p2 - p1)
  224. if self.fcapp.grid_status() == True:
  225. pos_canvas = self.translate_coords(curr_pos)
  226. pos = self.fcapp.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  227. # Update cursor
  228. self.fcapp.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  229. symbol='++', edge_color=self.fcapp.cursor_color_3D,
  230. size=self.fcapp.defaults["global_cursor_size"])
  231. def new_text_group(self, collection=None):
  232. if collection:
  233. return TextGroup(collection)
  234. else:
  235. return TextGroup(self.text_collection)
  236. def new_text_collection(self, **kwargs):
  237. return TextCollection(parent=self.view.scene, **kwargs)
  238. def fit_view(self, rect=None):
  239. # Lock updates in other threads
  240. self.shape_collection.lock_updates()
  241. if not rect:
  242. rect = Rect(-1, -1, 20, 20)
  243. try:
  244. rect.left, rect.right = self.shape_collection.bounds(axis=0)
  245. rect.bottom, rect.top = self.shape_collection.bounds(axis=1)
  246. except TypeError:
  247. pass
  248. # adjust the view camera to be slightly bigger than the bounds so the shape colleaction can be seen clearly
  249. # otherwise the shape collection boundary will have no border
  250. rect.left *= 0.96
  251. rect.bottom *= 0.96
  252. rect.right *= 1.01
  253. rect.top *= 1.01
  254. self.view.camera.rect = rect
  255. self.shape_collection.unlock_updates()
  256. def fit_center(self, loc, rect=None):
  257. # Lock updates in other threads
  258. self.shape_collection.lock_updates()
  259. if not rect:
  260. try:
  261. rect = Rect(loc[0]-20, loc[1]-20, 40, 40)
  262. except TypeError:
  263. pass
  264. self.view.camera.rect = rect
  265. self.shape_collection.unlock_updates()
  266. def clear(self):
  267. pass
  268. def redraw(self):
  269. self.shape_collection.redraw([])
  270. self.text_collection.redraw()
  271. def on_pool_recreated(self, pool):
  272. self.shape_collection.pool = pool
  273. class CursorBig(QtCore.QObject):
  274. """
  275. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  276. This way I don't have to chane (disable) things related to the cursor all over when
  277. using the low performance Matplotlib 2D graphic engine.
  278. """
  279. mouse_state_updated = QtCore.pyqtSignal(bool)
  280. mouse_position_updated = QtCore.pyqtSignal(list)
  281. def __init__(self):
  282. super().__init__()
  283. self._enabled = None
  284. @property
  285. def enabled(self):
  286. return True if self._enabled else False
  287. @enabled.setter
  288. def enabled(self, value):
  289. self._enabled = value
  290. self.mouse_state_updated.emit(value)
  291. def set_data(self, pos, **kwargs):
  292. """Internal event handler to draw the cursor when the mouse moves."""
  293. if 'edge_color' in kwargs:
  294. color = kwargs['edge_color']
  295. else:
  296. if self.app.defaults['global_theme'] == 'white':
  297. color = '#000000FF'
  298. else:
  299. color = '#FFFFFFFF'
  300. position = [pos[0][0], pos[0][1]]
  301. self.mouse_position_updated.emit(position)