FlatCAMObj.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from cStringIO import StringIO
  9. from PyQt4 import QtCore
  10. from copy import copy
  11. from ObjectUI import *
  12. import FlatCAMApp
  13. import inspect # TODO: For debugging only.
  14. from camlib import *
  15. from FlatCAMCommon import LoudDict
  16. from FlatCAMDraw import FlatCAMDraw
  17. ########################################
  18. ## FlatCAMObj ##
  19. ########################################
  20. class FlatCAMObj(QtCore.QObject):
  21. """
  22. Base type of objects handled in FlatCAM. These become interactive
  23. in the GUI, can be plotted, and their options can be modified
  24. by the user in their respective forms.
  25. """
  26. # Instance of the application to which these are related.
  27. # The app should set this value.
  28. app = None
  29. option_changed = QtCore.pyqtSignal(QtCore.QObject, str)
  30. def __init__(self, name):
  31. """
  32. Constructor.
  33. :param name: Name of the object given by the user.
  34. :return: FlatCAMObj
  35. """
  36. QtCore.QObject.__init__(self)
  37. # View
  38. self.ui = None
  39. self.options = LoudDict(name=name)
  40. self.options.set_change_callback(self.on_options_change)
  41. self.form_fields = {}
  42. self.axes = None # Matplotlib axes
  43. self.kind = None # Override with proper name
  44. self.muted_ui = False
  45. # assert isinstance(self.ui, ObjectUI)
  46. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  47. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  48. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  49. def from_dict(self, d):
  50. """
  51. This supersedes ``from_dict`` in derived classes. Derived classes
  52. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  53. ``self.options`` is only updated, not overwritten. This ensures that
  54. options set by the app do not vanish when reading the objects
  55. from a project file.
  56. :param d: Dictionary with attributes to set.
  57. :return: None
  58. """
  59. for attr in self.ser_attrs:
  60. if attr == 'options':
  61. self.options.update(d[attr])
  62. else:
  63. setattr(self, attr, d[attr])
  64. def on_options_change(self, key):
  65. #self.emit(QtCore.SIGNAL("optionChanged()"), key)
  66. self.option_changed.emit(self, key)
  67. def set_ui(self, ui):
  68. self.ui = ui
  69. self.form_fields = {"name": self.ui.name_entry}
  70. assert isinstance(self.ui, ObjectUI)
  71. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  72. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  73. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  74. def __str__(self):
  75. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  76. def on_name_activate(self):
  77. old_name = copy(self.options["name"])
  78. new_name = self.ui.name_entry.get_value()
  79. self.options["name"] = self.ui.name_entry.get_value()
  80. self.app.info("Name changed from %s to %s" % (old_name, new_name))
  81. def on_offset_button_click(self):
  82. self.app.report_usage("obj_on_offset_button")
  83. self.read_form()
  84. vect = self.ui.offsetvector_entry.get_value()
  85. self.offset(vect)
  86. self.plot()
  87. def on_scale_button_click(self):
  88. self.app.report_usage("obj_on_scale_button")
  89. self.read_form()
  90. factor = self.ui.scale_entry.get_value()
  91. self.scale(factor)
  92. self.plot()
  93. def setup_axes(self, figure):
  94. """
  95. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  96. them to figure if not part of the figure. 4) Sets transparent
  97. background. 5) Sets 1:1 scale aspect ratio.
  98. :param figure: A Matplotlib.Figure on which to add/configure axes.
  99. :type figure: matplotlib.figure.Figure
  100. :return: None
  101. :rtype: None
  102. """
  103. if self.axes is None:
  104. FlatCAMApp.App.log.debug("setup_axes(): New axes")
  105. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  106. label=self.options["name"])
  107. elif self.axes not in figure.axes:
  108. FlatCAMApp.App.log.debug("setup_axes(): Clearing and attaching axes")
  109. self.axes.cla()
  110. figure.add_axes(self.axes)
  111. else:
  112. FlatCAMApp.App.log.debug("setup_axes(): Clearing Axes")
  113. self.axes.cla()
  114. # Remove all decoration. The app's axes will have
  115. # the ticks and grid.
  116. self.axes.set_frame_on(False) # No frame
  117. self.axes.set_xticks([]) # No tick
  118. self.axes.set_yticks([]) # No ticks
  119. self.axes.patch.set_visible(False) # No background
  120. self.axes.set_aspect(1)
  121. def to_form(self):
  122. """
  123. Copies options to the UI form.
  124. :return: None
  125. """
  126. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.to_form()")
  127. for option in self.options:
  128. try:
  129. self.set_form_item(option)
  130. except:
  131. self.app.log.warning("Unexpected error:", sys.exc_info())
  132. def read_form(self):
  133. """
  134. Reads form into ``self.options``.
  135. :return: None
  136. :rtype: None
  137. """
  138. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  139. for option in self.options:
  140. try:
  141. self.read_form_item(option)
  142. except:
  143. self.app.log.warning("Unexpected error:", sys.exc_info())
  144. def build_ui(self):
  145. """
  146. Sets up the UI/form for this object. Show the UI
  147. in the App.
  148. :return: None
  149. :rtype: None
  150. """
  151. self.muted_ui = True
  152. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  153. # Remove anything else in the box
  154. # box_children = self.app.ui.notebook.selected_contents.get_children()
  155. # for child in box_children:
  156. # self.app.ui.notebook.selected_contents.remove(child)
  157. # while self.app.ui.selected_layout.count():
  158. # self.app.ui.selected_layout.takeAt(0)
  159. # Put in the UI
  160. # box_selected.pack_start(sw, True, True, 0)
  161. # self.app.ui.notebook.selected_contents.add(self.ui)
  162. # self.app.ui.selected_layout.addWidget(self.ui)
  163. try:
  164. self.app.ui.selected_scroll_area.takeWidget()
  165. except:
  166. self.app.log.debug("Nothing to remove")
  167. self.app.ui.selected_scroll_area.setWidget(self.ui)
  168. self.to_form()
  169. self.muted_ui = False
  170. def set_form_item(self, option):
  171. """
  172. Copies the specified option to the UI form.
  173. :param option: Name of the option (Key in ``self.options``).
  174. :type option: str
  175. :return: None
  176. """
  177. try:
  178. self.form_fields[option].set_value(self.options[option])
  179. except KeyError:
  180. self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  181. def read_form_item(self, option):
  182. """
  183. Reads the specified option from the UI form into ``self.options``.
  184. :param option: Name of the option.
  185. :type option: str
  186. :return: None
  187. """
  188. try:
  189. self.options[option] = self.form_fields[option].get_value()
  190. except KeyError:
  191. self.app.log.warning("Failed to read option from field: %s" % option)
  192. # #try read field only when option have equivalent in form_fields
  193. # if option in self.form_fields:
  194. # option_type=type(self.options[option])
  195. # try:
  196. # value=self.form_fields[option].get_value()
  197. # #catch per option as it was ignored anyway, also when syntax error (probably uninitialized field),don't read either.
  198. # except (KeyError,SyntaxError):
  199. # self.app.log.warning("Failed to read option from field: %s" % option)
  200. # else:
  201. # self.app.log.warning("Form fied does not exists: %s" % option)
  202. def plot(self):
  203. """
  204. Plot this object (Extend this method to implement the actual plotting).
  205. Axes get created, appended to canvas and cleared before plotting.
  206. Call this in descendants before doing the plotting.
  207. :return: Whether to continue plotting or not depending on the "plot" option.
  208. :rtype: bool
  209. """
  210. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  211. # Axes must exist and be attached to canvas.
  212. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  213. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  214. if not self.options["plot"]:
  215. self.axes.cla()
  216. self.app.plotcanvas.auto_adjust_axes()
  217. return False
  218. # Clear axes or we will plot on top of them.
  219. self.axes.cla() # TODO: Thread safe?
  220. return True
  221. def serialize(self):
  222. """
  223. Returns a representation of the object as a dictionary so
  224. it can be later exported as JSON. Override this method.
  225. :return: Dictionary representing the object
  226. :rtype: dict
  227. """
  228. return
  229. def deserialize(self, obj_dict):
  230. """
  231. Re-builds an object from its serialized version.
  232. :param obj_dict: Dictionary representing a FlatCAMObj
  233. :type obj_dict: dict
  234. :return: None
  235. """
  236. return
  237. class FlatCAMGerber(FlatCAMObj, Gerber):
  238. """
  239. Represents Gerber code.
  240. """
  241. ui_type = GerberObjectUI
  242. def __init__(self, name):
  243. Gerber.__init__(self)
  244. FlatCAMObj.__init__(self, name)
  245. self.kind = "gerber"
  246. # The 'name' is already in self.options from FlatCAMObj
  247. # Automatically updates the UI
  248. self.options.update({
  249. "plot": True,
  250. "multicolored": False,
  251. "solid": False,
  252. "isotooldia": 0.016,
  253. "isopasses": 1,
  254. "isooverlap": 0.15,
  255. "combine_passes": True,
  256. "cutouttooldia": 0.07,
  257. "cutoutmargin": 0.2,
  258. "cutoutgapsize": 0.15,
  259. "gaps": "tb",
  260. "noncoppermargin": 0.0,
  261. "noncopperrounded": False,
  262. "bboxmargin": 0.0,
  263. "bboxrounded": False
  264. })
  265. # Attributes to be included in serialization
  266. # Always append to it because it carries contents
  267. # from predecessors.
  268. self.ser_attrs += ['options', 'kind']
  269. # assert isinstance(self.ui, GerberObjectUI)
  270. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  271. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  272. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  273. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  274. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  275. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  276. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  277. def set_ui(self, ui):
  278. """
  279. Maps options with GUI inputs.
  280. Connects GUI events to methods.
  281. :param ui: GUI object.
  282. :type ui: GerberObjectUI
  283. :return: None
  284. """
  285. FlatCAMObj.set_ui(self, ui)
  286. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  287. self.form_fields.update({
  288. "plot": self.ui.plot_cb,
  289. "multicolored": self.ui.multicolored_cb,
  290. "solid": self.ui.solid_cb,
  291. "isotooldia": self.ui.iso_tool_dia_entry,
  292. "isopasses": self.ui.iso_width_entry,
  293. "isooverlap": self.ui.iso_overlap_entry,
  294. "combine_passes": self.ui.combine_passes_cb,
  295. "cutouttooldia": self.ui.cutout_tooldia_entry,
  296. "cutoutmargin": self.ui.cutout_margin_entry,
  297. "cutoutgapsize": self.ui.cutout_gap_entry,
  298. "gaps": self.ui.gaps_radio,
  299. "noncoppermargin": self.ui.noncopper_margin_entry,
  300. "noncopperrounded": self.ui.noncopper_rounded_cb,
  301. "bboxmargin": self.ui.bbmargin_entry,
  302. "bboxrounded": self.ui.bbrounded_cb
  303. })
  304. assert isinstance(self.ui, GerberObjectUI)
  305. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  306. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  307. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  308. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  309. self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  310. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  311. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  312. def on_generatenoncopper_button_click(self, *args):
  313. self.app.report_usage("gerber_on_generatenoncopper_button")
  314. self.read_form()
  315. name = self.options["name"] + "_noncopper"
  316. def geo_init(geo_obj, app_obj):
  317. assert isinstance(geo_obj, FlatCAMGeometry)
  318. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  319. if not self.options["noncopperrounded"]:
  320. bounding_box = bounding_box.envelope
  321. non_copper = bounding_box.difference(self.solid_geometry)
  322. geo_obj.solid_geometry = non_copper
  323. # TODO: Check for None
  324. self.app.new_object("geometry", name, geo_init)
  325. def on_generatebb_button_click(self, *args):
  326. self.app.report_usage("gerber_on_generatebb_button")
  327. self.read_form()
  328. name = self.options["name"] + "_bbox"
  329. def geo_init(geo_obj, app_obj):
  330. assert isinstance(geo_obj, FlatCAMGeometry)
  331. # Bounding box with rounded corners
  332. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  333. if not self.options["bboxrounded"]: # Remove rounded corners
  334. bounding_box = bounding_box.envelope
  335. geo_obj.solid_geometry = bounding_box
  336. self.app.new_object("geometry", name, geo_init)
  337. def on_generatecutout_button_click(self, *args):
  338. self.app.report_usage("gerber_on_generatecutout_button")
  339. self.read_form()
  340. name = self.options["name"] + "_cutout"
  341. def geo_init(geo_obj, app_obj):
  342. margin = self.options["cutoutmargin"] + self.options["cutouttooldia"]/2
  343. gap_size = self.options["cutoutgapsize"] + self.options["cutouttooldia"]
  344. minx, miny, maxx, maxy = self.bounds()
  345. minx -= margin
  346. maxx += margin
  347. miny -= margin
  348. maxy += margin
  349. midx = 0.5 * (minx + maxx)
  350. midy = 0.5 * (miny + maxy)
  351. hgap = 0.5 * gap_size
  352. pts = [[midx - hgap, maxy],
  353. [minx, maxy],
  354. [minx, midy + hgap],
  355. [minx, midy - hgap],
  356. [minx, miny],
  357. [midx - hgap, miny],
  358. [midx + hgap, miny],
  359. [maxx, miny],
  360. [maxx, midy - hgap],
  361. [maxx, midy + hgap],
  362. [maxx, maxy],
  363. [midx + hgap, maxy]]
  364. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  365. [pts[6], pts[7], pts[10], pts[11]]],
  366. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  367. [pts[3], pts[4], pts[7], pts[8]]],
  368. "4": [[pts[0], pts[1], pts[2]],
  369. [pts[3], pts[4], pts[5]],
  370. [pts[6], pts[7], pts[8]],
  371. [pts[9], pts[10], pts[11]]]}
  372. cuts = cases[self.options['gaps']]
  373. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  374. # TODO: Check for None
  375. self.app.new_object("geometry", name, geo_init)
  376. def on_iso_button_click(self, *args):
  377. self.app.report_usage("gerber_on_iso_button")
  378. self.read_form()
  379. self.isolate()
  380. def follow(self, outname=None):
  381. """
  382. Creates a geometry object "following" the gerber paths.
  383. :return: None
  384. """
  385. default_name = self.options["name"] + "_follow"
  386. follow_name = outname or default_name
  387. def follow_init(follow_obj, app_obj):
  388. # Propagate options
  389. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  390. follow_obj.solid_geometry = self.solid_geometry
  391. app_obj.info("Follow geometry created: %s" % follow_obj.options["name"])
  392. # TODO: Do something if this is None. Offer changing name?
  393. self.app.new_object("geometry", follow_name, follow_init)
  394. def isolate(self, dia=None, passes=None, overlap=None, outname=None, combine=None):
  395. """
  396. Creates an isolation routing geometry object in the project.
  397. :param dia: Tool diameter
  398. :param passes: Number of tool widths to cut
  399. :param overlap: Overlap between passes in fraction of tool diameter
  400. :param outname: Base name of the output object
  401. :return: None
  402. """
  403. if dia is None:
  404. dia = self.options["isotooldia"]
  405. if passes is None:
  406. passes = int(self.options["isopasses"])
  407. if overlap is None:
  408. overlap = self.options["isooverlap"]
  409. if combine is None:
  410. combine = self.options["combine_passes"]
  411. else:
  412. combine = bool(combine)
  413. base_name = self.options["name"] + "_iso"
  414. base_name = outname or base_name
  415. def generate_envelope(offset, invert):
  416. # isolation_geometry produces an envelope that is going on the left of the geometry
  417. # (the copper features). To leave the least amount of burrs on the features
  418. # the tool needs to travel on the right side of the features (this is called conventional milling)
  419. # the first pass is the one cutting all of the features, so it needs to be reversed
  420. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  421. # to cut on the right side of the left over copper i.e on the left side of the features.
  422. geom = self.isolation_geometry(offset)
  423. if invert:
  424. if type(geom) is MultiPolygon:
  425. pl = []
  426. for p in geom:
  427. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  428. geom = MultiPolygon(pl)
  429. elif type(geom) is Polygon:
  430. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  431. else:
  432. raise "Unexpected Geometry"
  433. return geom
  434. if combine:
  435. iso_name = base_name
  436. # TODO: This is ugly. Create way to pass data into init function.
  437. def iso_init(geo_obj, app_obj):
  438. # Propagate options
  439. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  440. geo_obj.solid_geometry = []
  441. for i in range(passes):
  442. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  443. geom = generate_envelope (offset, i == 0)
  444. geo_obj.solid_geometry.append(geom)
  445. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  446. # TODO: Do something if this is None. Offer changing name?
  447. self.app.new_object("geometry", iso_name, iso_init)
  448. else:
  449. for i in range(passes):
  450. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  451. if passes > 1:
  452. iso_name = base_name + str(i + 1)
  453. else:
  454. iso_name = base_name
  455. # TODO: This is ugly. Create way to pass data into init function.
  456. def iso_init(geo_obj, app_obj):
  457. # Propagate options
  458. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  459. geo_obj.solid_geometry = generate_envelope (offset, i == 0)
  460. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  461. # TODO: Do something if this is None. Offer changing name?
  462. self.app.new_object("geometry", iso_name, iso_init)
  463. def on_plot_cb_click(self, *args):
  464. if self.muted_ui:
  465. return
  466. self.read_form_item('plot')
  467. self.plot()
  468. def on_solid_cb_click(self, *args):
  469. if self.muted_ui:
  470. return
  471. self.read_form_item('solid')
  472. self.plot()
  473. def on_multicolored_cb_click(self, *args):
  474. if self.muted_ui:
  475. return
  476. self.read_form_item('multicolored')
  477. self.plot()
  478. def convert_units(self, units):
  479. """
  480. Converts the units of the object by scaling dimensions in all geometry
  481. and options.
  482. :param units: Units to which to convert the object: "IN" or "MM".
  483. :type units: str
  484. :return: None
  485. :rtype: None
  486. """
  487. factor = Gerber.convert_units(self, units)
  488. self.options['isotooldia'] *= factor
  489. self.options['cutoutmargin'] *= factor
  490. self.options['cutoutgapsize'] *= factor
  491. self.options['noncoppermargin'] *= factor
  492. self.options['bboxmargin'] *= factor
  493. def plot(self):
  494. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  495. # Does all the required setup and returns False
  496. # if the 'ptint' option is set to False.
  497. if not FlatCAMObj.plot(self):
  498. return
  499. geometry = self.solid_geometry
  500. # Make sure geometry is iterable.
  501. try:
  502. _ = iter(geometry)
  503. except TypeError:
  504. geometry = [geometry]
  505. if self.options["multicolored"]:
  506. linespec = '-'
  507. else:
  508. linespec = 'k-'
  509. if self.options["solid"]:
  510. for poly in geometry:
  511. # TODO: Too many things hardcoded.
  512. try:
  513. patch = PolygonPatch(poly,
  514. facecolor="#BBF268",
  515. edgecolor="#006E20",
  516. alpha=0.75,
  517. zorder=2)
  518. self.axes.add_patch(patch)
  519. except AssertionError:
  520. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  521. FlatCAMApp.App.log.warning(str(poly))
  522. else:
  523. for poly in geometry:
  524. x, y = poly.exterior.xy
  525. self.axes.plot(x, y, linespec)
  526. for ints in poly.interiors:
  527. x, y = ints.coords.xy
  528. self.axes.plot(x, y, linespec)
  529. self.app.plotcanvas.auto_adjust_axes()
  530. def serialize(self):
  531. return {
  532. "options": self.options,
  533. "kind": self.kind
  534. }
  535. class FlatCAMExcellon(FlatCAMObj, Excellon):
  536. """
  537. Represents Excellon/Drill code.
  538. """
  539. ui_type = ExcellonObjectUI
  540. def __init__(self, name):
  541. Excellon.__init__(self)
  542. FlatCAMObj.__init__(self, name)
  543. self.kind = "excellon"
  544. self.options.update({
  545. "plot": True,
  546. "solid": False,
  547. "drillz": -0.1,
  548. "travelz": 0.1,
  549. "feedrate": 5.0,
  550. # "toolselection": ""
  551. "tooldia": 0.1,
  552. "toolchange": False,
  553. "toolchangez": 1.0,
  554. "spindlespeed": None
  555. })
  556. # TODO: Document this.
  557. self.tool_cbs = {}
  558. # Attributes to be included in serialization
  559. # Always append to it because it carries contents
  560. # from predecessors.
  561. self.ser_attrs += ['options', 'kind']
  562. @staticmethod
  563. def merge(exc_list, exc_final):
  564. """
  565. Merge excellons in exc_list into exc_final.
  566. Options are allways copied from source .
  567. Tools are also merged, if name for tool is same and size differs, then as name is used next available number from both lists
  568. if only one object is specified in exc_list then this acts as copy only
  569. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  570. :param exc_final: Destination FlatCAMExcellon object.
  571. :return: None
  572. """
  573. if type(exc_list) is not list:
  574. exc_list_real= list()
  575. exc_list_real.append(exc_list)
  576. else:
  577. exc_list_real=exc_list
  578. for exc in exc_list_real:
  579. # Expand lists
  580. if type(exc) is list:
  581. FlatCAMExcellon.merge(exc, exc_final)
  582. # If not list, merge excellons
  583. else:
  584. # TODO: I realize forms does not save values into options , when object is deselected
  585. # leave this here for future use
  586. # this reinitialize options based on forms, all steps may not be necessary
  587. # exc.app.collection.set_active(exc.options['name'])
  588. # exc.to_form()
  589. # exc.read_form()
  590. for option in exc.options:
  591. if option is not 'name':
  592. try:
  593. exc_final.options[option] = exc.options[option]
  594. except:
  595. exc.app.log.warning("Failed to copy option.",option)
  596. #deep copy of all drills,to avoid any references
  597. for drill in exc.drills:
  598. point = Point(drill['point'].x,drill['point'].y)
  599. exc_final.drills.append({"point": point, "tool": drill['tool']})
  600. toolsrework=dict()
  601. max_numeric_tool=0
  602. for toolname in exc.tools.iterkeys():
  603. numeric_tool=int(toolname)
  604. if numeric_tool>max_numeric_tool:
  605. max_numeric_tool=numeric_tool
  606. toolsrework[exc.tools[toolname]['C']]=toolname
  607. #exc_final as last because names from final tools will be used
  608. for toolname in exc_final.tools.iterkeys():
  609. numeric_tool=int(toolname)
  610. if numeric_tool>max_numeric_tool:
  611. max_numeric_tool=numeric_tool
  612. toolsrework[exc_final.tools[toolname]['C']]=toolname
  613. for toolvalues in toolsrework.iterkeys():
  614. if toolsrework[toolvalues] in exc_final.tools:
  615. if exc_final.tools[toolsrework[toolvalues]]!={"C": toolvalues}:
  616. exc_final.tools[str(max_numeric_tool+1)]={"C": toolvalues}
  617. else:
  618. exc_final.tools[toolsrework[toolvalues]]={"C": toolvalues}
  619. #this value was not co
  620. exc_final.zeros=exc.zeros
  621. exc_final.create_geometry()
  622. def build_ui(self):
  623. FlatCAMObj.build_ui(self)
  624. # Populate tool list
  625. n = len(self.tools)
  626. self.ui.tools_table.setColumnCount(2)
  627. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
  628. self.ui.tools_table.setRowCount(n)
  629. self.ui.tools_table.setSortingEnabled(False)
  630. i = 0
  631. for tool in self.tools:
  632. id = QtGui.QTableWidgetItem(tool)
  633. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  634. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  635. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  636. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  637. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  638. i += 1
  639. # sort the tool diameter column
  640. self.ui.tools_table.sortItems(1)
  641. # all the tools are selected by default
  642. self.ui.tools_table.selectColumn(0)
  643. self.ui.tools_table.resizeColumnsToContents()
  644. self.ui.tools_table.resizeRowsToContents()
  645. self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
  646. self.ui.tools_table.verticalHeader().hide()
  647. self.ui.tools_table.setSortingEnabled(True)
  648. def set_ui(self, ui):
  649. """
  650. Configures the user interface for this object.
  651. Connects options to form fields.
  652. :param ui: User interface object.
  653. :type ui: ExcellonObjectUI
  654. :return: None
  655. """
  656. FlatCAMObj.set_ui(self, ui)
  657. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  658. self.form_fields.update({
  659. "plot": self.ui.plot_cb,
  660. "solid": self.ui.solid_cb,
  661. "drillz": self.ui.cutz_entry,
  662. "travelz": self.ui.travelz_entry,
  663. "feedrate": self.ui.feedrate_entry,
  664. "tooldia": self.ui.tooldia_entry,
  665. "toolchange": self.ui.toolchange_cb,
  666. "toolchangez": self.ui.toolchangez_entry,
  667. "spindlespeed": self.ui.spindlespeed_entry
  668. })
  669. assert isinstance(self.ui, ExcellonObjectUI), \
  670. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  671. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  672. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  673. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  674. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  675. def get_selected_tools_list(self):
  676. """
  677. Returns the keys to the self.tools dictionary corresponding
  678. to the selections on the tool list in the GUI.
  679. :return: List of tools.
  680. :rtype: list
  681. """
  682. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  683. def generate_milling(self, tools=None, outname=None, tooldia=None):
  684. """
  685. Note: This method is a good template for generic operations as
  686. it takes it's options from parameters or otherwise from the
  687. object's options and returns a (success, msg) tuple as feedback
  688. for shell operations.
  689. :return: Success/failure condition tuple (bool, str).
  690. :rtype: tuple
  691. """
  692. # Get the tools from the list. These are keys
  693. # to self.tools
  694. if tools is None:
  695. tools = self.get_selected_tools_list()
  696. if outname is None:
  697. outname = self.options["name"] + "_mill"
  698. if tooldia is None:
  699. tooldia = self.options["tooldia"]
  700. # Sort tools by diameter. items() -> [('name', diameter), ...]
  701. sorted_tools = sorted(self.tools.items(), key=lambda tl: tl[1])
  702. if tools == "all":
  703. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  704. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  705. if len(tools) == 0:
  706. self.app.inform.emit("Please select one or more tools from the list and try again.")
  707. return False, "Error: No tools."
  708. for tool in tools:
  709. if self.tools[tool]["C"] < tooldia:
  710. self.app.inform.emit("[warning] Milling tool is larger than hole size. Cancelled.")
  711. return False, "Error: Milling tool is larger than hole."
  712. def geo_init(geo_obj, app_obj):
  713. assert isinstance(geo_obj, FlatCAMGeometry), \
  714. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  715. app_obj.progress.emit(20)
  716. geo_obj.solid_geometry = []
  717. for hole in self.drills:
  718. if hole['tool'] in tools:
  719. geo_obj.solid_geometry.append(
  720. Point(hole['point']).buffer(self.tools[hole['tool']]["C"] / 2 -
  721. tooldia / 2).exterior
  722. )
  723. def geo_thread(app_obj):
  724. app_obj.new_object("geometry", outname, geo_init)
  725. app_obj.progress.emit(100)
  726. # Create a promise with the new name
  727. self.app.collection.promise(outname)
  728. # Send to worker
  729. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  730. return True, ""
  731. def on_generate_milling_button_click(self, *args):
  732. self.app.report_usage("excellon_on_create_milling_button")
  733. self.read_form()
  734. self.generate_milling()
  735. def on_create_cncjob_button_click(self, *args):
  736. self.app.report_usage("excellon_on_create_cncjob_button")
  737. self.read_form()
  738. # Get the tools from the list
  739. tools = self.get_selected_tools_list()
  740. if len(tools) == 0:
  741. self.app.inform.emit("Please select one or more tools from the list and try again.")
  742. return
  743. job_name = self.options["name"] + "_cnc"
  744. # Object initialization function for app.new_object()
  745. def job_init(job_obj, app_obj):
  746. assert isinstance(job_obj, FlatCAMCNCjob), \
  747. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  748. app_obj.progress.emit(20)
  749. job_obj.z_cut = self.options["drillz"]
  750. job_obj.z_move = self.options["travelz"]
  751. job_obj.feedrate = self.options["feedrate"]
  752. job_obj.spindlespeed = self.options["spindlespeed"]
  753. # There could be more than one drill size...
  754. # job_obj.tooldia = # TODO: duplicate variable!
  755. # job_obj.options["tooldia"] =
  756. tools_csv = ','.join(tools)
  757. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  758. toolchange=self.options["toolchange"],
  759. toolchangez=self.options["toolchangez"])
  760. app_obj.progress.emit(50)
  761. job_obj.gcode_parse()
  762. app_obj.progress.emit(60)
  763. job_obj.create_geometry()
  764. app_obj.progress.emit(80)
  765. # To be run in separate thread
  766. def job_thread(app_obj):
  767. app_obj.new_object("cncjob", job_name, job_init)
  768. app_obj.progress.emit(100)
  769. # Create promise for the new name.
  770. self.app.collection.promise(job_name)
  771. # Send to worker
  772. # self.app.worker.add_task(job_thread, [self.app])
  773. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  774. def on_plot_cb_click(self, *args):
  775. if self.muted_ui:
  776. return
  777. self.read_form_item('plot')
  778. self.plot()
  779. def on_solid_cb_click(self, *args):
  780. if self.muted_ui:
  781. return
  782. self.read_form_item('solid')
  783. self.plot()
  784. def convert_units(self, units):
  785. factor = Excellon.convert_units(self, units)
  786. self.options['drillz'] *= factor
  787. self.options['travelz'] *= factor
  788. self.options['feedrate'] *= factor
  789. def plot(self):
  790. # Does all the required setup and returns False
  791. # if the 'ptint' option is set to False.
  792. if not FlatCAMObj.plot(self):
  793. return
  794. try:
  795. _ = iter(self.solid_geometry)
  796. except TypeError:
  797. self.solid_geometry = [self.solid_geometry]
  798. # Plot excellon (All polygons?)
  799. if self.options["solid"]:
  800. for geo in self.solid_geometry:
  801. patch = PolygonPatch(geo,
  802. facecolor="#C40000",
  803. edgecolor="#750000",
  804. alpha=0.75,
  805. zorder=3)
  806. self.axes.add_patch(patch)
  807. else:
  808. for geo in self.solid_geometry:
  809. x, y = geo.exterior.coords.xy
  810. self.axes.plot(x, y, 'r-')
  811. for ints in geo.interiors:
  812. x, y = ints.coords.xy
  813. self.axes.plot(x, y, 'g-')
  814. self.app.plotcanvas.auto_adjust_axes()
  815. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  816. """
  817. Represents G-Code.
  818. """
  819. ui_type = CNCObjectUI
  820. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  821. feedrate=3.0, z_cut=-0.002, tooldia=0.0,
  822. spindlespeed=None):
  823. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  824. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  825. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia,
  826. spindlespeed=spindlespeed)
  827. FlatCAMObj.__init__(self, name)
  828. self.kind = "cncjob"
  829. self.options.update({
  830. "plot": True,
  831. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  832. "append": "",
  833. "prepend": "",
  834. "dwell": False,
  835. "dwelltime": 1
  836. })
  837. # Attributes to be included in serialization
  838. # Always append to it because it carries contents
  839. # from predecessors.
  840. self.ser_attrs += ['options', 'kind']
  841. def set_ui(self, ui):
  842. FlatCAMObj.set_ui(self, ui)
  843. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  844. assert isinstance(self.ui, CNCObjectUI), \
  845. "Expected a CNCObjectUI, got %s" % type(self.ui)
  846. self.form_fields.update({
  847. "plot": self.ui.plot_cb,
  848. "tooldia": self.ui.tooldia_entry,
  849. "append": self.ui.append_text,
  850. "prepend": self.ui.prepend_text,
  851. "postprocess": self.ui.process_script,
  852. "dwell": self.ui.dwell_cb,
  853. "dwelltime": self.ui.dwelltime_entry
  854. })
  855. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  856. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  857. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  858. def on_updateplot_button_click(self, *args):
  859. """
  860. Callback for the "Updata Plot" button. Reads the form for updates
  861. and plots the object.
  862. """
  863. self.read_form()
  864. self.plot()
  865. def on_exportgcode_button_click(self, *args):
  866. self.app.report_usage("cncjob_on_exportgcode_button")
  867. self.read_form()
  868. try:
  869. filename = unicode(QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  870. directory=self.app.defaults["last_folder"]))
  871. except TypeError:
  872. filename = unicode(QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ..."))
  873. preamble = str(self.ui.prepend_text.get_value())
  874. postamble = str(self.ui.append_text.get_value())
  875. processor = str(self.ui.process_script.get_value())
  876. self.export_gcode(filename, preamble=preamble, postamble=postamble, processor=processor)
  877. def dwell_generator(self, lines):
  878. """
  879. Inserts "G4 P..." instructions after spindle-start
  880. instructions (M03 or M04).
  881. """
  882. log.debug("dwell_generator()...")
  883. m3m4re = re.compile(r'^\s*[mM]0[34]')
  884. g4re = re.compile(r'^\s*[gG]4\s+([\d\.\+\-e]+)')
  885. bufline = None
  886. for line in lines:
  887. # If the buffer contains a G4, yield that.
  888. # If current line is a G4, discard it.
  889. if bufline is not None:
  890. yield bufline
  891. bufline = None
  892. if not g4re.search(line):
  893. yield line
  894. continue
  895. # If start spindle, buffer a G4.
  896. if m3m4re.search(line):
  897. log.debug("Found M03/4")
  898. bufline = "G4 P{}\n".format(self.options['dwelltime'])
  899. yield line
  900. raise StopIteration
  901. def export_gcode(self, filename, preamble='', postamble='', processor=''):
  902. lines = StringIO(self.gcode)
  903. ## Post processing
  904. # Dwell?
  905. if self.options['dwell']:
  906. log.debug("Will add G04!")
  907. lines = self.dwell_generator(lines)
  908. ## Write
  909. with open(filename, 'w') as f:
  910. f.write(preamble + "\n")
  911. for line in lines:
  912. f.write(line)
  913. f.write(postamble)
  914. # Just for adding it to the recent files list.
  915. self.app.file_opened.emit("cncjob", filename)
  916. self.app.inform.emit("Saved to: " + filename)
  917. def get_gcode(self, preamble='', postamble=''):
  918. #we need this to beable get_gcode separatelly for shell command export_code
  919. return preamble + '\n' + self.gcode + "\n" + postamble
  920. def on_plot_cb_click(self, *args):
  921. if self.muted_ui:
  922. return
  923. self.read_form_item('plot')
  924. self.plot()
  925. def plot(self):
  926. # Does all the required setup and returns False
  927. # if the 'ptint' option is set to False.
  928. if not FlatCAMObj.plot(self):
  929. return
  930. self.plot2(self.axes, tooldia=self.options["tooldia"])
  931. self.app.plotcanvas.auto_adjust_axes()
  932. def convert_units(self, units):
  933. factor = CNCjob.convert_units(self, units)
  934. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  935. self.options["tooldia"] *= factor
  936. class FlatCAMGeometry(FlatCAMObj, Geometry):
  937. """
  938. Geometric object not associated with a specific
  939. format.
  940. """
  941. ui_type = GeometryObjectUI
  942. @staticmethod
  943. def merge(geo_list, geo_final):
  944. """
  945. Merges the geometry of objects in geo_list into
  946. the geometry of geo_final.
  947. :param geo_list: List of FlatCAMGeometry Objects to join.
  948. :param geo_final: Destination FlatCAMGeometry object.
  949. :return: None
  950. """
  951. if geo_final.solid_geometry is None:
  952. geo_final.solid_geometry = []
  953. if type(geo_final.solid_geometry) is not list:
  954. geo_final.solid_geometry = [geo_final.solid_geometry]
  955. for geo in geo_list:
  956. # Expand lists
  957. if type(geo) is list:
  958. FlatCAMGeometry.merge(geo, geo_final)
  959. # If not list, just append
  960. else:
  961. geo_final.solid_geometry.append(geo.solid_geometry)
  962. # try: # Iterable
  963. # for shape in geo.solid_geometry:
  964. # geo_final.solid_geometry.append(shape)
  965. #
  966. # except TypeError: # Non-iterable
  967. # geo_final.solid_geometry.append(geo.solid_geometry)
  968. def __init__(self, name):
  969. FlatCAMObj.__init__(self, name)
  970. Geometry.__init__(self)
  971. self.kind = "geometry"
  972. self.options.update({
  973. "plot": True,
  974. "cutz": -0.002,
  975. "travelz": 0.1,
  976. "feedrate": 5.0,
  977. "spindlespeed": None,
  978. "cnctooldia": 0.4 / 25.4,
  979. "painttooldia": 0.0625,
  980. "paintoverlap": 0.15,
  981. "paintmargin": 0.01,
  982. "paintmethod": "standard",
  983. "pathconnect": True,
  984. "paintcontour": True,
  985. "multidepth": False,
  986. "depthperpass": 0.002,
  987. "selectmethod": "single"
  988. })
  989. # Attributes to be included in serialization
  990. # Always append to it because it carries contents
  991. # from predecessors.
  992. self.ser_attrs += ['options', 'kind']
  993. def build_ui(self):
  994. FlatCAMObj.build_ui(self)
  995. def set_ui(self, ui):
  996. FlatCAMObj.set_ui(self, ui)
  997. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  998. assert isinstance(self.ui, GeometryObjectUI), \
  999. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1000. self.form_fields.update({
  1001. "plot": self.ui.plot_cb,
  1002. "cutz": self.ui.cutz_entry,
  1003. "travelz": self.ui.travelz_entry,
  1004. "feedrate": self.ui.cncfeedrate_entry,
  1005. "spindlespeed": self.ui.cncspindlespeed_entry,
  1006. "cnctooldia": self.ui.cnctooldia_entry,
  1007. "painttooldia": self.ui.painttooldia_entry,
  1008. "paintoverlap": self.ui.paintoverlap_entry,
  1009. "paintmargin": self.ui.paintmargin_entry,
  1010. "paintmethod": self.ui.paintmethod_combo,
  1011. "pathconnect": self.ui.pathconnect_cb,
  1012. "paintcontour": self.ui.paintcontour_cb,
  1013. "multidepth": self.ui.mpass_cb,
  1014. "depthperpass": self.ui.maxdepth_entry,
  1015. "selectmethod": self.ui.selectmethod_combo
  1016. })
  1017. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1018. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1019. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  1020. def on_paint_button_click(self, *args):
  1021. self.app.report_usage("geometry_on_paint_button")
  1022. self.read_form()
  1023. tooldia = self.options["painttooldia"]
  1024. overlap = self.options["paintoverlap"]
  1025. if self.options["selectmethod"] == "all":
  1026. self.paint_poly_all(tooldia, overlap,
  1027. connect=self.options["pathconnect"],
  1028. contour=self.options["paintcontour"])
  1029. return
  1030. if self.options["selectmethod"] == "single":
  1031. self.app.info("Click inside the desired polygon.")
  1032. # To be called after clicking on the plot.
  1033. def doit(event):
  1034. self.app.info("Painting polygon...")
  1035. self.app.plotcanvas.mpl_disconnect(subscription)
  1036. point = [event.xdata, event.ydata]
  1037. self.paint_poly_single_click(point, tooldia, overlap,
  1038. connect=self.options["pathconnect"],
  1039. contour=self.options["paintcontour"])
  1040. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  1041. def paint_poly_single_click(self, inside_pt, tooldia, overlap,
  1042. outname=None, connect=True, contour=True):
  1043. """
  1044. Paints a polygon selected by clicking on its interior.
  1045. Note:
  1046. * The margin is taken directly from the form.
  1047. :param inside_pt: [x, y]
  1048. :param tooldia: Diameter of the painting tool
  1049. :param overlap: Overlap of the tool between passes.
  1050. :param outname: Name of the resulting Geometry Object.
  1051. :param connect: Connect lines to avoid tool lifts.
  1052. :param contour: Paint around the edges.
  1053. :return: None
  1054. """
  1055. # Which polygon.
  1056. poly = self.find_polygon(inside_pt)
  1057. # No polygon?
  1058. if poly is None:
  1059. self.app.log.warning('No polygon found.')
  1060. self.app.inform.emit('[warning] No polygon found.')
  1061. return
  1062. proc = self.app.proc_container.new("Painting polygon.")
  1063. name = outname or self.options["name"] + "_paint"
  1064. # Initializes the new geometry object
  1065. def gen_paintarea(geo_obj, app_obj):
  1066. assert isinstance(geo_obj, FlatCAMGeometry), \
  1067. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1068. #assert isinstance(app_obj, App)
  1069. if self.options["paintmethod"] == "seed":
  1070. # Type(cp) == FlatCAMRTreeStorage | None
  1071. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1072. tooldia, overlap=overlap, connect=connect,
  1073. contour=contour)
  1074. elif self.options["paintmethod"] == "lines":
  1075. # Type(cp) == FlatCAMRTreeStorage | None
  1076. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1077. tooldia, overlap=overlap, connect=connect,
  1078. contour=contour)
  1079. else:
  1080. # Type(cp) == FlatCAMRTreeStorage | None
  1081. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1082. tooldia, overlap=overlap, connect=connect,
  1083. contour=contour)
  1084. if cp is not None:
  1085. geo_obj.solid_geometry = list(cp.get_objects())
  1086. geo_obj.options["cnctooldia"] = tooldia
  1087. # Experimental...
  1088. print "Indexing...",
  1089. geo_obj.make_index()
  1090. print "Done"
  1091. self.app.inform.emit("Done.")
  1092. def job_thread(app_obj):
  1093. try:
  1094. app_obj.new_object("geometry", name, gen_paintarea)
  1095. except Exception as e:
  1096. proc.done()
  1097. raise e
  1098. proc.done()
  1099. self.app.inform.emit("Polygon Paint started ...")
  1100. # Promise object with the new name
  1101. self.app.collection.promise(name)
  1102. # Background
  1103. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1104. def paint_poly_all(self, tooldia, overlap, outname=None,
  1105. connect=True, contour=True):
  1106. """
  1107. Paints all polygons in this object.
  1108. :param tooldia:
  1109. :param overlap:
  1110. :param outname:
  1111. :param connect: Connect lines to avoid tool lifts.
  1112. :param contour: Paint around the edges.
  1113. :return:
  1114. """
  1115. proc = self.app.proc_container.new("Painting polygon.")
  1116. name = outname or self.options["name"] + "_paint"
  1117. # This is a recursive generator of individual Polygons.
  1118. # Note: Double check correct implementation. Might exit
  1119. # early if it finds something that is not a Polygon?
  1120. def recurse(geo):
  1121. try:
  1122. for subg in geo:
  1123. for subsubg in recurse(subg):
  1124. yield subsubg
  1125. except TypeError:
  1126. if isinstance(geo, Polygon):
  1127. yield geo
  1128. raise StopIteration
  1129. # Initializes the new geometry object
  1130. def gen_paintarea(geo_obj, app_obj):
  1131. assert isinstance(geo_obj, FlatCAMGeometry), \
  1132. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1133. geo_obj.solid_geometry = []
  1134. for poly in recurse(self.solid_geometry):
  1135. if self.options["paintmethod"] == "seed":
  1136. # Type(cp) == FlatCAMRTreeStorage | None
  1137. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1138. tooldia, overlap=overlap, contour=contour,
  1139. connect=connect)
  1140. elif self.options["paintmethod"] == "lines":
  1141. # Type(cp) == FlatCAMRTreeStorage | None
  1142. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1143. tooldia, overlap=overlap, contour=contour,
  1144. connect=connect)
  1145. else:
  1146. # Type(cp) == FlatCAMRTreeStorage | None
  1147. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1148. tooldia, overlap=overlap, contour=contour,
  1149. connect=connect)
  1150. if cp is not None:
  1151. geo_obj.solid_geometry += list(cp.get_objects())
  1152. geo_obj.options["cnctooldia"] = tooldia
  1153. # Experimental...
  1154. print "Indexing...",
  1155. geo_obj.make_index()
  1156. print "Done"
  1157. self.app.inform.emit("Done.")
  1158. def job_thread(app_obj):
  1159. try:
  1160. app_obj.new_object("geometry", name, gen_paintarea)
  1161. except Exception as e:
  1162. proc.done()
  1163. traceback.print_stack()
  1164. raise e
  1165. proc.done()
  1166. self.app.inform.emit("Polygon Paint started ...")
  1167. # Promise object with the new name
  1168. self.app.collection.promise(name)
  1169. # Background
  1170. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1171. def on_generatecnc_button_click(self, *args):
  1172. self.app.report_usage("geometry_on_generatecnc_button")
  1173. self.read_form()
  1174. self.generatecncjob()
  1175. def generatecncjob(self,
  1176. z_cut=None,
  1177. z_move=None,
  1178. feedrate=None,
  1179. tooldia=None,
  1180. outname=None,
  1181. spindlespeed=None,
  1182. multidepth=None,
  1183. depthperpass=None,
  1184. use_thread=True):
  1185. """
  1186. Creates a CNCJob out of this Geometry object. The actual
  1187. work is done by the target FlatCAMCNCjob object's
  1188. `generate_from_geometry_2()` method.
  1189. :param z_cut: Cut depth (negative)
  1190. :param z_move: Hight of the tool when travelling (not cutting)
  1191. :param feedrate: Feed rate while cutting
  1192. :param tooldia: Tool diameter
  1193. :param outname: Name of the new object
  1194. :param spindlespeed: Spindle speed (RPM)
  1195. :return: None
  1196. """
  1197. outname = outname if outname is not None else self.options["name"] + "_cnc"
  1198. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  1199. z_move = z_move if z_move is not None else self.options["travelz"]
  1200. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  1201. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  1202. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  1203. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  1204. # To allow default value to be "" (optional in gui) and translate to None
  1205. # if not isinstance(spindlespeed, int):
  1206. # if isinstance(self.options["spindlespeed"], int) or \
  1207. # isinstance(self.options["spindlespeed"], float):
  1208. # spindlespeed = int(self.options["spindlespeed"])
  1209. # else:
  1210. # spindlespeed = None
  1211. if spindlespeed is None:
  1212. # int or None.
  1213. spindlespeed = self.options['spindlespeed']
  1214. # Object initialization function for app.new_object()
  1215. # RUNNING ON SEPARATE THREAD!
  1216. def job_init(job_obj, app_obj):
  1217. assert isinstance(job_obj, FlatCAMCNCjob), \
  1218. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1219. # Propagate options
  1220. job_obj.options["tooldia"] = tooldia
  1221. app_obj.progress.emit(20)
  1222. job_obj.z_cut = z_cut
  1223. job_obj.z_move = z_move
  1224. job_obj.feedrate = feedrate
  1225. job_obj.spindlespeed = spindlespeed
  1226. app_obj.progress.emit(40)
  1227. # TODO: The tolerance should not be hard coded. Just for testing.
  1228. job_obj.generate_from_geometry_2(self,
  1229. multidepth=multidepth,
  1230. depthpercut=depthperpass,
  1231. tolerance=0.0005)
  1232. app_obj.progress.emit(50)
  1233. job_obj.gcode_parse()
  1234. app_obj.progress.emit(80)
  1235. if use_thread:
  1236. # To be run in separate thread
  1237. def job_thread(app_obj):
  1238. with self.app.proc_container.new("Generating CNC Job."):
  1239. app_obj.new_object("cncjob", outname, job_init)
  1240. app_obj.inform.emit("CNCjob created: %s" % outname)
  1241. app_obj.progress.emit(100)
  1242. # Create a promise with the name
  1243. self.app.collection.promise(outname)
  1244. # Send to worker
  1245. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1246. else:
  1247. self.app.new_object("cncjob", outname, job_init)
  1248. def on_plot_cb_click(self, *args): # TODO: args not needed
  1249. if self.muted_ui:
  1250. return
  1251. self.read_form_item('plot')
  1252. self.plot()
  1253. def scale(self, factor):
  1254. """
  1255. Scales all geometry by a given factor.
  1256. :param factor: Factor by which to scale the object's geometry/
  1257. :type factor: float
  1258. :return: None
  1259. :rtype: None
  1260. """
  1261. if type(self.solid_geometry) == list:
  1262. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  1263. for g in self.solid_geometry]
  1264. else:
  1265. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  1266. origin=(0, 0))
  1267. def offset(self, vect):
  1268. """
  1269. Offsets all geometry by a given vector/
  1270. :param vect: (x, y) vector by which to offset the object's geometry.
  1271. :type vect: tuple
  1272. :return: None
  1273. :rtype: None
  1274. """
  1275. dx, dy = vect
  1276. def translate_recursion(geom):
  1277. if type(geom) == list:
  1278. geoms=list()
  1279. for local_geom in geom:
  1280. geoms.append(translate_recursion(local_geom))
  1281. return geoms
  1282. else:
  1283. return affinity.translate(geom, xoff=dx, yoff=dy)
  1284. self.solid_geometry=translate_recursion(self.solid_geometry)
  1285. def convert_units(self, units):
  1286. factor = Geometry.convert_units(self, units)
  1287. self.options['cutz'] *= factor
  1288. self.options['travelz'] *= factor
  1289. self.options['feedrate'] *= factor
  1290. self.options['cnctooldia'] *= factor
  1291. self.options['painttooldia'] *= factor
  1292. self.options['paintmargin'] *= factor
  1293. return factor
  1294. def plot_element(self, element):
  1295. try:
  1296. for sub_el in element:
  1297. self.plot_element(sub_el)
  1298. except TypeError: # Element is not iterable...
  1299. if type(element) == Polygon:
  1300. x, y = element.exterior.coords.xy
  1301. self.axes.plot(x, y, 'r-')
  1302. for ints in element.interiors:
  1303. x, y = ints.coords.xy
  1304. self.axes.plot(x, y, 'r-')
  1305. return
  1306. if type(element) == LineString or type(element) == LinearRing:
  1307. x, y = element.coords.xy
  1308. self.axes.plot(x, y, 'r-')
  1309. return
  1310. FlatCAMApp.App.log.warning("Did not plot:" + str(type(element)))
  1311. def plot(self):
  1312. """
  1313. Plots the object into its axes. If None, of if the axes
  1314. are not part of the app's figure, it fetches new ones.
  1315. :return: None
  1316. """
  1317. # Does all the required setup and returns False
  1318. # if the 'ptint' option is set to False.
  1319. if not FlatCAMObj.plot(self):
  1320. return
  1321. # Make sure solid_geometry is iterable.
  1322. # TODO: This method should not modify the object !!!
  1323. # try:
  1324. # _ = iter(self.solid_geometry)
  1325. # except TypeError:
  1326. # if self.solid_geometry is None:
  1327. # self.solid_geometry = []
  1328. # else:
  1329. # self.solid_geometry = [self.solid_geometry]
  1330. #
  1331. # for geo in self.solid_geometry:
  1332. #
  1333. # if type(geo) == Polygon:
  1334. # x, y = geo.exterior.coords.xy
  1335. # self.axes.plot(x, y, 'r-')
  1336. # for ints in geo.interiors:
  1337. # x, y = ints.coords.xy
  1338. # self.axes.plot(x, y, 'r-')
  1339. # continue
  1340. #
  1341. # if type(geo) == LineString or type(geo) == LinearRing:
  1342. # x, y = geo.coords.xy
  1343. # self.axes.plot(x, y, 'r-')
  1344. # continue
  1345. #
  1346. # if type(geo) == MultiPolygon:
  1347. # for poly in geo:
  1348. # x, y = poly.exterior.coords.xy
  1349. # self.axes.plot(x, y, 'r-')
  1350. # for ints in poly.interiors:
  1351. # x, y = ints.coords.xy
  1352. # self.axes.plot(x, y, 'r-')
  1353. # continue
  1354. #
  1355. # FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  1356. self.plot_element(self.solid_geometry)
  1357. self.app.plotcanvas.auto_adjust_axes()