FlatCAMDraw.py 41 KB

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