FlatCAMDraw.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. from PyQt4 import QtGui, QtCore, Qt
  2. import FlatCAMApp
  3. from camlib import *
  4. from shapely.geometry import Polygon, LineString, Point, LinearRing
  5. from shapely.geometry import MultiPoint, MultiPolygon
  6. from shapely.geometry import box as shply_box
  7. from shapely.ops import cascaded_union, unary_union
  8. import shapely.affinity as affinity
  9. from shapely.wkt import loads as sloads
  10. from shapely.wkt import dumps as sdumps
  11. from shapely.geometry.base import BaseGeometry
  12. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot
  13. from numpy.linalg import solve
  14. from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea
  15. from rtree import index as rtindex
  16. class DrawToolShape(object):
  17. @staticmethod
  18. def get_pts(o):
  19. """
  20. Returns a list of all points in the object, where
  21. the object can be a Polygon, Not a polygon, or a list
  22. of such. Search is done recursively.
  23. :param: geometric object
  24. :return: List of points
  25. :rtype: list
  26. """
  27. pts = []
  28. ## Iterable: descend into each item.
  29. try:
  30. for subo in o:
  31. pts += DrawToolShape.get_pts(subo)
  32. ## Non-iterable
  33. except TypeError:
  34. ## DrawToolShape: descend into .geo.
  35. if isinstance(o, DrawToolShape):
  36. pts += DrawToolShape.get_pts(o.geo)
  37. ## Descend into .exerior and .interiors
  38. elif type(o) == Polygon:
  39. pts += DrawToolShape.get_pts(o.exterior)
  40. for i in o.interiors:
  41. pts += DrawToolShape.get_pts(i)
  42. ## Has .coords: list them.
  43. else:
  44. pts += list(o.coords)
  45. return pts
  46. def __init__(self, geo=[]):
  47. # Shapely type or list of such
  48. self.geo = geo
  49. self.utility = False
  50. def get_all_points(self):
  51. return DrawToolShape.get_pts(self)
  52. class DrawToolUtilityShape(DrawToolShape):
  53. def __init__(self, geo=[]):
  54. super(DrawToolUtilityShape, self).__init__(geo=geo)
  55. self.utility = True
  56. class DrawTool(object):
  57. """
  58. Abstract Class representing a tool in the drawing
  59. program. Can generate geometry, including temporary
  60. utility geometry that is updated on user clicks
  61. and mouse motion.
  62. """
  63. def __init__(self, draw_app):
  64. self.draw_app = draw_app
  65. self.complete = False
  66. self.start_msg = "Click on 1st point..."
  67. self.points = []
  68. self.geometry = None # DrawToolShape or None
  69. def click(self, point):
  70. """
  71. :param point: [x, y] Coordinate pair.
  72. """
  73. return ""
  74. def on_key(self, key):
  75. return None
  76. def utility_geometry(self, data=None):
  77. return None
  78. class FCShapeTool(DrawTool):
  79. def __init__(self, draw_app):
  80. DrawTool.__init__(self, draw_app)
  81. def make(self):
  82. pass
  83. class FCCircle(FCShapeTool):
  84. """
  85. Resulting type: Polygon
  86. """
  87. def __init__(self, draw_app):
  88. DrawTool.__init__(self, draw_app)
  89. self.start_msg = "Click on CENTER ..."
  90. def click(self, point):
  91. self.points.append(point)
  92. if len(self.points) == 1:
  93. return "Click on perimeter to complete ..."
  94. if len(self.points) == 2:
  95. self.make()
  96. return "Done."
  97. return ""
  98. def utility_geometry(self, data=None):
  99. if len(self.points) == 1:
  100. p1 = self.points[0]
  101. p2 = data
  102. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  103. return DrawToolUtilityShape(Point(p1).buffer(radius))
  104. return None
  105. def make(self):
  106. p1 = self.points[0]
  107. p2 = self.points[1]
  108. radius = distance(p1, p2)
  109. self.geometry = DrawToolShape(Point(p1).buffer(radius))
  110. self.complete = True
  111. class FCArc(FCShapeTool):
  112. def __init__(self, draw_app):
  113. DrawTool.__init__(self, draw_app)
  114. self.start_msg = "Click on CENTER ..."
  115. # Direction of rotation between point 1 and 2.
  116. # 'cw' or 'ccw'. Switch direction by hitting the
  117. # 'o' key.
  118. self.direction = "cw"
  119. # Mode
  120. # C12 = Center, p1, p2
  121. # 12C = p1, p2, Center
  122. # 132 = p1, p3, p2
  123. self.mode = "c12" # Center, p1, p2
  124. self.steps_per_circ = 55
  125. def click(self, point):
  126. self.points.append(point)
  127. if len(self.points) == 1:
  128. return "Click on 1st point ..."
  129. if len(self.points) == 2:
  130. return "Click on 2nd point to complete ..."
  131. if len(self.points) == 3:
  132. self.make()
  133. return "Done."
  134. return ""
  135. def on_key(self, key):
  136. if key == 'o':
  137. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  138. return 'Direction: ' + self.direction.upper()
  139. if key == 'p':
  140. if self.mode == 'c12':
  141. self.mode = '12c'
  142. elif self.mode == '12c':
  143. self.mode = '132'
  144. else:
  145. self.mode = 'c12'
  146. return 'Mode: ' + self.mode
  147. def utility_geometry(self, data=None):
  148. if len(self.points) == 1: # Show the radius
  149. center = self.points[0]
  150. p1 = data
  151. return DrawToolUtilityShape(LineString([center, p1]))
  152. if len(self.points) == 2: # Show the arc
  153. if self.mode == 'c12':
  154. center = self.points[0]
  155. p1 = self.points[1]
  156. p2 = data
  157. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  158. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  159. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  160. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  161. self.direction, self.steps_per_circ)),
  162. Point(center)])
  163. elif self.mode == '132':
  164. p1 = array(self.points[0])
  165. p3 = array(self.points[1])
  166. p2 = array(data)
  167. center, radius, t = three_point_circle(p1, p2, p3)
  168. direction = 'cw' if sign(t) > 0 else 'ccw'
  169. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  170. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  171. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  172. direction, self.steps_per_circ)),
  173. Point(center), Point(p1), Point(p3)])
  174. else: # '12c'
  175. p1 = array(self.points[0])
  176. p2 = array(self.points[1])
  177. # Midpoint
  178. a = (p1 + p2) / 2.0
  179. # Parallel vector
  180. c = p2 - p1
  181. # Perpendicular vector
  182. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  183. b /= norm(b)
  184. # Distance
  185. t = distance(data, a)
  186. # Which side? Cross product with c.
  187. # cross(M-A, B-A), where line is AB and M is test point.
  188. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  189. t *= sign(side)
  190. # Center = a + bt
  191. center = a + b * t
  192. radius = norm(center - p1)
  193. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  194. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  195. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  196. self.direction, self.steps_per_circ)),
  197. Point(center)])
  198. return None
  199. def make(self):
  200. if self.mode == 'c12':
  201. center = self.points[0]
  202. p1 = self.points[1]
  203. p2 = self.points[2]
  204. radius = distance(center, p1)
  205. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  206. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  207. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  208. self.direction, self.steps_per_circ)))
  209. elif self.mode == '132':
  210. p1 = array(self.points[0])
  211. p3 = array(self.points[1])
  212. p2 = array(self.points[2])
  213. center, radius, t = three_point_circle(p1, p2, p3)
  214. direction = 'cw' if sign(t) > 0 else 'ccw'
  215. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  216. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  217. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  218. direction, self.steps_per_circ)))
  219. else: # self.mode == '12c'
  220. p1 = array(self.points[0])
  221. p2 = array(self.points[1])
  222. pc = array(self.points[2])
  223. # Midpoint
  224. a = (p1 + p2) / 2.0
  225. # Parallel vector
  226. c = p2 - p1
  227. # Perpendicular vector
  228. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  229. b /= norm(b)
  230. # Distance
  231. t = distance(pc, a)
  232. # Which side? Cross product with c.
  233. # cross(M-A, B-A), where line is AB and M is test point.
  234. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  235. t *= sign(side)
  236. # Center = a + bt
  237. center = a + b * t
  238. radius = norm(center - p1)
  239. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  240. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  241. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  242. self.direction, self.steps_per_circ)))
  243. self.complete = True
  244. class FCRectangle(FCShapeTool):
  245. """
  246. Resulting type: Polygon
  247. """
  248. def __init__(self, draw_app):
  249. DrawTool.__init__(self, draw_app)
  250. self.start_msg = "Click on 1st corner ..."
  251. def click(self, point):
  252. self.points.append(point)
  253. if len(self.points) == 1:
  254. return "Click on opposite corner to complete ..."
  255. if len(self.points) == 2:
  256. self.make()
  257. return "Done."
  258. return ""
  259. def utility_geometry(self, data=None):
  260. if len(self.points) == 1:
  261. p1 = self.points[0]
  262. p2 = data
  263. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  264. return None
  265. def make(self):
  266. p1 = self.points[0]
  267. p2 = self.points[1]
  268. #self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  269. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  270. self.complete = True
  271. class FCPolygon(FCShapeTool):
  272. """
  273. Resulting type: Polygon
  274. """
  275. def __init__(self, draw_app):
  276. DrawTool.__init__(self, draw_app)
  277. self.start_msg = "Click on 1st point ..."
  278. def click(self, point):
  279. self.points.append(point)
  280. if len(self.points) > 0:
  281. return "Click on next point or hit SPACE to complete ..."
  282. return ""
  283. def utility_geometry(self, data=None):
  284. if len(self.points) == 1:
  285. temp_points = [x for x in self.points]
  286. temp_points.append(data)
  287. return DrawToolUtilityShape(LineString(temp_points))
  288. if len(self.points) > 1:
  289. temp_points = [x for x in self.points]
  290. temp_points.append(data)
  291. return DrawToolUtilityShape(LinearRing(temp_points))
  292. return None
  293. def make(self):
  294. # self.geometry = LinearRing(self.points)
  295. self.geometry = DrawToolShape(Polygon(self.points))
  296. self.complete = True
  297. class FCPath(FCPolygon):
  298. """
  299. Resulting type: LineString
  300. """
  301. def make(self):
  302. self.geometry = DrawToolShape(LineString(self.points))
  303. self.complete = True
  304. def utility_geometry(self, data=None):
  305. if len(self.points) > 1:
  306. temp_points = [x for x in self.points]
  307. temp_points.append(data)
  308. return DrawToolUtilityShape(LineString(temp_points))
  309. return None
  310. class FCSelect(DrawTool):
  311. def __init__(self, draw_app):
  312. DrawTool.__init__(self, draw_app)
  313. self.storage = self.draw_app.storage
  314. #self.shape_buffer = self.draw_app.shape_buffer
  315. self.selected = self.draw_app.selected
  316. self.start_msg = "Click on geometry to select"
  317. def click(self, point):
  318. _, closest_shape = self.storage.nearest(point)
  319. if self.draw_app.key != 'control':
  320. self.draw_app.selected = []
  321. self.draw_app.set_selected(closest_shape)
  322. return ""
  323. class FCMove(FCShapeTool):
  324. def __init__(self, draw_app):
  325. FCShapeTool.__init__(self, draw_app)
  326. #self.shape_buffer = self.draw_app.shape_buffer
  327. self.origin = None
  328. self.destination = None
  329. self.start_msg = "Click on reference point."
  330. def set_origin(self, origin):
  331. self.origin = origin
  332. def click(self, point):
  333. if len(self.draw_app.get_selected()) == 0:
  334. return "Nothing to move."
  335. if self.origin is None:
  336. self.set_origin(point)
  337. return "Click on final location."
  338. else:
  339. self.destination = point
  340. self.make()
  341. return "Done."
  342. def make(self):
  343. # Create new geometry
  344. dx = self.destination[0] - self.origin[0]
  345. dy = self.destination[1] - self.origin[1]
  346. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  347. for geom in self.draw_app.get_selected()]
  348. # Delete old
  349. self.draw_app.delete_selected()
  350. # # Select the new
  351. # for g in self.geometry:
  352. # # Note that g is not in the app's buffer yet!
  353. # self.draw_app.set_selected(g)
  354. self.complete = True
  355. def utility_geometry(self, data=None):
  356. """
  357. Temporary geometry on screen while using this tool.
  358. :param data:
  359. :return:
  360. """
  361. if self.origin is None:
  362. return None
  363. if len(self.draw_app.get_selected()) == 0:
  364. return None
  365. dx = data[0] - self.origin[0]
  366. dy = data[1] - self.origin[1]
  367. return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  368. for geom in self.draw_app.get_selected()])
  369. class FCCopy(FCMove):
  370. def make(self):
  371. # Create new geometry
  372. dx = self.destination[0] - self.origin[0]
  373. dy = self.destination[1] - self.origin[1]
  374. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  375. for geom in self.draw_app.get_selected()]
  376. self.complete = True
  377. ########################
  378. ### Main Application ###
  379. ########################
  380. class FlatCAMDraw(QtCore.QObject):
  381. def __init__(self, app, disabled=False):
  382. assert isinstance(app, FlatCAMApp.App)
  383. super(FlatCAMDraw, self).__init__()
  384. self.app = app
  385. self.canvas = app.plotcanvas
  386. self.axes = self.canvas.new_axes("draw")
  387. ### Drawing Toolbar ###
  388. self.drawing_toolbar = QtGui.QToolBar()
  389. self.drawing_toolbar.setDisabled(disabled)
  390. self.app.ui.addToolBar(self.drawing_toolbar)
  391. self.select_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/pointer32.png'), 'Select')
  392. self.add_circle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/circle32.png'), 'Add Circle')
  393. self.add_arc_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/arc32.png'), 'Add Arc')
  394. self.add_rectangle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/rectangle32.png'), 'Add Rectangle')
  395. self.add_polygon_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/polygon32.png'), 'Add Polygon')
  396. self.add_path_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/path32.png'), 'Add Path')
  397. self.union_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/union32.png'), 'Polygon Union')
  398. self.subtract_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/subtract32.png'), 'Polygon Subtraction')
  399. self.cutpath_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/cutpath32.png'), 'Cut Path')
  400. self.move_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/move32.png'), 'Move Objects')
  401. self.copy_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/copy32.png'), 'Copy Objects')
  402. ### Snap Toolbar ###
  403. self.snap_toolbar = QtGui.QToolBar()
  404. self.grid_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/grid32.png'), 'Snap to grid')
  405. self.grid_gap_x_entry = QtGui.QLineEdit()
  406. self.grid_gap_x_entry.setMaximumWidth(70)
  407. self.grid_gap_x_entry.setToolTip("Grid X distance")
  408. self.snap_toolbar.addWidget(self.grid_gap_x_entry)
  409. self.grid_gap_y_entry = QtGui.QLineEdit()
  410. self.grid_gap_y_entry.setMaximumWidth(70)
  411. self.grid_gap_y_entry.setToolTip("Grid Y distante")
  412. self.snap_toolbar.addWidget(self.grid_gap_y_entry)
  413. self.corner_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/corner32.png'), 'Snap to corner')
  414. self.snap_max_dist_entry = QtGui.QLineEdit()
  415. self.snap_max_dist_entry.setMaximumWidth(70)
  416. self.snap_max_dist_entry.setToolTip("Max. magnet distance")
  417. self.snap_toolbar.addWidget(self.snap_max_dist_entry)
  418. self.snap_toolbar.setDisabled(disabled)
  419. self.app.ui.addToolBar(self.snap_toolbar)
  420. ### Event handlers ###
  421. ## Canvas events
  422. self.canvas.mpl_connect('button_press_event', self.on_canvas_click)
  423. self.canvas.mpl_connect('motion_notify_event', self.on_canvas_move)
  424. self.canvas.mpl_connect('key_press_event', self.on_canvas_key)
  425. self.canvas.mpl_connect('key_release_event', self.on_canvas_key_release)
  426. self.union_btn.triggered.connect(self.union)
  427. self.subtract_btn.triggered.connect(self.subtract)
  428. self.cutpath_btn.triggered.connect(self.cutpath)
  429. ## Toolbar events and properties
  430. self.tools = {
  431. "select": {"button": self.select_btn,
  432. "constructor": FCSelect},
  433. "circle": {"button": self.add_circle_btn,
  434. "constructor": FCCircle},
  435. "arc": {"button": self.add_arc_btn,
  436. "constructor": FCArc},
  437. "rectangle": {"button": self.add_rectangle_btn,
  438. "constructor": FCRectangle},
  439. "polygon": {"button": self.add_polygon_btn,
  440. "constructor": FCPolygon},
  441. "path": {"button": self.add_path_btn,
  442. "constructor": FCPath},
  443. "move": {"button": self.move_btn,
  444. "constructor": FCMove},
  445. "copy": {"button": self.copy_btn,
  446. "constructor": FCCopy}
  447. }
  448. ### Data
  449. self.active_tool = None
  450. self.storage = FlatCAMDraw.make_storage()
  451. self.utility = []
  452. ## List of selected shapes.
  453. self.selected = []
  454. self.move_timer = QtCore.QTimer()
  455. self.move_timer.setSingleShot(True)
  456. self.key = None # Currently pressed key
  457. def make_callback(thetool):
  458. def f():
  459. self.on_tool_select(thetool)
  460. return f
  461. for tool in self.tools:
  462. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  463. self.tools[tool]["button"].setCheckable(True) # Checkable
  464. # for snap_tool in [self.grid_snap_btn, self.corner_snap_btn]:
  465. # snap_tool.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  466. # snap_tool.setCheckable(True)
  467. self.grid_snap_btn.setCheckable(True)
  468. self.grid_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  469. self.corner_snap_btn.setCheckable(True)
  470. self.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  471. self.options = {
  472. "snap-x": 0.1,
  473. "snap-y": 0.1,
  474. "snap_max": 0.05,
  475. "grid_snap": False,
  476. "corner_snap": False,
  477. }
  478. self.grid_gap_x_entry.setText(str(self.options["snap-x"]))
  479. self.grid_gap_y_entry.setText(str(self.options["snap-y"]))
  480. self.snap_max_dist_entry.setText(str(self.options["snap_max"]))
  481. self.rtree_index = rtindex.Index()
  482. def entry2option(option, entry):
  483. self.options[option] = float(entry.text())
  484. self.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  485. self.grid_gap_x_entry.editingFinished.connect(lambda: entry2option("snap-x", self.grid_gap_x_entry))
  486. self.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  487. self.grid_gap_y_entry.editingFinished.connect(lambda: entry2option("snap-y", self.grid_gap_y_entry))
  488. self.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  489. self.snap_max_dist_entry.editingFinished.connect(lambda: entry2option("snap_max", self.snap_max_dist_entry))
  490. def activate(self):
  491. pass
  492. def add_shape(self, shape):
  493. """
  494. Adds a shape to the shape storage.
  495. :param shape: Shape to be added.
  496. :type shape: DrawToolShape
  497. :return: None
  498. """
  499. # List of DrawToolShape?
  500. if isinstance(shape, list):
  501. for subshape in shape:
  502. self.add_shape(subshape)
  503. return
  504. assert isinstance(shape, DrawToolShape)
  505. assert shape.geo is not None
  506. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list)
  507. if isinstance(shape, DrawToolUtilityShape):
  508. self.utility.append(shape)
  509. else:
  510. self.storage.insert(shape)
  511. def deactivate(self):
  512. self.clear()
  513. self.drawing_toolbar.setDisabled(True)
  514. self.snap_toolbar.setDisabled(True) # TODO: Combine and move into tool
  515. def delete_utility_geometry(self):
  516. #for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  517. #for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  518. for_deletion = [shape for shape in self.utility]
  519. for shape in for_deletion:
  520. self.delete_shape(shape)
  521. def cutpath(self):
  522. selected = self.get_selected()
  523. tools = selected[1:]
  524. toolgeo = cascaded_union([shp.geo for shp in tools])
  525. target = selected[0]
  526. if type(target.geo) == Polygon:
  527. for ring in poly2rings(target.geo):
  528. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  529. self.delete_shape(target)
  530. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  531. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  532. self.delete_shape(target)
  533. else:
  534. self.app.log.warning("Not implemented.")
  535. self.replot()
  536. def toolbar_tool_toggle(self, key):
  537. self.options[key] = self.sender().isChecked()
  538. print "grid_snap", self.options["grid_snap"]
  539. def clear(self):
  540. self.active_tool = None
  541. #self.shape_buffer = []
  542. self.selected = []
  543. self.storage = FlatCAMDraw.make_storage()
  544. self.replot()
  545. def edit_fcgeometry(self, fcgeometry):
  546. """
  547. Imports the geometry from the given FlatCAM Geometry object
  548. into the editor.
  549. :param fcgeometry: FlatCAMGeometry
  550. :return: None
  551. """
  552. if fcgeometry.solid_geometry is None:
  553. geometry = []
  554. else:
  555. try:
  556. _ = iter(fcgeometry.solid_geometry)
  557. geometry = fcgeometry.solid_geometry
  558. except TypeError:
  559. geometry = [fcgeometry.solid_geometry]
  560. # Delete contents of editor.
  561. #self.shape_buffer = []
  562. self.clear()
  563. # Link shapes into editor.
  564. for shape in geometry:
  565. #self.shape_buffer.append(DrawToolShape(geometry))
  566. self.add_shape(DrawToolShape(shape.flatten()))
  567. self.replot()
  568. self.drawing_toolbar.setDisabled(False)
  569. self.snap_toolbar.setDisabled(False)
  570. def on_tool_select(self, tool):
  571. """
  572. Behavior of the toolbar. Tool initialization.
  573. :rtype : None
  574. """
  575. self.app.log.debug("on_tool_select('%s')" % tool)
  576. # This is to make the group behave as radio group
  577. if tool in self.tools:
  578. if self.tools[tool]["button"].isChecked():
  579. self.app.log.debug("%s is checked." % tool)
  580. for t in self.tools:
  581. if t != tool:
  582. self.tools[t]["button"].setChecked(False)
  583. self.active_tool = self.tools[tool]["constructor"](self)
  584. self.app.info(self.active_tool.start_msg)
  585. else:
  586. self.app.log.debug("%s is NOT checked." % tool)
  587. for t in self.tools:
  588. self.tools[t]["button"].setChecked(False)
  589. self.active_tool = None
  590. def on_canvas_click(self, event):
  591. """
  592. event.x and .y have canvas coordinates
  593. event.xdaya and .ydata have plot coordinates
  594. :param event: Event object dispatched by Matplotlib
  595. :return: None
  596. """
  597. if self.active_tool is not None:
  598. # Dispatch event to active_tool
  599. msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  600. self.app.info(msg)
  601. # If it is a shape generating tool
  602. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  603. self.on_shape_complete()
  604. return
  605. if isinstance(self.active_tool, FCSelect):
  606. self.app.log.debug("Replotting after click.")
  607. self.replot()
  608. else:
  609. self.app.log.debug("No active tool to respond to click!")
  610. def on_canvas_move(self, event):
  611. """
  612. event.x and .y have canvas coordinates
  613. event.xdaya and .ydata have plot coordinates
  614. :param event: Event object dispatched by Matplotlib
  615. :return:
  616. """
  617. self.on_canvas_move_effective(event)
  618. return None
  619. # self.move_timer.stop()
  620. #
  621. # if self.active_tool is None:
  622. # return
  623. #
  624. # # Make a function to avoid late evaluation
  625. # def make_callback():
  626. # def f():
  627. # self.on_canvas_move_effective(event)
  628. # return f
  629. # callback = make_callback()
  630. #
  631. # self.move_timer.timeout.connect(callback)
  632. # self.move_timer.start(500) # Stops if aready running
  633. def on_canvas_move_effective(self, event):
  634. """
  635. Is called after timeout on timer set in on_canvas_move.
  636. For details on animating on MPL see:
  637. http://wiki.scipy.org/Cookbook/Matplotlib/Animations
  638. event.x and .y have canvas coordinates
  639. event.xdaya and .ydata have plot coordinates
  640. :param event: Event object dispatched by Matplotlib
  641. :return: None
  642. """
  643. try:
  644. x = float(event.xdata)
  645. y = float(event.ydata)
  646. except TypeError:
  647. return
  648. if self.active_tool is None:
  649. return
  650. ### Snap coordinates
  651. x, y = self.snap(x, y)
  652. ### Utility geometry (animated)
  653. self.canvas.canvas.restore_region(self.canvas.background)
  654. geo = self.active_tool.utility_geometry(data=(x, y))
  655. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  656. # Remove any previous utility shape
  657. self.delete_utility_geometry()
  658. # Add the new utility shape
  659. self.add_shape(geo)
  660. # Efficient plotting for fast animation
  661. #self.canvas.canvas.restore_region(self.canvas.background)
  662. elements = self.plot_shape(geometry=geo.geo, linespec="b--", animated=True)
  663. for el in elements:
  664. self.axes.draw_artist(el)
  665. #self.canvas.canvas.blit(self.axes.bbox)
  666. # Pointer (snapped)
  667. elements = self.axes.plot(x, y, 'bo', animated=True)
  668. for el in elements:
  669. self.axes.draw_artist(el)
  670. self.canvas.canvas.blit(self.axes.bbox)
  671. def on_canvas_key(self, event):
  672. """
  673. event.key has the key.
  674. :param event:
  675. :return:
  676. """
  677. self.key = event.key
  678. ### Finish the current action. Use with tools that do not
  679. ### complete automatically, like a polygon or path.
  680. if event.key == ' ':
  681. if isinstance(self.active_tool, FCShapeTool):
  682. self.active_tool.click(self.snap(event.xdata, event.ydata))
  683. self.active_tool.make()
  684. if self.active_tool.complete:
  685. self.on_shape_complete()
  686. return
  687. ### Abort the current action
  688. if event.key == 'escape':
  689. # TODO: ...?
  690. self.on_tool_select("select")
  691. self.app.info("Cancelled.")
  692. self.delete_utility_geometry()
  693. self.replot()
  694. self.select_btn.setChecked(True)
  695. self.on_tool_select('select')
  696. return
  697. ### Delete selected object
  698. if event.key == '-':
  699. self.delete_selected()
  700. self.replot()
  701. ### Move
  702. if event.key == 'm':
  703. self.move_btn.setChecked(True)
  704. self.on_tool_select('move')
  705. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  706. ### Copy
  707. if event.key == 'c':
  708. self.copy_btn.setChecked(True)
  709. self.on_tool_select('copy')
  710. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  711. ### Snap
  712. if event.key == 'g':
  713. self.grid_snap_btn.trigger()
  714. if event.key == 'k':
  715. self.corner_snap_btn.trigger()
  716. ### Propagate to tool
  717. response = self.active_tool.on_key(event.key)
  718. if response is not None:
  719. self.app.info(response)
  720. def on_canvas_key_release(self, event):
  721. self.key = None
  722. def get_selected(self):
  723. """
  724. Returns list of shapes that are selected in the editor.
  725. :return: List of shapes.
  726. """
  727. #return [shape for shape in self.shape_buffer if shape["selected"]]
  728. return self.selected
  729. def delete_selected(self):
  730. # for shape in self.get_selected():
  731. # self.shape_buffer.remove(shape)
  732. # self.app.info("Shape deleted.")
  733. tempref = [s for s in self.selected]
  734. for shape in tempref:
  735. #self.shape_buffer.remove(shape)
  736. self.delete_shape(shape)
  737. self.selected = []
  738. def plot_shape(self, geometry=None, linespec='b-', linewidth=1, animated=False):
  739. """
  740. Plots a geometric object or list of objects without rendering. Plotted objects
  741. are returned as a list. This allows for efficient/animated rendering.
  742. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  743. :param linespec: Matplotlib linespec string.
  744. :param linewidth: Width of lines in # of pixels.
  745. :param animated: If geometry is to be animated. (See MPL plot())
  746. :return: List of plotted elements.
  747. """
  748. plot_elements = []
  749. if geometry is None:
  750. geometry = self.active_tool.geometry
  751. try:
  752. _ = iter(geometry)
  753. iterable_geometry = geometry
  754. except TypeError:
  755. iterable_geometry = [geometry]
  756. for geo in iterable_geometry:
  757. if type(geo) == Polygon:
  758. x, y = geo.exterior.coords.xy
  759. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  760. plot_elements.append(element)
  761. for ints in geo.interiors:
  762. x, y = ints.coords.xy
  763. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  764. plot_elements.append(element)
  765. continue
  766. if type(geo) == LineString or type(geo) == LinearRing:
  767. x, y = geo.coords.xy
  768. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  769. plot_elements.append(element)
  770. continue
  771. if type(geo) == MultiPolygon:
  772. for poly in geo:
  773. x, y = poly.exterior.coords.xy
  774. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  775. plot_elements.append(element)
  776. for ints in poly.interiors:
  777. x, y = ints.coords.xy
  778. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  779. plot_elements.append(element)
  780. continue
  781. if type(geo) == Point:
  782. x, y = geo.coords.xy
  783. element, = self.axes.plot(x, y, 'bo', linewidth=linewidth, animated=animated)
  784. plot_elements.append(element)
  785. continue
  786. return plot_elements
  787. # self.canvas.auto_adjust_axes()
  788. def plot_all(self):
  789. self.app.log.debug("plot_all()")
  790. self.axes.cla()
  791. #for shape in self.shape_buffer:
  792. for shape in self.storage.get_objects():
  793. if shape.geo is None: # TODO: This shouldn't have happened
  794. continue
  795. if shape in self.selected:
  796. self.plot_shape(geometry=shape.geo, linespec='k-', linewidth=2)
  797. continue
  798. self.plot_shape(geometry=shape.geo)
  799. for shape in self.utility:
  800. self.plot_shape(geometry=shape.geo, linespec='k--', linewidth=1)
  801. continue
  802. self.canvas.auto_adjust_axes()
  803. def add2index(self, id, geo):
  804. """
  805. Adds every coordinate of geo to the rtree index
  806. under the given id.
  807. :param id: Index of data in list being indexed.
  808. :param geo: Some Shapely.geom kind
  809. :return: None
  810. """
  811. if isinstance(geo, DrawToolShape):
  812. self.add2index(id, geo.geo)
  813. else:
  814. # List or Iterable Shapely type
  815. try:
  816. for subgeo in geo:
  817. self.add2index(id, subgeo)
  818. # Not iteable...
  819. except TypeError:
  820. try:
  821. for pt in geo.coords:
  822. self.rtree_index.add(id, pt)
  823. except NotImplementedError:
  824. # It's a polygon?
  825. for pt in geo.exterior.coords:
  826. self.rtree_index.add(id, pt)
  827. def remove_from_index(self, id, geo):
  828. """
  829. :param id: Index id
  830. :param geo: Geometry to remove from index.
  831. :return: None
  832. """
  833. # DrawToolShape
  834. if isinstance(geo, DrawToolShape):
  835. self.remove_from_index(id, geo.geo)
  836. else:
  837. # List or Iterable Shapely type
  838. try:
  839. for subgeo in geo:
  840. self.remove_from_index(id, subgeo)
  841. # Not iteable...
  842. except TypeError:
  843. try:
  844. for pt in geo.coords:
  845. self.rtree_index.delete(id, pt)
  846. except NotImplementedError:
  847. # It's a polygon?
  848. for pt in geo.exterior.coords:
  849. self.rtree_index.delete(id, pt)
  850. def on_shape_complete(self):
  851. self.app.log.debug("on_shape_complete()")
  852. # For some reason plotting just the last created figure does not
  853. # work. The figure is not shown. Calling replot does the trick
  854. # which generates a new axes object.
  855. #self.plot_shape()
  856. #self.canvas.auto_adjust_axes()
  857. self.add_shape(self.active_tool.geometry)
  858. # Remove any utility shapes
  859. self.delete_utility_geometry()
  860. self.replot()
  861. self.active_tool = type(self.active_tool)(self)
  862. def delete_shape(self, shape):
  863. # try:
  864. # # Remove from index list
  865. # shp_idx = self.main_index.index(shape)
  866. # self.main_index[shp_idx] = None
  867. #
  868. # # Remove from rtree index
  869. # self.remove_from_index(shp_idx, shape)
  870. # except ValueError:
  871. # pass
  872. #
  873. # if shape in self.shape_buffer:
  874. # self.shape_buffer.remove(shape)
  875. if shape in self.utility:
  876. self.utility.remove(shape)
  877. return
  878. self.storage.remove(shape)
  879. if shape in self.selected:
  880. self.selected.remove(shape)
  881. def replot(self):
  882. #self.canvas.clear()
  883. self.axes = self.canvas.new_axes("draw")
  884. self.plot_all()
  885. @staticmethod
  886. def make_storage():
  887. ## Shape storage.
  888. storage = FlatCAMRTreeStorage()
  889. storage.get_points = DrawToolShape.get_pts
  890. return storage
  891. def set_selected(self, shape):
  892. # Remove and add to the end.
  893. if shape in self.selected:
  894. self.selected.remove(shape)
  895. self.selected.append(shape)
  896. def set_unselected(self, shape):
  897. if shape in self.selected:
  898. self.selected.remove(shape)
  899. def snap(self, x, y):
  900. """
  901. Adjusts coordinates to snap settings.
  902. :param x: Input coordinate X
  903. :param y: Input coordinate Y
  904. :return: Snapped (x, y)
  905. """
  906. snap_x, snap_y = (x, y)
  907. snap_distance = Inf
  908. ### Object (corner?) snap
  909. ### No need for the objects, just the coordinates
  910. ### in the index.
  911. if self.options["corner_snap"]:
  912. try:
  913. nearest_pt, shape = self.storage.nearest((x, y))
  914. nearest_pt_distance = distance((x, y), nearest_pt)
  915. if nearest_pt_distance <= self.options["snap_max"]:
  916. snap_distance = nearest_pt_distance
  917. snap_x, snap_y = nearest_pt
  918. except (StopIteration, AssertionError):
  919. pass
  920. ### Grid snap
  921. if self.options["grid_snap"]:
  922. if self.options["snap-x"] != 0:
  923. snap_x_ = round(x / self.options["snap-x"]) * self.options['snap-x']
  924. else:
  925. snap_x_ = x
  926. if self.options["snap-y"] != 0:
  927. snap_y_ = round(y / self.options["snap-y"]) * self.options['snap-y']
  928. else:
  929. snap_y_ = y
  930. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  931. if nearest_grid_distance < snap_distance:
  932. snap_x, snap_y = (snap_x_, snap_y_)
  933. return snap_x, snap_y
  934. def update_fcgeometry(self, fcgeometry):
  935. """
  936. Transfers the drawing tool shape buffer to the selected geometry
  937. object. The geometry already in the object are removed.
  938. :param fcgeometry: FlatCAMGeometry
  939. :return: None
  940. """
  941. fcgeometry.solid_geometry = []
  942. #for shape in self.shape_buffer:
  943. for shape in self.storage.get_objects():
  944. fcgeometry.solid_geometry.append(shape.geo)
  945. def union(self):
  946. """
  947. Makes union of selected polygons. Original polygons
  948. are deleted.
  949. :return: None.
  950. """
  951. results = cascaded_union([t.geo for t in self.get_selected()])
  952. # Delete originals.
  953. for shape in self.get_selected():
  954. #self.shape_buffer.remove(shape)
  955. self.delete_shape(shape) # TODO: This will crash
  956. # Selected geometry is now gone!
  957. self.selected = []
  958. self.add_shape(DrawToolShape(results))
  959. self.replot()
  960. def subtract(self):
  961. selected = self.get_selected()
  962. tools = selected[1:]
  963. toolgeo = cascaded_union([shp.geo for shp in tools])
  964. result = selected[0].geo.difference(toolgeo)
  965. self.delete_shape(selected[0])
  966. self.add_shape(DrawToolShape(result))
  967. self.replot()
  968. def distance(pt1, pt2):
  969. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  970. def mag(vec):
  971. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  972. def poly2rings(poly):
  973. return [poly.exterior] + [interior for interior in poly.interiors]