FlatCAMDraw.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. self.draw_app.app.log.debug("Selected shape containing: " + str(closest_shape.geo))
  323. return ""
  324. class FCMove(FCShapeTool):
  325. def __init__(self, draw_app):
  326. FCShapeTool.__init__(self, draw_app)
  327. #self.shape_buffer = self.draw_app.shape_buffer
  328. self.origin = None
  329. self.destination = None
  330. self.start_msg = "Click on reference point."
  331. def set_origin(self, origin):
  332. self.origin = origin
  333. def click(self, point):
  334. if len(self.draw_app.get_selected()) == 0:
  335. return "Nothing to move."
  336. if self.origin is None:
  337. self.set_origin(point)
  338. return "Click on final location."
  339. else:
  340. self.destination = point
  341. self.make()
  342. return "Done."
  343. def make(self):
  344. # Create new geometry
  345. dx = self.destination[0] - self.origin[0]
  346. dy = self.destination[1] - self.origin[1]
  347. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  348. for geom in self.draw_app.get_selected()]
  349. # Delete old
  350. self.draw_app.delete_selected()
  351. # # Select the new
  352. # for g in self.geometry:
  353. # # Note that g is not in the app's buffer yet!
  354. # self.draw_app.set_selected(g)
  355. self.complete = True
  356. def utility_geometry(self, data=None):
  357. """
  358. Temporary geometry on screen while using this tool.
  359. :param data:
  360. :return:
  361. """
  362. if self.origin is None:
  363. return None
  364. if len(self.draw_app.get_selected()) == 0:
  365. return None
  366. dx = data[0] - self.origin[0]
  367. dy = data[1] - self.origin[1]
  368. return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  369. for geom in self.draw_app.get_selected()])
  370. class FCCopy(FCMove):
  371. def make(self):
  372. # Create new geometry
  373. dx = self.destination[0] - self.origin[0]
  374. dy = self.destination[1] - self.origin[1]
  375. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  376. for geom in self.draw_app.get_selected()]
  377. self.complete = True
  378. ########################
  379. ### Main Application ###
  380. ########################
  381. class FlatCAMDraw(QtCore.QObject):
  382. def __init__(self, app, disabled=False):
  383. assert isinstance(app, FlatCAMApp.App)
  384. super(FlatCAMDraw, self).__init__()
  385. self.app = app
  386. self.canvas = app.plotcanvas
  387. self.axes = self.canvas.new_axes("draw")
  388. ### Drawing Toolbar ###
  389. self.drawing_toolbar = QtGui.QToolBar()
  390. self.drawing_toolbar.setDisabled(disabled)
  391. self.app.ui.addToolBar(self.drawing_toolbar)
  392. self.select_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/pointer32.png'), "Select 'Esc'")
  393. self.add_circle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/circle32.png'), 'Add Circle')
  394. self.add_arc_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/arc32.png'), 'Add Arc')
  395. self.add_rectangle_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/rectangle32.png'), 'Add Rectangle')
  396. self.add_polygon_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/polygon32.png'), 'Add Polygon')
  397. self.add_path_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/path32.png'), 'Add Path')
  398. self.union_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/union32.png'), 'Polygon Union')
  399. self.subtract_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/subtract32.png'), 'Polygon Subtraction')
  400. self.cutpath_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/cutpath32.png'), 'Cut Path')
  401. self.move_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/move32.png'), "Move Objects 'm'")
  402. self.copy_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/copy32.png'), "Copy Objects 'c'")
  403. self.delete_btn = self.drawing_toolbar.addAction(QtGui.QIcon('share/deleteshape32.png'), "Delete Shape '-'")
  404. ### Snap Toolbar ###
  405. self.snap_toolbar = QtGui.QToolBar()
  406. self.grid_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/grid32.png'), 'Snap to grid')
  407. self.grid_gap_x_entry = QtGui.QLineEdit()
  408. self.grid_gap_x_entry.setMaximumWidth(70)
  409. self.grid_gap_x_entry.setToolTip("Grid X distance")
  410. self.snap_toolbar.addWidget(self.grid_gap_x_entry)
  411. self.grid_gap_y_entry = QtGui.QLineEdit()
  412. self.grid_gap_y_entry.setMaximumWidth(70)
  413. self.grid_gap_y_entry.setToolTip("Grid Y distante")
  414. self.snap_toolbar.addWidget(self.grid_gap_y_entry)
  415. self.corner_snap_btn = self.snap_toolbar.addAction(QtGui.QIcon('share/corner32.png'), 'Snap to corner')
  416. self.snap_max_dist_entry = QtGui.QLineEdit()
  417. self.snap_max_dist_entry.setMaximumWidth(70)
  418. self.snap_max_dist_entry.setToolTip("Max. magnet distance")
  419. self.snap_toolbar.addWidget(self.snap_max_dist_entry)
  420. self.snap_toolbar.setDisabled(disabled)
  421. self.app.ui.addToolBar(self.snap_toolbar)
  422. ### Event handlers ###
  423. ## Canvas events
  424. self.canvas.mpl_connect('button_press_event', self.on_canvas_click)
  425. self.canvas.mpl_connect('motion_notify_event', self.on_canvas_move)
  426. self.canvas.mpl_connect('key_press_event', self.on_canvas_key)
  427. self.canvas.mpl_connect('key_release_event', self.on_canvas_key_release)
  428. self.union_btn.triggered.connect(self.union)
  429. self.subtract_btn.triggered.connect(self.subtract)
  430. self.cutpath_btn.triggered.connect(self.cutpath)
  431. self.delete_btn.triggered.connect(self.on_delete_btn)
  432. ## Toolbar events and properties
  433. self.tools = {
  434. "select": {"button": self.select_btn,
  435. "constructor": FCSelect},
  436. "circle": {"button": self.add_circle_btn,
  437. "constructor": FCCircle},
  438. "arc": {"button": self.add_arc_btn,
  439. "constructor": FCArc},
  440. "rectangle": {"button": self.add_rectangle_btn,
  441. "constructor": FCRectangle},
  442. "polygon": {"button": self.add_polygon_btn,
  443. "constructor": FCPolygon},
  444. "path": {"button": self.add_path_btn,
  445. "constructor": FCPath},
  446. "move": {"button": self.move_btn,
  447. "constructor": FCMove},
  448. "copy": {"button": self.copy_btn,
  449. "constructor": FCCopy}
  450. }
  451. ### Data
  452. self.active_tool = None
  453. self.storage = FlatCAMDraw.make_storage()
  454. self.utility = []
  455. ## List of selected shapes.
  456. self.selected = []
  457. self.move_timer = QtCore.QTimer()
  458. self.move_timer.setSingleShot(True)
  459. self.key = None # Currently pressed key
  460. def make_callback(thetool):
  461. def f():
  462. self.on_tool_select(thetool)
  463. return f
  464. for tool in self.tools:
  465. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  466. self.tools[tool]["button"].setCheckable(True) # Checkable
  467. # for snap_tool in [self.grid_snap_btn, self.corner_snap_btn]:
  468. # snap_tool.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  469. # snap_tool.setCheckable(True)
  470. self.grid_snap_btn.setCheckable(True)
  471. self.grid_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("grid_snap"))
  472. self.corner_snap_btn.setCheckable(True)
  473. self.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  474. self.options = {
  475. "snap-x": 0.1,
  476. "snap-y": 0.1,
  477. "snap_max": 0.05,
  478. "grid_snap": False,
  479. "corner_snap": False,
  480. }
  481. self.grid_gap_x_entry.setText(str(self.options["snap-x"]))
  482. self.grid_gap_y_entry.setText(str(self.options["snap-y"]))
  483. self.snap_max_dist_entry.setText(str(self.options["snap_max"]))
  484. self.rtree_index = rtindex.Index()
  485. def entry2option(option, entry):
  486. self.options[option] = float(entry.text())
  487. self.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  488. self.grid_gap_x_entry.editingFinished.connect(lambda: entry2option("snap-x", self.grid_gap_x_entry))
  489. self.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  490. self.grid_gap_y_entry.editingFinished.connect(lambda: entry2option("snap-y", self.grid_gap_y_entry))
  491. self.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  492. self.snap_max_dist_entry.editingFinished.connect(lambda: entry2option("snap_max", self.snap_max_dist_entry))
  493. def activate(self):
  494. pass
  495. def add_shape(self, shape):
  496. """
  497. Adds a shape to the shape storage.
  498. :param shape: Shape to be added.
  499. :type shape: DrawToolShape
  500. :return: None
  501. """
  502. # List of DrawToolShape?
  503. if isinstance(shape, list):
  504. for subshape in shape:
  505. self.add_shape(subshape)
  506. return
  507. assert isinstance(shape, DrawToolShape)
  508. assert shape.geo is not None
  509. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list)
  510. if isinstance(shape, DrawToolUtilityShape):
  511. self.utility.append(shape)
  512. else:
  513. self.storage.insert(shape)
  514. def deactivate(self):
  515. self.clear()
  516. self.drawing_toolbar.setDisabled(True)
  517. self.snap_toolbar.setDisabled(True) # TODO: Combine and move into tool
  518. def delete_utility_geometry(self):
  519. #for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  520. #for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  521. for_deletion = [shape for shape in self.utility]
  522. for shape in for_deletion:
  523. self.delete_shape(shape)
  524. def cutpath(self):
  525. selected = self.get_selected()
  526. tools = selected[1:]
  527. toolgeo = cascaded_union([shp.geo for shp in tools])
  528. target = selected[0]
  529. if type(target.geo) == Polygon:
  530. for ring in poly2rings(target.geo):
  531. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  532. self.delete_shape(target)
  533. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  534. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  535. self.delete_shape(target)
  536. else:
  537. self.app.log.warning("Not implemented.")
  538. self.replot()
  539. def toolbar_tool_toggle(self, key):
  540. self.options[key] = self.sender().isChecked()
  541. def clear(self):
  542. self.active_tool = None
  543. #self.shape_buffer = []
  544. self.selected = []
  545. self.storage = FlatCAMDraw.make_storage()
  546. self.replot()
  547. def edit_fcgeometry(self, fcgeometry):
  548. """
  549. Imports the geometry from the given FlatCAM Geometry object
  550. into the editor.
  551. :param fcgeometry: FlatCAMGeometry
  552. :return: None
  553. """
  554. assert isinstance(fcgeometry, Geometry)
  555. self.clear()
  556. # Link shapes into editor.
  557. for shape in fcgeometry.flatten():
  558. if shape is not None: # TODO: Make flatten never create a None
  559. self.add_shape(DrawToolShape(shape))
  560. self.replot()
  561. self.drawing_toolbar.setDisabled(False)
  562. self.snap_toolbar.setDisabled(False)
  563. def on_tool_select(self, tool):
  564. """
  565. Behavior of the toolbar. Tool initialization.
  566. :rtype : None
  567. """
  568. self.app.log.debug("on_tool_select('%s')" % tool)
  569. # This is to make the group behave as radio group
  570. if tool in self.tools:
  571. if self.tools[tool]["button"].isChecked():
  572. self.app.log.debug("%s is checked." % tool)
  573. for t in self.tools:
  574. if t != tool:
  575. self.tools[t]["button"].setChecked(False)
  576. self.active_tool = self.tools[tool]["constructor"](self)
  577. self.app.info(self.active_tool.start_msg)
  578. else:
  579. self.app.log.debug("%s is NOT checked." % tool)
  580. for t in self.tools:
  581. self.tools[t]["button"].setChecked(False)
  582. self.active_tool = None
  583. def on_canvas_click(self, event):
  584. """
  585. event.x and .y have canvas coordinates
  586. event.xdaya and .ydata have plot coordinates
  587. :param event: Event object dispatched by Matplotlib
  588. :return: None
  589. """
  590. if self.active_tool is not None:
  591. # Dispatch event to active_tool
  592. msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  593. self.app.info(msg)
  594. # If it is a shape generating tool
  595. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  596. self.on_shape_complete()
  597. return
  598. if isinstance(self.active_tool, FCSelect):
  599. self.app.log.debug("Replotting after click.")
  600. self.replot()
  601. else:
  602. self.app.log.debug("No active tool to respond to click!")
  603. def on_canvas_move(self, event):
  604. """
  605. event.x and .y have canvas coordinates
  606. event.xdaya and .ydata have plot coordinates
  607. :param event: Event object dispatched by Matplotlib
  608. :return:
  609. """
  610. self.on_canvas_move_effective(event)
  611. return None
  612. # self.move_timer.stop()
  613. #
  614. # if self.active_tool is None:
  615. # return
  616. #
  617. # # Make a function to avoid late evaluation
  618. # def make_callback():
  619. # def f():
  620. # self.on_canvas_move_effective(event)
  621. # return f
  622. # callback = make_callback()
  623. #
  624. # self.move_timer.timeout.connect(callback)
  625. # self.move_timer.start(500) # Stops if aready running
  626. def on_canvas_move_effective(self, event):
  627. """
  628. Is called after timeout on timer set in on_canvas_move.
  629. For details on animating on MPL see:
  630. http://wiki.scipy.org/Cookbook/Matplotlib/Animations
  631. event.x and .y have canvas coordinates
  632. event.xdaya and .ydata have plot coordinates
  633. :param event: Event object dispatched by Matplotlib
  634. :return: None
  635. """
  636. try:
  637. x = float(event.xdata)
  638. y = float(event.ydata)
  639. except TypeError:
  640. return
  641. if self.active_tool is None:
  642. return
  643. ### Snap coordinates
  644. x, y = self.snap(x, y)
  645. ### Utility geometry (animated)
  646. self.canvas.canvas.restore_region(self.canvas.background)
  647. geo = self.active_tool.utility_geometry(data=(x, y))
  648. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  649. # Remove any previous utility shape
  650. self.delete_utility_geometry()
  651. # Add the new utility shape
  652. self.add_shape(geo)
  653. # Efficient plotting for fast animation
  654. #self.canvas.canvas.restore_region(self.canvas.background)
  655. elements = self.plot_shape(geometry=geo.geo,
  656. linespec="b--",
  657. linewidth=1,
  658. animated=True)
  659. for el in elements:
  660. self.axes.draw_artist(el)
  661. #self.canvas.canvas.blit(self.axes.bbox)
  662. # Pointer (snapped)
  663. elements = self.axes.plot(x, y, 'bo', animated=True)
  664. for el in elements:
  665. self.axes.draw_artist(el)
  666. self.canvas.canvas.blit(self.axes.bbox)
  667. def on_canvas_key(self, event):
  668. """
  669. event.key has the key.
  670. :param event:
  671. :return:
  672. """
  673. self.key = event.key
  674. ### Finish the current action. Use with tools that do not
  675. ### complete automatically, like a polygon or path.
  676. if event.key == ' ':
  677. if isinstance(self.active_tool, FCShapeTool):
  678. self.active_tool.click(self.snap(event.xdata, event.ydata))
  679. self.active_tool.make()
  680. if self.active_tool.complete:
  681. self.on_shape_complete()
  682. return
  683. ### Abort the current action
  684. if event.key == 'escape':
  685. # TODO: ...?
  686. self.on_tool_select("select")
  687. self.app.info("Cancelled.")
  688. self.delete_utility_geometry()
  689. self.replot()
  690. self.select_btn.setChecked(True)
  691. self.on_tool_select('select')
  692. return
  693. ### Delete selected object
  694. if event.key == '-':
  695. self.delete_selected()
  696. self.replot()
  697. ### Move
  698. if event.key == 'm':
  699. self.move_btn.setChecked(True)
  700. self.on_tool_select('move')
  701. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  702. ### Copy
  703. if event.key == 'c':
  704. self.copy_btn.setChecked(True)
  705. self.on_tool_select('copy')
  706. self.active_tool.set_origin(self.snap(event.xdata, event.ydata))
  707. ### Snap
  708. if event.key == 'g':
  709. self.grid_snap_btn.trigger()
  710. if event.key == 'k':
  711. self.corner_snap_btn.trigger()
  712. ### Propagate to tool
  713. response = self.active_tool.on_key(event.key)
  714. if response is not None:
  715. self.app.info(response)
  716. def on_canvas_key_release(self, event):
  717. self.key = None
  718. def on_delete_btn(self):
  719. self.delete_selected()
  720. self.replot()
  721. def get_selected(self):
  722. """
  723. Returns list of shapes that are selected in the editor.
  724. :return: List of shapes.
  725. """
  726. #return [shape for shape in self.shape_buffer if shape["selected"]]
  727. return self.selected
  728. def delete_selected(self):
  729. # for shape in self.get_selected():
  730. # self.shape_buffer.remove(shape)
  731. # self.app.info("Shape deleted.")
  732. tempref = [s for s in self.selected]
  733. for shape in tempref:
  734. #self.shape_buffer.remove(shape)
  735. self.delete_shape(shape)
  736. self.selected = []
  737. def plot_shape(self, geometry=None, linespec='b-', linewidth=1, animated=False):
  738. """
  739. Plots a geometric object or list of objects without rendering. Plotted objects
  740. are returned as a list. This allows for efficient/animated rendering.
  741. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  742. :param linespec: Matplotlib linespec string.
  743. :param linewidth: Width of lines in # of pixels.
  744. :param animated: If geometry is to be animated. (See MPL plot())
  745. :return: List of plotted elements.
  746. """
  747. plot_elements = []
  748. if geometry is None:
  749. geometry = self.active_tool.geometry
  750. # try:
  751. # _ = iter(geometry)
  752. # iterable_geometry = geometry
  753. # except TypeError:
  754. # iterable_geometry = [geometry]
  755. ## Iterable: Descend into each element.
  756. try:
  757. for geo in geometry:
  758. plot_elements += self.plot_shape(geometry=geo,
  759. linespec=linespec,
  760. linewidth=linewidth,
  761. animated=animated)
  762. ## Non-iterable
  763. except TypeError:
  764. ## DrawToolShape
  765. if isinstance(geometry, DrawToolShape):
  766. plot_elements += self.plot_shape(geometry=geometry.geo,
  767. linespec=linespec,
  768. linewidth=linewidth,
  769. animated=animated)
  770. ## Polygon: Dscend into exterior and each interior.
  771. if type(geometry) == Polygon:
  772. plot_elements += self.plot_shape(geometry=geometry.exterior,
  773. linespec=linespec,
  774. linewidth=linewidth,
  775. animated=animated)
  776. plot_elements += self.plot_shape(geometry=geometry.interiors,
  777. linespec=linespec,
  778. linewidth=linewidth,
  779. animated=animated)
  780. # x, y = geo.exterior.coords.xy
  781. # element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  782. # plot_elements.append(element)
  783. # for ints in geo.interiors:
  784. # x, y = ints.coords.xy
  785. # element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  786. # plot_elements.append(element)
  787. # continue
  788. if type(geometry) == LineString or type(geometry) == LinearRing:
  789. x, y = geometry.coords.xy
  790. element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  791. plot_elements.append(element)
  792. # continue
  793. # if type(geo) == MultiPolygon:
  794. # for poly in geo:
  795. # x, y = poly.exterior.coords.xy
  796. # element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  797. # plot_elements.append(element)
  798. # for ints in poly.interiors:
  799. # x, y = ints.coords.xy
  800. # element, = self.axes.plot(x, y, linespec, linewidth=linewidth, animated=animated)
  801. # plot_elements.append(element)
  802. # continue
  803. if type(geometry) == Point:
  804. x, y = geometry.coords.xy
  805. element, = self.axes.plot(x, y, 'bo', linewidth=linewidth, animated=animated)
  806. plot_elements.append(element)
  807. # continue
  808. return plot_elements
  809. # self.canvas.auto_adjust_axes()
  810. def plot_all(self):
  811. self.app.log.debug("plot_all()")
  812. self.axes.cla()
  813. #for shape in self.shape_buffer:
  814. for shape in self.storage.get_objects():
  815. if shape.geo is None: # TODO: This shouldn't have happened
  816. continue
  817. if shape in self.selected:
  818. self.plot_shape(geometry=shape.geo, linespec='k-', linewidth=2)
  819. continue
  820. self.plot_shape(geometry=shape.geo)
  821. for shape in self.utility:
  822. self.plot_shape(geometry=shape.geo, linespec='k--', linewidth=1)
  823. continue
  824. self.canvas.auto_adjust_axes()
  825. def add2index(self, id, geo):
  826. """
  827. Adds every coordinate of geo to the rtree index
  828. under the given id.
  829. :param id: Index of data in list being indexed.
  830. :param geo: Some Shapely.geom kind
  831. :return: None
  832. """
  833. if isinstance(geo, DrawToolShape):
  834. self.add2index(id, geo.geo)
  835. else:
  836. # List or Iterable Shapely type
  837. try:
  838. for subgeo in geo:
  839. self.add2index(id, subgeo)
  840. # Not iteable...
  841. except TypeError:
  842. try:
  843. for pt in geo.coords:
  844. self.rtree_index.add(id, pt)
  845. except NotImplementedError:
  846. # It's a polygon?
  847. for pt in geo.exterior.coords:
  848. self.rtree_index.add(id, pt)
  849. def remove_from_index(self, id, geo):
  850. """
  851. :param id: Index id
  852. :param geo: Geometry to remove from index.
  853. :return: None
  854. """
  855. # DrawToolShape
  856. if isinstance(geo, DrawToolShape):
  857. self.remove_from_index(id, geo.geo)
  858. else:
  859. # List or Iterable Shapely type
  860. try:
  861. for subgeo in geo:
  862. self.remove_from_index(id, subgeo)
  863. # Not iteable...
  864. except TypeError:
  865. try:
  866. for pt in geo.coords:
  867. self.rtree_index.delete(id, pt)
  868. except NotImplementedError:
  869. # It's a polygon?
  870. for pt in geo.exterior.coords:
  871. self.rtree_index.delete(id, pt)
  872. def on_shape_complete(self):
  873. self.app.log.debug("on_shape_complete()")
  874. # For some reason plotting just the last created figure does not
  875. # work. The figure is not shown. Calling replot does the trick
  876. # which generates a new axes object.
  877. #self.plot_shape()
  878. #self.canvas.auto_adjust_axes()
  879. self.add_shape(self.active_tool.geometry)
  880. # Remove any utility shapes
  881. self.delete_utility_geometry()
  882. self.replot()
  883. self.active_tool = type(self.active_tool)(self)
  884. def delete_shape(self, shape):
  885. # try:
  886. # # Remove from index list
  887. # shp_idx = self.main_index.index(shape)
  888. # self.main_index[shp_idx] = None
  889. #
  890. # # Remove from rtree index
  891. # self.remove_from_index(shp_idx, shape)
  892. # except ValueError:
  893. # pass
  894. #
  895. # if shape in self.shape_buffer:
  896. # self.shape_buffer.remove(shape)
  897. if shape in self.utility:
  898. self.utility.remove(shape)
  899. return
  900. self.storage.remove(shape)
  901. if shape in self.selected:
  902. self.selected.remove(shape)
  903. def replot(self):
  904. #self.canvas.clear()
  905. self.axes = self.canvas.new_axes("draw")
  906. self.plot_all()
  907. @staticmethod
  908. def make_storage():
  909. ## Shape storage.
  910. storage = FlatCAMRTreeStorage()
  911. storage.get_points = DrawToolShape.get_pts
  912. return storage
  913. def set_selected(self, shape):
  914. # Remove and add to the end.
  915. if shape in self.selected:
  916. self.selected.remove(shape)
  917. self.selected.append(shape)
  918. def set_unselected(self, shape):
  919. if shape in self.selected:
  920. self.selected.remove(shape)
  921. def snap(self, x, y):
  922. """
  923. Adjusts coordinates to snap settings.
  924. :param x: Input coordinate X
  925. :param y: Input coordinate Y
  926. :return: Snapped (x, y)
  927. """
  928. snap_x, snap_y = (x, y)
  929. snap_distance = Inf
  930. ### Object (corner?) snap
  931. ### No need for the objects, just the coordinates
  932. ### in the index.
  933. if self.options["corner_snap"]:
  934. try:
  935. nearest_pt, shape = self.storage.nearest((x, y))
  936. nearest_pt_distance = distance((x, y), nearest_pt)
  937. if nearest_pt_distance <= self.options["snap_max"]:
  938. snap_distance = nearest_pt_distance
  939. snap_x, snap_y = nearest_pt
  940. except (StopIteration, AssertionError):
  941. pass
  942. ### Grid snap
  943. if self.options["grid_snap"]:
  944. if self.options["snap-x"] != 0:
  945. snap_x_ = round(x / self.options["snap-x"]) * self.options['snap-x']
  946. else:
  947. snap_x_ = x
  948. if self.options["snap-y"] != 0:
  949. snap_y_ = round(y / self.options["snap-y"]) * self.options['snap-y']
  950. else:
  951. snap_y_ = y
  952. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  953. if nearest_grid_distance < snap_distance:
  954. snap_x, snap_y = (snap_x_, snap_y_)
  955. return snap_x, snap_y
  956. def update_fcgeometry(self, fcgeometry):
  957. """
  958. Transfers the drawing tool shape buffer to the selected geometry
  959. object. The geometry already in the object are removed.
  960. :param fcgeometry: FlatCAMGeometry
  961. :return: None
  962. """
  963. fcgeometry.solid_geometry = []
  964. #for shape in self.shape_buffer:
  965. for shape in self.storage.get_objects():
  966. fcgeometry.solid_geometry.append(shape.geo)
  967. def union(self):
  968. """
  969. Makes union of selected polygons. Original polygons
  970. are deleted.
  971. :return: None.
  972. """
  973. results = cascaded_union([t.geo for t in self.get_selected()])
  974. # Delete originals.
  975. for_deletion = [s for s in self.get_selected()]
  976. for shape in for_deletion:
  977. self.delete_shape(shape)
  978. # Selected geometry is now gone!
  979. self.selected = []
  980. self.add_shape(DrawToolShape(results))
  981. self.replot()
  982. def subtract(self):
  983. selected = self.get_selected()
  984. tools = selected[1:]
  985. toolgeo = cascaded_union([shp.geo for shp in tools])
  986. result = selected[0].geo.difference(toolgeo)
  987. self.delete_shape(selected[0])
  988. self.add_shape(DrawToolShape(result))
  989. self.replot()
  990. def distance(pt1, pt2):
  991. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  992. def mag(vec):
  993. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  994. def poly2rings(poly):
  995. return [poly.exterior] + [interior for interior in poly.interiors]