Common.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 11/4/2019 #
  11. # ##########################################################
  12. from PyQt5 import QtCore
  13. from shapely.geometry import Polygon, Point, LineString
  14. from shapely.ops import unary_union
  15. from appGUI.VisPyVisuals import ShapeCollection
  16. from appTool import AppTool
  17. from copy import deepcopy
  18. import collections
  19. import numpy as np
  20. # from voronoi import Voronoi
  21. # from voronoi import Polygon as voronoi_polygon
  22. import gettext
  23. import appTranslation as fcTranslate
  24. import builtins
  25. fcTranslate.apply_language('strings')
  26. if '_' not in builtins.__dict__:
  27. _ = gettext.gettext
  28. class GracefulException(Exception):
  29. """
  30. Graceful Exception raised when the user is requesting to cancel the current threaded task
  31. """
  32. def __init__(self):
  33. super().__init__()
  34. def __str__(self):
  35. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  36. class LoudDict(dict):
  37. """
  38. A Dictionary with a callback for item changes.
  39. """
  40. def __init__(self, *args, **kwargs):
  41. dict.__init__(self, *args, **kwargs)
  42. self.callback = lambda x: None
  43. def __setitem__(self, key, value):
  44. """
  45. Overridden __setitem__ method. Will emit 'changed(QString)' if the item was changed, with key as parameter.
  46. """
  47. if key in self and self.__getitem__(key) == value:
  48. return
  49. dict.__setitem__(self, key, value)
  50. self.callback(key)
  51. def update(self, *args, **kwargs):
  52. if len(args) > 1:
  53. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  54. other = dict(*args, **kwargs)
  55. for key in other:
  56. self[key] = other[key]
  57. def set_change_callback(self, callback):
  58. """
  59. Assigns a function as callback on item change. The callback
  60. will receive the key of the object that was changed.
  61. :param callback: Function to call on item change.
  62. :type callback: func
  63. :return: None
  64. """
  65. self.callback = callback
  66. # Fix for Python3.10
  67. MutableSequence = None
  68. try:
  69. MutableSequence = collections.MutableSequence
  70. except AttributeError:
  71. MutableSequence = collections.abc.MutableSequence
  72. class LoudUniqueList(list, MutableSequence):
  73. """
  74. A List with a callback for item changes, callback which returns the index where the items are added/modified.
  75. A List that will allow adding only items that are not in the list.
  76. """
  77. def __init__(self, arg=None):
  78. super().__init__()
  79. self.callback = lambda x: None
  80. if arg is not None:
  81. if isinstance(arg, list):
  82. self.extend(arg)
  83. else:
  84. self.extend([arg])
  85. def insert(self, i, v):
  86. if v in self:
  87. raise ValueError("One of the added items is already in the list.")
  88. self.callback(i)
  89. return super().insert(i, v)
  90. def append(self, v):
  91. if v in self:
  92. raise ValueError("One of the added items is already in the list.")
  93. le = len(self)
  94. self.callback(le)
  95. return super().append(v)
  96. def extend(self, t):
  97. for v in t:
  98. if v in self:
  99. raise ValueError("One of the added items is already in the list.")
  100. le = len(self)
  101. self.callback(le)
  102. return super().extend(t)
  103. def __add__(self, t): # This is for something like `LoudUniqueList([1, 2, 3]) + list([4, 5, 6])`...
  104. for v in t:
  105. if v in self:
  106. raise ValueError("One of the added items is already in the list.")
  107. le = len(self)
  108. self.callback(le)
  109. return super().__add__(t)
  110. def __iadd__(self, t): # This is for something like `l = LoudUniqueList(); l += [1, 2, 3]`
  111. for v in t:
  112. if v in self:
  113. raise ValueError("One of the added items is already in the list.")
  114. le = len(self)
  115. self.callback(le)
  116. return super().__iadd__(t)
  117. def __setitem__(self, i, v):
  118. try:
  119. for v1 in v:
  120. if v1 in self:
  121. raise ValueError("One of the modified items is already in the list.")
  122. except TypeError:
  123. if v in self:
  124. raise ValueError("One of the modified items is already in the list.")
  125. if v is not None:
  126. self.callback(i)
  127. return super().__setitem__(i, v)
  128. def set_callback(self, callback):
  129. """
  130. Assigns a function as callback on item change. The callback
  131. will receive the index of the object that was changed.
  132. :param callback: Function to call on item change.
  133. :type callback: func
  134. :return: None
  135. """
  136. self.callback = callback
  137. class FCSignal:
  138. """
  139. Taken from here: https://blog.abstractfactory.io/dynamic-signals-in-pyqt/
  140. """
  141. def __init__(self):
  142. self.__subscribers = []
  143. def emit(self, *args, **kwargs):
  144. for subs in self.__subscribers:
  145. subs(*args, **kwargs)
  146. def connect(self, func):
  147. self.__subscribers.append(func)
  148. def disconnect(self, func):
  149. try:
  150. self.__subscribers.remove(func)
  151. except ValueError:
  152. print('Warning: function %s not removed '
  153. 'from signal %s' % (func, self))
  154. def color_variant(hex_color, bright_factor=1):
  155. """
  156. Takes a color in HEX format #FF00FF and produces a lighter or darker variant
  157. :param hex_color: color to change
  158. :type hex_color: str
  159. :param bright_factor: factor to change the color brightness [0 ... 1]
  160. :type bright_factor: float
  161. :return: Modified color
  162. :rtype: str
  163. """
  164. if len(hex_color) != 7:
  165. print("Color is %s, but needs to be in #FF00FF format. Returning original color." % hex_color)
  166. return hex_color
  167. if bright_factor > 1.0:
  168. bright_factor = 1.0
  169. if bright_factor < 0.0:
  170. bright_factor = 0.0
  171. rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]]
  172. new_rgb = []
  173. for hex_value in rgb_hex:
  174. # adjust each color channel and turn it into a INT suitable as argument for hex()
  175. mod_color = round(int(hex_value, 16) * bright_factor)
  176. # make sure that each color channel has two digits without the 0x prefix
  177. mod_color_hex = str(hex(mod_color)[2:]).zfill(2)
  178. new_rgb.append(mod_color_hex)
  179. return "#" + "".join([i for i in new_rgb])
  180. class ExclusionAreas(QtCore.QObject):
  181. """
  182. Functionality for adding Exclusion Areas for the Excellon and Geometry FlatCAM Objects
  183. """
  184. e_shape_modified = QtCore.pyqtSignal()
  185. def __init__(self, app):
  186. super().__init__()
  187. self.app = app
  188. self.app.log.debug("+ Adding Exclusion Areas")
  189. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  190. # VisPy visuals
  191. if self.app.is_legacy is False:
  192. try:
  193. self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  194. except AttributeError:
  195. self.exclusion_shapes = None
  196. else:
  197. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  198. self.exclusion_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name="exclusion")
  199. # Event signals disconnect id holders
  200. self.mr = None
  201. self.mm = None
  202. self.kp = None
  203. # variables to be used in area exclusion
  204. self.cursor_pos = (0, 0)
  205. self.first_click = False
  206. self.points = []
  207. self.poly_drawn = False
  208. '''
  209. Here we store the exclusion shapes and some other information's
  210. Each list element is a dictionary with the format:
  211. {
  212. "obj_type": string ("excellon" or "geometry") <- self.obj_type
  213. "shape": Shapely polygon
  214. "strategy": string ("over" or "around") <- self.strategy_button
  215. "overz": float <- self.over_z_button
  216. }
  217. '''
  218. self.exclusion_areas_storage = []
  219. self.mouse_is_dragging = False
  220. self.solid_geometry = []
  221. self.obj_type = None
  222. self.shape_type_button = None
  223. self.over_z_button = None
  224. self.strategy_button = None
  225. self.cnc_button = None
  226. def on_add_area_click(self, shape_button, overz_button, strategy_radio, cnc_button, solid_geo, obj_type):
  227. """
  228. :param shape_button: a FCButton that has the value for the shape
  229. :param overz_button: a FCDoubleSpinner that holds the Over Z value
  230. :param strategy_radio: a RadioSet button with the strategy_button value
  231. :param cnc_button: a FCButton in Object UI that when clicked the CNCJob is created
  232. We have a reference here so we can change the color signifying that exclusion areas are
  233. available.
  234. :param solid_geo: reference to the object solid geometry for which we add exclusion areas
  235. :param obj_type: Type of FlatCAM object that called this method. String: "excellon" or "geometry"
  236. :type obj_type: str
  237. :return: None
  238. """
  239. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  240. self.app.call_source = 'geometry'
  241. self.shape_type_button = shape_button
  242. self.over_z_button = overz_button
  243. self.strategy_button = strategy_radio
  244. self.cnc_button = cnc_button
  245. self.solid_geometry = solid_geo
  246. self.obj_type = obj_type
  247. if self.app.is_legacy is False:
  248. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  249. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  250. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  251. else:
  252. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  253. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  254. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  255. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  256. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  257. # self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  258. # To be called after clicking on the plot.
  259. def on_mouse_release(self, event):
  260. """
  261. Called on mouse click release.
  262. :param event: Mouse event
  263. :type event:
  264. :return: None
  265. :rtype:
  266. """
  267. if self.app.is_legacy is False:
  268. event_pos = event.pos
  269. # event_is_dragging = event.is_dragging
  270. right_button = 2
  271. else:
  272. event_pos = (event.xdata, event.ydata)
  273. # event_is_dragging = self.app.plotcanvas.is_dragging
  274. right_button = 3
  275. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  276. if self.app.grid_status():
  277. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  278. else:
  279. curr_pos = (event_pos[0], event_pos[1])
  280. x1, y1 = curr_pos[0], curr_pos[1]
  281. # shape_type_button = self.ui.area_shape_radio.get_value()
  282. # do clear area only for left mouse clicks
  283. if event.button == 1:
  284. if self.shape_type_button.get_value() == "square":
  285. if self.first_click is False:
  286. self.first_click = True
  287. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  288. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  289. if self.app.grid_status():
  290. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  291. else:
  292. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  293. self.app.delete_selection_shape()
  294. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  295. pt1 = (x0, y0)
  296. pt2 = (x1, y0)
  297. pt3 = (x1, y1)
  298. pt4 = (x0, y1)
  299. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  300. # {
  301. # "obj_type": string("excellon" or "geometry") < - self.obj_type
  302. # "shape": Shapely polygon
  303. # "strategy_button": string("over" or "around") < - self.strategy_button
  304. # "overz": float < - self.over_z_button
  305. # }
  306. new_el = {
  307. "obj_type": self.obj_type,
  308. "shape": new_rectangle,
  309. "strategy": self.strategy_button.get_value(),
  310. "overz": self.over_z_button.get_value()
  311. }
  312. self.exclusion_areas_storage.append(new_el)
  313. if self.obj_type == 'excellon':
  314. color = "#FF7400"
  315. face_color = "#FF7400BF"
  316. else:
  317. color = "#098a8f"
  318. face_color = "#FF7400BF"
  319. # add a temporary shape on canvas
  320. AppTool.draw_tool_selection_shape(
  321. self, old_coords=(x0, y0), coords=(x1, y1),
  322. color=color,
  323. face_color=face_color,
  324. shapes_storage=self.exclusion_shapes)
  325. self.first_click = False
  326. return
  327. else:
  328. self.points.append((x1, y1))
  329. if len(self.points) > 1:
  330. self.poly_drawn = True
  331. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  332. return ""
  333. elif event.button == right_button and self.mouse_is_dragging is False:
  334. shape_type = self.shape_type_button.get_value()
  335. if shape_type == "square":
  336. self.first_click = False
  337. else:
  338. # if we finish to add a polygon
  339. if self.poly_drawn is True:
  340. try:
  341. # try to add the point where we last clicked if it is not already in the self.points
  342. last_pt = (x1, y1)
  343. if last_pt != self.points[-1]:
  344. self.points.append(last_pt)
  345. except IndexError:
  346. pass
  347. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  348. if len(self.points) > 2:
  349. AppTool.delete_moving_selection_shape(self)
  350. pol = Polygon(self.points)
  351. # do not add invalid polygons even if they are drawn by utility geometry
  352. if pol.is_valid:
  353. """
  354. {
  355. "obj_type": string("excellon" or "geometry") < - self.obj_type
  356. "shape": Shapely polygon
  357. "strategy": string("over" or "around") < - self.strategy_button
  358. "overz": float < - self.over_z_button
  359. }
  360. """
  361. new_el = {
  362. "obj_type": self.obj_type,
  363. "shape": pol,
  364. "strategy": self.strategy_button.get_value(),
  365. "overz": self.over_z_button.get_value()
  366. }
  367. self.exclusion_areas_storage.append(new_el)
  368. if self.obj_type == 'excellon':
  369. color = "#FF7400"
  370. face_color = "#FF7400BF"
  371. else:
  372. color = "#098a8f"
  373. face_color = "#FF7400BF"
  374. AppTool.draw_selection_shape_polygon(
  375. self, points=self.points,
  376. color=color,
  377. face_color=face_color,
  378. shapes_storage=self.exclusion_shapes)
  379. self.app.inform.emit(
  380. _("Zone added. Click to start adding next zone or right click to finish."))
  381. self.points = []
  382. self.poly_drawn = False
  383. return
  384. # AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  385. if self.app.is_legacy is False:
  386. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  387. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  388. # self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  389. else:
  390. self.app.plotcanvas.graph_event_disconnect(self.mr)
  391. self.app.plotcanvas.graph_event_disconnect(self.mm)
  392. # self.app.plotcanvas.graph_event_disconnect(self.kp)
  393. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  394. self.app.on_mouse_click_over_plot)
  395. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  396. self.app.on_mouse_move_over_plot)
  397. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  398. self.app.on_mouse_click_release_over_plot)
  399. self.app.call_source = 'app'
  400. if len(self.exclusion_areas_storage) == 0:
  401. return
  402. # since the exclusion areas should apply to all objects in the app collection, this check is limited to
  403. # only the current object therefore it will not guarantee success
  404. self.app.inform.emit("%s" % _("Exclusion areas added. Checking overlap with the object geometry ..."))
  405. for el in self.exclusion_areas_storage:
  406. if el["shape"].intersects(unary_union(self.solid_geometry)):
  407. self.on_clear_area_click()
  408. self.app.inform.emit(
  409. "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ..."))
  410. return
  411. self.app.inform.emit("[success] %s" % _("Exclusion areas added."))
  412. self.cnc_button.setStyleSheet("""
  413. QPushButton
  414. {
  415. font-weight: bold;
  416. color: orange;
  417. }
  418. """)
  419. self.cnc_button.setToolTip(
  420. '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas."))
  421. )
  422. self.e_shape_modified.emit()
  423. def area_disconnect(self):
  424. """
  425. Will do the cleanup. Will disconnect the mouse events for the custom handlers in this class and initialize
  426. certain class attributes.
  427. :return: None
  428. :rtype:
  429. """
  430. if self.app.is_legacy is False:
  431. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  432. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  433. else:
  434. self.app.plotcanvas.graph_event_disconnect(self.mr)
  435. self.app.plotcanvas.graph_event_disconnect(self.mm)
  436. self.app.plotcanvas.graph_event_disconnect(self.kp)
  437. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  438. self.app.on_mouse_click_over_plot)
  439. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  440. self.app.on_mouse_move_over_plot)
  441. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  442. self.app.on_mouse_click_release_over_plot)
  443. self.points = []
  444. self.poly_drawn = False
  445. self.exclusion_areas_storage = []
  446. AppTool.delete_moving_selection_shape(self)
  447. # AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  448. self.app.call_source = "app"
  449. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted."))
  450. def on_mouse_move(self, event):
  451. """
  452. Called on mouse move
  453. :param event: mouse event
  454. :type event:
  455. :return: None
  456. :rtype:
  457. """
  458. shape_type = self.shape_type_button.get_value()
  459. if self.app.is_legacy is False:
  460. event_pos = event.pos
  461. event_is_dragging = event.is_dragging
  462. # right_button = 2
  463. else:
  464. event_pos = (event.xdata, event.ydata)
  465. event_is_dragging = self.app.plotcanvas.is_dragging
  466. # right_button = 3
  467. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  468. # detect mouse dragging motion
  469. if event_is_dragging is True:
  470. self.mouse_is_dragging = True
  471. else:
  472. self.mouse_is_dragging = False
  473. # update the cursor position
  474. if self.app.grid_status():
  475. # Update cursor
  476. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  477. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  478. symbol='++', edge_color=self.app.cursor_color_3D,
  479. edge_width=self.app.defaults["global_cursor_width"],
  480. size=self.app.defaults["global_cursor_size"])
  481. # update the positions on status bar
  482. if self.cursor_pos is None:
  483. self.cursor_pos = (0, 0)
  484. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  485. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  486. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  487. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  488. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  489. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  490. units = self.app.defaults["units"].lower()
  491. self.app.plotcanvas.text_hud.text = \
  492. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  493. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  494. if self.obj_type == 'excellon':
  495. color = "#FF7400"
  496. face_color = "#FF7400BF"
  497. else:
  498. color = "#098a8f"
  499. face_color = "#FF7400BF"
  500. # draw the utility geometry
  501. if shape_type == "square":
  502. if self.first_click:
  503. self.app.delete_selection_shape()
  504. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  505. color=color,
  506. face_color=face_color,
  507. coords=(curr_pos[0], curr_pos[1]))
  508. else:
  509. AppTool.delete_moving_selection_shape(self)
  510. AppTool.draw_moving_selection_shape_poly(
  511. self, points=self.points,
  512. color=color,
  513. face_color=face_color,
  514. data=(curr_pos[0], curr_pos[1]))
  515. def on_clear_area_click(self):
  516. """
  517. Slot for clicking the button for Deleting all the Exclusion areas.
  518. :return: None
  519. :rtype:
  520. """
  521. self.clear_shapes()
  522. # restore the default StyleSheet
  523. self.cnc_button.setStyleSheet("")
  524. # update the StyleSheet
  525. self.cnc_button.setStyleSheet("""
  526. QPushButton
  527. {
  528. font-weight: bold;
  529. }
  530. """)
  531. self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object."))
  532. def clear_shapes(self):
  533. """
  534. Will delete all the Exclusion areas; will delete on canvas any possible selection box for the Exclusion areas.
  535. :return: None
  536. :rtype:
  537. """
  538. if self.exclusion_areas_storage:
  539. self.app.inform.emit('%s' % _("All exclusion zones deleted."))
  540. self.exclusion_areas_storage.clear()
  541. AppTool.delete_moving_selection_shape(self)
  542. self.app.delete_selection_shape()
  543. AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  544. def delete_sel_shapes(self, idxs):
  545. """
  546. :param idxs: list of indexes in self.exclusion_areas_storage list to be deleted
  547. :type idxs: list
  548. :return: None
  549. """
  550. # delete all plotted shapes
  551. AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  552. # delete shapes
  553. for idx in sorted(idxs, reverse=True):
  554. del self.exclusion_areas_storage[idx]
  555. # re-add what's left after deletion in first step
  556. if self.obj_type == 'excellon':
  557. color = "#FF7400"
  558. face_color = "#FF7400BF"
  559. else:
  560. color = "#098a8f"
  561. face_color = "#FF7400BF"
  562. face_alpha = 0.3
  563. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  564. for geo_el in self.exclusion_areas_storage:
  565. if isinstance(geo_el['shape'], Polygon):
  566. self.exclusion_shapes.add(
  567. geo_el['shape'], color=color, face_color=color_t, update=True, layer=0, tolerance=None)
  568. if self.app.is_legacy is True:
  569. self.exclusion_shapes.redraw()
  570. # if there are still some exclusion areas in the storage
  571. if self.exclusion_areas_storage:
  572. self.app.inform.emit('[success] %s' % _("Selected exclusion zones deleted."))
  573. else:
  574. # restore the default StyleSheet
  575. self.cnc_button.setStyleSheet("")
  576. # update the StyleSheet
  577. self.cnc_button.setStyleSheet("""
  578. QPushButton
  579. {
  580. font-weight: bold;
  581. }
  582. """)
  583. self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object."))
  584. # there are no more exclusion areas in the storage, all have been selected and deleted
  585. self.app.inform.emit('%s' % _("All exclusion zones deleted."))
  586. def travel_coordinates(self, start_point, end_point, tooldia):
  587. """
  588. WIll create a path the go around the exclusion areas on the shortest path when travelling (at a Z above the
  589. material).
  590. :param start_point: X,Y coordinates for the start point of the travel line
  591. :type start_point: tuple
  592. :param end_point: X,Y coordinates for the destination point of the travel line
  593. :type end_point: tuple
  594. :param tooldia: THe tool diameter used and which generates the travel lines
  595. :type tooldia float
  596. :return: A list of x,y tuples that describe the avoiding path
  597. :rtype: list
  598. """
  599. ret_list = []
  600. # Travel lines: rapids. Should not pass through Exclusion areas
  601. travel_line = LineString([start_point, end_point])
  602. origin_point = Point(start_point)
  603. buffered_storage = []
  604. # add a little something to the half diameter, to make sure that we really don't enter in the exclusion zones
  605. buffered_distance = (tooldia / 2.0) + (0.1 if self.app.defaults['units'] == 'MM' else 0.00393701)
  606. for area in self.exclusion_areas_storage:
  607. new_area = deepcopy(area)
  608. new_area['shape'] = area['shape'].buffer(buffered_distance, join_style=2)
  609. buffered_storage.append(new_area)
  610. # sort the Exclusion areas from the closest to the start_point to the farthest
  611. tmp = []
  612. for area in buffered_storage:
  613. dist = Point(start_point).distance(area['shape'])
  614. tmp.append((dist, area))
  615. tmp.sort(key=lambda k: k[0])
  616. sorted_area_storage = [k[1] for k in tmp]
  617. # process the ordered exclusion areas list
  618. for area in sorted_area_storage:
  619. outline = area['shape'].exterior
  620. if travel_line.intersects(outline):
  621. intersection_pts = travel_line.intersection(outline)
  622. if isinstance(intersection_pts, Point):
  623. # it's just a touch, continue
  624. continue
  625. entry_pt = nearest_point(origin_point, intersection_pts)
  626. exit_pt = farthest_point(origin_point, intersection_pts)
  627. if area['strategy'] == 'around':
  628. full_vertex_points = [Point(x) for x in list(outline.coords)]
  629. # the last coordinate in outline, a LinearRing, is the closing one
  630. # therefore a duplicate of the first one; discard it
  631. vertex_points = full_vertex_points[:-1]
  632. # dist_from_entry = [(entry_pt.distance(vt), vertex_points.index(vt)) for vt in vertex_points]
  633. # closest_point_entry = nsmallest(1, dist_from_entry, key=lambda x: x[0])
  634. # start_idx = closest_point_entry[0][1]
  635. #
  636. # dist_from_exit = [(exit_pt.distance(vt), vertex_points.index(vt)) for vt in vertex_points]
  637. # closest_point_exit = nsmallest(1, dist_from_exit, key=lambda x: x[0])
  638. # end_idx = closest_point_exit[0][1]
  639. # pts_line_entry = None
  640. # pts_line_exit = None
  641. # for i in range(len(full_vertex_points)):
  642. # try:
  643. # line = LineString(
  644. # [
  645. # (full_vertex_points[i].x, full_vertex_points[i].y),
  646. # (full_vertex_points[i + 1].x, full_vertex_points[i + 1].y)
  647. # ]
  648. # )
  649. # except IndexError:
  650. # continue
  651. #
  652. # if entry_pt.within(line) or entry_pt.equals(Point(line.coords[0])) or \
  653. # entry_pt.equals(Point(line.coords[1])):
  654. # pts_line_entry = [Point(x) for x in line.coords]
  655. #
  656. # if exit_pt.within(line) or exit_pt.equals(Point(line.coords[0])) or \
  657. # exit_pt.equals(Point(line.coords[1])):
  658. # pts_line_exit = [Point(x) for x in line.coords]
  659. #
  660. # closest_point_entry = nearest_point(entry_pt, pts_line_entry)
  661. # start_idx = vertex_points.index(closest_point_entry)
  662. #
  663. # closest_point_exit = nearest_point(exit_pt, pts_line_exit)
  664. # end_idx = vertex_points.index(closest_point_exit)
  665. # find all vertexes for which a line from start_point does not cross the Exclusion area polygon
  666. # the same for end_point
  667. # we don't need closest points for which the path leads to crosses of the Exclusion area
  668. close_start_points = []
  669. close_end_points = []
  670. for i in range(len(vertex_points)):
  671. try:
  672. start_line = LineString(
  673. [
  674. start_point,
  675. (vertex_points[i].x, vertex_points[i].y)
  676. ]
  677. )
  678. end_line = LineString(
  679. [
  680. end_point,
  681. (vertex_points[i].x, vertex_points[i].y)
  682. ]
  683. )
  684. except IndexError:
  685. continue
  686. if not start_line.crosses(area['shape']):
  687. close_start_points.append(vertex_points[i])
  688. if not end_line.crosses(area['shape']):
  689. close_end_points.append(vertex_points[i])
  690. closest_point_entry = nearest_point(entry_pt, close_start_points)
  691. closest_point_exit = nearest_point(exit_pt, close_end_points)
  692. start_idx = vertex_points.index(closest_point_entry)
  693. end_idx = vertex_points.index(closest_point_exit)
  694. # calculate possible paths: one clockwise the other counterclockwise on the exterior of the
  695. # exclusion area outline (Polygon.exterior)
  696. vp_len = len(vertex_points)
  697. if end_idx > start_idx:
  698. path_1 = vertex_points[start_idx:(end_idx + 1)]
  699. path_2 = [vertex_points[start_idx]]
  700. idx = start_idx
  701. for __ in range(vp_len):
  702. idx = idx - 1 if idx > 0 else (vp_len - 1)
  703. path_2.append(vertex_points[idx])
  704. if idx == end_idx:
  705. break
  706. else:
  707. path_1 = vertex_points[end_idx:(start_idx + 1)]
  708. path_2 = [vertex_points[end_idx]]
  709. idx = end_idx
  710. for __ in range(vp_len):
  711. idx = idx - 1 if idx > 0 else (vp_len - 1)
  712. path_2.append(vertex_points[idx])
  713. if idx == start_idx:
  714. break
  715. path_1.reverse()
  716. path_2.reverse()
  717. # choose the one with the lesser length
  718. length_path_1 = 0
  719. for i in range(len(path_1)):
  720. try:
  721. length_path_1 += path_1[i].distance(path_1[i + 1])
  722. except IndexError:
  723. pass
  724. length_path_2 = 0
  725. for i in range(len(path_2)):
  726. try:
  727. length_path_2 += path_2[i].distance(path_2[i + 1])
  728. except IndexError:
  729. pass
  730. path = path_1 if length_path_1 < length_path_2 else path_2
  731. # transform the list of Points into a list of Points coordinates
  732. path_coords = [[None, (p.x, p.y)] for p in path]
  733. ret_list += path_coords
  734. else:
  735. path_coords = [[float(area['overz']), (entry_pt.x, entry_pt.y)], [None, (exit_pt.x, exit_pt.y)]]
  736. ret_list += path_coords
  737. # create a new LineString to test again for possible other Exclusion zones
  738. last_pt_in_path = path_coords[-1][1]
  739. travel_line = LineString([last_pt_in_path, end_point])
  740. ret_list.append([None, end_point])
  741. return ret_list
  742. def farthest_point(origin, points_list):
  743. """
  744. Calculate the farthest Point in a list from another Point
  745. :param origin: Reference Point
  746. :type origin: Point
  747. :param points_list: List of Points or a MultiPoint
  748. :type points_list: list
  749. :return: Farthest Point
  750. :rtype: Point
  751. """
  752. old_dist = 0
  753. fartherst_pt = None
  754. for pt in points_list:
  755. dist = abs(origin.distance(pt))
  756. if dist >= old_dist:
  757. fartherst_pt = pt
  758. old_dist = dist
  759. return fartherst_pt
  760. # def voronoi_diagram(geom, envelope, edges=False):
  761. # """
  762. #
  763. # :param geom: a collection of Shapely Points from which to build the Voronoi diagram
  764. # :type geom: MultiPoint
  765. # :param envelope: a bounding box to constrain the diagram (Shapely Polygon)
  766. # :type envelope: Polygon
  767. # :param edges: If False, return regions as polygons. Else, return only
  768. # edges e.g. LineStrings.
  769. # :type edges: bool, False
  770. # :return:
  771. # :rtype:
  772. # """
  773. #
  774. # if not isinstance(geom, MultiPoint):
  775. # return False
  776. #
  777. # coords = list(envelope.exterior.coords)
  778. # v_poly = voronoi_polygon(coords)
  779. #
  780. # vp = Voronoi(v_poly)
  781. #
  782. # points = []
  783. # for pt in geom:
  784. # points.append((pt.x, pt.y))
  785. # vp.create_diagram(points=points, vis_steps=False, verbose=False, vis_result=False, vis_tree=False)
  786. #
  787. # if edges is True:
  788. # return vp.edges
  789. # else:
  790. # voronoi_polygons = []
  791. # for pt in vp.points:
  792. # try:
  793. # poly_coords = list(pt.get_coordinates())
  794. # new_poly_coords = []
  795. # for coord in poly_coords:
  796. # new_poly_coords.append((coord.x, coord.y))
  797. #
  798. # voronoi_polygons.append(Polygon(new_poly_coords))
  799. # except Exception:
  800. # print(traceback.format_exc())
  801. #
  802. # return voronoi_polygons
  803. def nearest_point(origin, points_list):
  804. """
  805. Calculate the nearest Point in a list from another Point
  806. :param origin: Reference Point
  807. :type origin: Point
  808. :param points_list: List of Points or a MultiPoint
  809. :type points_list: list
  810. :return: Nearest Point
  811. :rtype: Point
  812. """
  813. old_dist = np.Inf
  814. nearest_pt = None
  815. for pt in points_list:
  816. dist = abs(origin.distance(pt))
  817. if dist <= old_dist:
  818. nearest_pt = pt
  819. old_dist = dist
  820. return nearest_pt