FlatCAMObj.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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 io 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. try:
  425. if type(geom) is MultiPolygon:
  426. pl = []
  427. for p in geom:
  428. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  429. geom = MultiPolygon(pl)
  430. elif type(geom) is Polygon:
  431. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  432. except Exception as e:
  433. str("Unexpected Geometry")
  434. return geom
  435. if combine:
  436. iso_name = base_name
  437. # TODO: This is ugly. Create way to pass data into init function.
  438. def iso_init(geo_obj, app_obj):
  439. # Propagate options
  440. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  441. geo_obj.solid_geometry = []
  442. for i in range(passes):
  443. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  444. geom = generate_envelope (offset, i == 0)
  445. geo_obj.solid_geometry.append(geom)
  446. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  447. # TODO: Do something if this is None. Offer changing name?
  448. self.app.new_object("geometry", iso_name, iso_init)
  449. else:
  450. for i in range(passes):
  451. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  452. if passes > 1:
  453. iso_name = base_name + str(i + 1)
  454. else:
  455. iso_name = base_name
  456. # TODO: This is ugly. Create way to pass data into init function.
  457. def iso_init(geo_obj, app_obj):
  458. # Propagate options
  459. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  460. geo_obj.solid_geometry = generate_envelope (offset, i == 0)
  461. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  462. # TODO: Do something if this is None. Offer changing name?
  463. self.app.new_object("geometry", iso_name, iso_init)
  464. def on_plot_cb_click(self, *args):
  465. if self.muted_ui:
  466. return
  467. self.read_form_item('plot')
  468. self.plot()
  469. def on_solid_cb_click(self, *args):
  470. if self.muted_ui:
  471. return
  472. self.read_form_item('solid')
  473. self.plot()
  474. def on_multicolored_cb_click(self, *args):
  475. if self.muted_ui:
  476. return
  477. self.read_form_item('multicolored')
  478. self.plot()
  479. def convert_units(self, units):
  480. """
  481. Converts the units of the object by scaling dimensions in all geometry
  482. and options.
  483. :param units: Units to which to convert the object: "IN" or "MM".
  484. :type units: str
  485. :return: None
  486. :rtype: None
  487. """
  488. factor = Gerber.convert_units(self, units)
  489. self.options['isotooldia'] *= factor
  490. self.options['cutoutmargin'] *= factor
  491. self.options['cutoutgapsize'] *= factor
  492. self.options['noncoppermargin'] *= factor
  493. self.options['bboxmargin'] *= factor
  494. def plot(self):
  495. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  496. # Does all the required setup and returns False
  497. # if the 'ptint' option is set to False.
  498. if not FlatCAMObj.plot(self):
  499. return
  500. geometry = self.solid_geometry
  501. # Make sure geometry is iterable.
  502. try:
  503. _ = iter(geometry)
  504. except TypeError:
  505. geometry = [geometry]
  506. if self.options["multicolored"]:
  507. linespec = '-'
  508. else:
  509. linespec = 'k-'
  510. if self.options["solid"]:
  511. for poly in geometry:
  512. # TODO: Too many things hardcoded.
  513. try:
  514. patch = PolygonPatch(poly,
  515. facecolor="#BBF268",
  516. edgecolor="#006E20",
  517. alpha=0.75,
  518. zorder=2)
  519. self.axes.add_patch(patch)
  520. except AssertionError:
  521. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  522. FlatCAMApp.App.log.warning(str(poly))
  523. else:
  524. for poly in geometry:
  525. x, y = poly.exterior.xy
  526. self.axes.plot(x, y, linespec)
  527. for ints in poly.interiors:
  528. x, y = ints.coords.xy
  529. self.axes.plot(x, y, linespec)
  530. self.app.plotcanvas.auto_adjust_axes()
  531. def serialize(self):
  532. return {
  533. "options": self.options,
  534. "kind": self.kind
  535. }
  536. class FlatCAMExcellon(FlatCAMObj, Excellon):
  537. """
  538. Represents Excellon/Drill code.
  539. """
  540. ui_type = ExcellonObjectUI
  541. def __init__(self, name):
  542. Excellon.__init__(self)
  543. FlatCAMObj.__init__(self, name)
  544. self.kind = "excellon"
  545. self.options.update({
  546. "plot": True,
  547. "solid": False,
  548. "drillz": -0.1,
  549. "travelz": 0.1,
  550. "feedrate": 5.0,
  551. # "toolselection": ""
  552. "tooldia": 0.1,
  553. "toolchange": False,
  554. "toolchangez": 1.0,
  555. "spindlespeed": None
  556. })
  557. # TODO: Document this.
  558. self.tool_cbs = {}
  559. # Attributes to be included in serialization
  560. # Always append to it because it carries contents
  561. # from predecessors.
  562. self.ser_attrs += ['options', 'kind']
  563. @staticmethod
  564. def merge(exc_list, exc_final):
  565. """
  566. Merge excellons in exc_list into exc_final.
  567. Options are allways copied from source .
  568. Tools are also merged, if name for tool is same and size differs, then as name is used next available number from both lists
  569. if only one object is specified in exc_list then this acts as copy only
  570. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  571. :param exc_final: Destination FlatCAMExcellon object.
  572. :return: None
  573. """
  574. if type(exc_list) is not list:
  575. exc_list_real= list()
  576. exc_list_real.append(exc_list)
  577. else:
  578. exc_list_real=exc_list
  579. for exc in exc_list_real:
  580. # Expand lists
  581. if type(exc) is list:
  582. FlatCAMExcellon.merge(exc, exc_final)
  583. # If not list, merge excellons
  584. else:
  585. # TODO: I realize forms does not save values into options , when object is deselected
  586. # leave this here for future use
  587. # this reinitialize options based on forms, all steps may not be necessary
  588. # exc.app.collection.set_active(exc.options['name'])
  589. # exc.to_form()
  590. # exc.read_form()
  591. for option in exc.options:
  592. if option is not 'name':
  593. try:
  594. exc_final.options[option] = exc.options[option]
  595. except:
  596. exc.app.log.warning("Failed to copy option.",option)
  597. #deep copy of all drills,to avoid any references
  598. for drill in exc.drills:
  599. point = Point(drill['point'].x,drill['point'].y)
  600. exc_final.drills.append({"point": point, "tool": drill['tool']})
  601. toolsrework=dict()
  602. max_numeric_tool=0
  603. for toolname in list(exc.tools.keys()):
  604. numeric_tool=int(toolname)
  605. if numeric_tool>max_numeric_tool:
  606. max_numeric_tool=numeric_tool
  607. toolsrework[exc.tools[toolname]['C']]=toolname
  608. #exc_final as last because names from final tools will be used
  609. for toolname in list(exc_final.tools.keys()):
  610. numeric_tool=int(toolname)
  611. if numeric_tool>max_numeric_tool:
  612. max_numeric_tool=numeric_tool
  613. toolsrework[exc_final.tools[toolname]['C']]=toolname
  614. for toolvalues in list(toolsrework.keys()):
  615. if toolsrework[toolvalues] in exc_final.tools:
  616. if exc_final.tools[toolsrework[toolvalues]]!={"C": toolvalues}:
  617. exc_final.tools[str(max_numeric_tool+1)]={"C": toolvalues}
  618. else:
  619. exc_final.tools[toolsrework[toolvalues]]={"C": toolvalues}
  620. #this value was not co
  621. exc_final.zeros=exc.zeros
  622. exc_final.create_geometry()
  623. def build_ui(self):
  624. FlatCAMObj.build_ui(self)
  625. # Populate tool list
  626. n = len(self.tools)
  627. self.ui.tools_table.setColumnCount(2)
  628. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
  629. self.ui.tools_table.setRowCount(n)
  630. self.ui.tools_table.setSortingEnabled(False)
  631. i = 0
  632. for tool in self.tools:
  633. id = QtGui.QTableWidgetItem(tool)
  634. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  635. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  636. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  637. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  638. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  639. i += 1
  640. # sort the tool diameter column
  641. self.ui.tools_table.sortItems(1)
  642. # all the tools are selected by default
  643. self.ui.tools_table.selectColumn(0)
  644. self.ui.tools_table.resizeColumnsToContents()
  645. self.ui.tools_table.resizeRowsToContents()
  646. self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
  647. self.ui.tools_table.verticalHeader().hide()
  648. self.ui.tools_table.setSortingEnabled(True)
  649. def set_ui(self, ui):
  650. """
  651. Configures the user interface for this object.
  652. Connects options to form fields.
  653. :param ui: User interface object.
  654. :type ui: ExcellonObjectUI
  655. :return: None
  656. """
  657. FlatCAMObj.set_ui(self, ui)
  658. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  659. self.form_fields.update({
  660. "plot": self.ui.plot_cb,
  661. "solid": self.ui.solid_cb,
  662. "drillz": self.ui.cutz_entry,
  663. "travelz": self.ui.travelz_entry,
  664. "feedrate": self.ui.feedrate_entry,
  665. "tooldia": self.ui.tooldia_entry,
  666. "toolchange": self.ui.toolchange_cb,
  667. "toolchangez": self.ui.toolchangez_entry,
  668. "spindlespeed": self.ui.spindlespeed_entry
  669. })
  670. assert isinstance(self.ui, ExcellonObjectUI), \
  671. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  672. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  673. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  674. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  675. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  676. def get_selected_tools_list(self):
  677. """
  678. Returns the keys to the self.tools dictionary corresponding
  679. to the selections on the tool list in the GUI.
  680. :return: List of tools.
  681. :rtype: list
  682. """
  683. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  684. def generate_milling(self, tools=None, outname=None, tooldia=None):
  685. """
  686. Note: This method is a good template for generic operations as
  687. it takes it's options from parameters or otherwise from the
  688. object's options and returns a (success, msg) tuple as feedback
  689. for shell operations.
  690. :return: Success/failure condition tuple (bool, str).
  691. :rtype: tuple
  692. """
  693. # Get the tools from the list. These are keys
  694. # to self.tools
  695. if tools is None:
  696. tools = self.get_selected_tools_list()
  697. if outname is None:
  698. outname = self.options["name"] + "_mill"
  699. if tooldia is None:
  700. tooldia = self.options["tooldia"]
  701. # Sort tools by diameter. items() -> [('name', diameter), ...]
  702. sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1])
  703. if tools == "all":
  704. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  705. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  706. if len(tools) == 0:
  707. self.app.inform.emit("Please select one or more tools from the list and try again.")
  708. return False, "Error: No tools."
  709. for tool in tools:
  710. if self.tools[tool]["C"] < tooldia:
  711. self.app.inform.emit("[warning] Milling tool is larger than hole size. Cancelled.")
  712. return False, "Error: Milling tool is larger than hole."
  713. def geo_init(geo_obj, app_obj):
  714. assert isinstance(geo_obj, FlatCAMGeometry), \
  715. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  716. app_obj.progress.emit(20)
  717. geo_obj.solid_geometry = []
  718. for hole in self.drills:
  719. if hole['tool'] in tools:
  720. geo_obj.solid_geometry.append(
  721. Point(hole['point']).buffer(self.tools[hole['tool']]["C"] / 2 -
  722. tooldia / 2).exterior
  723. )
  724. def geo_thread(app_obj):
  725. app_obj.new_object("geometry", outname, geo_init)
  726. app_obj.progress.emit(100)
  727. # Create a promise with the new name
  728. self.app.collection.promise(outname)
  729. # Send to worker
  730. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  731. return True, ""
  732. def on_generate_milling_button_click(self, *args):
  733. self.app.report_usage("excellon_on_create_milling_button")
  734. self.read_form()
  735. self.generate_milling()
  736. def on_create_cncjob_button_click(self, *args):
  737. self.app.report_usage("excellon_on_create_cncjob_button")
  738. self.read_form()
  739. # Get the tools from the list
  740. tools = self.get_selected_tools_list()
  741. if len(tools) == 0:
  742. self.app.inform.emit("Please select one or more tools from the list and try again.")
  743. return
  744. job_name = self.options["name"] + "_cnc"
  745. # Object initialization function for app.new_object()
  746. def job_init(job_obj, app_obj):
  747. assert isinstance(job_obj, FlatCAMCNCjob), \
  748. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  749. app_obj.progress.emit(20)
  750. job_obj.z_cut = self.options["drillz"]
  751. job_obj.z_move = self.options["travelz"]
  752. job_obj.feedrate = self.options["feedrate"]
  753. job_obj.spindlespeed = self.options["spindlespeed"]
  754. # There could be more than one drill size...
  755. # job_obj.tooldia = # TODO: duplicate variable!
  756. # job_obj.options["tooldia"] =
  757. tools_csv = ','.join(tools)
  758. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  759. toolchange=self.options["toolchange"],
  760. toolchangez=self.options["toolchangez"])
  761. app_obj.progress.emit(50)
  762. job_obj.gcode_parse()
  763. app_obj.progress.emit(60)
  764. job_obj.create_geometry()
  765. app_obj.progress.emit(80)
  766. # To be run in separate thread
  767. def job_thread(app_obj):
  768. app_obj.new_object("cncjob", job_name, job_init)
  769. app_obj.progress.emit(100)
  770. # Create promise for the new name.
  771. self.app.collection.promise(job_name)
  772. # Send to worker
  773. # self.app.worker.add_task(job_thread, [self.app])
  774. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  775. def on_plot_cb_click(self, *args):
  776. if self.muted_ui:
  777. return
  778. self.read_form_item('plot')
  779. self.plot()
  780. def on_solid_cb_click(self, *args):
  781. if self.muted_ui:
  782. return
  783. self.read_form_item('solid')
  784. self.plot()
  785. def convert_units(self, units):
  786. factor = Excellon.convert_units(self, units)
  787. self.options['drillz'] *= factor
  788. self.options['travelz'] *= factor
  789. self.options['feedrate'] *= factor
  790. def plot(self):
  791. # Does all the required setup and returns False
  792. # if the 'ptint' option is set to False.
  793. if not FlatCAMObj.plot(self):
  794. return
  795. try:
  796. _ = iter(self.solid_geometry)
  797. except TypeError:
  798. self.solid_geometry = [self.solid_geometry]
  799. # Plot excellon (All polygons?)
  800. if self.options["solid"]:
  801. for geo in self.solid_geometry:
  802. patch = PolygonPatch(geo,
  803. facecolor="#C40000",
  804. edgecolor="#750000",
  805. alpha=0.75,
  806. zorder=3)
  807. self.axes.add_patch(patch)
  808. else:
  809. for geo in self.solid_geometry:
  810. x, y = geo.exterior.coords.xy
  811. self.axes.plot(x, y, 'r-')
  812. for ints in geo.interiors:
  813. x, y = ints.coords.xy
  814. self.axes.plot(x, y, 'g-')
  815. self.app.plotcanvas.auto_adjust_axes()
  816. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  817. """
  818. Represents G-Code.
  819. """
  820. ui_type = CNCObjectUI
  821. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  822. feedrate=3.0, z_cut=-0.002, tooldia=0.0,
  823. spindlespeed=None):
  824. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  825. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  826. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia,
  827. spindlespeed=spindlespeed)
  828. FlatCAMObj.__init__(self, name)
  829. self.kind = "cncjob"
  830. self.options.update({
  831. "plot": True,
  832. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  833. "append": "",
  834. "prepend": "",
  835. "dwell": False,
  836. "dwelltime": 1
  837. })
  838. # Attributes to be included in serialization
  839. # Always append to it because it carries contents
  840. # from predecessors.
  841. self.ser_attrs += ['options', 'kind']
  842. def set_ui(self, ui):
  843. FlatCAMObj.set_ui(self, ui)
  844. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  845. assert isinstance(self.ui, CNCObjectUI), \
  846. "Expected a CNCObjectUI, got %s" % type(self.ui)
  847. self.form_fields.update({
  848. "plot": self.ui.plot_cb,
  849. "tooldia": self.ui.tooldia_entry,
  850. "append": self.ui.append_text,
  851. "prepend": self.ui.prepend_text,
  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 = str(QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  870. directory=self.app.defaults["last_folder"]))
  871. except TypeError:
  872. filename = str(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. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  876. def dwell_generator(self, lines):
  877. """
  878. Inserts "G4 P..." instructions after spindle-start
  879. instructions (M03 or M04).
  880. """
  881. log.debug("dwell_generator()...")
  882. m3m4re = re.compile(r'^\s*[mM]0[34]')
  883. g4re = re.compile(r'^\s*[gG]4\s+([\d\.\+\-e]+)')
  884. bufline = None
  885. for line in lines:
  886. # If the buffer contains a G4, yield that.
  887. # If current line is a G4, discard it.
  888. if bufline is not None:
  889. yield bufline
  890. bufline = None
  891. if not g4re.search(line):
  892. yield line
  893. continue
  894. # If start spindle, buffer a G4.
  895. if m3m4re.search(line):
  896. log.debug("Found M03/4")
  897. bufline = "G4 P{}\n".format(self.options['dwelltime'])
  898. yield line
  899. raise StopIteration
  900. def export_gcode(self, filename, preamble='', postamble=''):
  901. lines = StringIO(self.gcode)
  902. ## Post processing
  903. # Dwell?
  904. if self.options['dwell']:
  905. log.debug("Will add G04!")
  906. lines = self.dwell_generator(lines)
  907. ## Write
  908. with open(filename, 'w') as f:
  909. f.write(preamble + "\n")
  910. for line in lines:
  911. f.write(line)
  912. f.write(postamble)
  913. # Just for adding it to the recent files list.
  914. self.app.file_opened.emit("cncjob", filename)
  915. self.app.inform.emit("Saved to: " + filename)
  916. def get_gcode(self, preamble='', postamble=''):
  917. #we need this to beable get_gcode separatelly for shell command export_code
  918. return preamble + '\n' + self.gcode + "\n" + postamble
  919. def on_plot_cb_click(self, *args):
  920. if self.muted_ui:
  921. return
  922. self.read_form_item('plot')
  923. self.plot()
  924. def plot(self):
  925. # Does all the required setup and returns False
  926. # if the 'ptint' option is set to False.
  927. if not FlatCAMObj.plot(self):
  928. return
  929. self.plot2(self.axes, tooldia=self.options["tooldia"])
  930. self.app.plotcanvas.auto_adjust_axes()
  931. def convert_units(self, units):
  932. factor = CNCjob.convert_units(self, units)
  933. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  934. self.options["tooldia"] *= factor
  935. class FlatCAMGeometry(FlatCAMObj, Geometry):
  936. """
  937. Geometric object not associated with a specific
  938. format.
  939. """
  940. ui_type = GeometryObjectUI
  941. @staticmethod
  942. def merge(geo_list, geo_final):
  943. """
  944. Merges the geometry of objects in geo_list into
  945. the geometry of geo_final.
  946. :param geo_list: List of FlatCAMGeometry Objects to join.
  947. :param geo_final: Destination FlatCAMGeometry object.
  948. :return: None
  949. """
  950. if geo_final.solid_geometry is None:
  951. geo_final.solid_geometry = []
  952. if type(geo_final.solid_geometry) is not list:
  953. geo_final.solid_geometry = [geo_final.solid_geometry]
  954. for geo in geo_list:
  955. # Expand lists
  956. if type(geo) is list:
  957. FlatCAMGeometry.merge(geo, geo_final)
  958. # If not list, just append
  959. else:
  960. geo_final.solid_geometry.append(geo.solid_geometry)
  961. # try: # Iterable
  962. # for shape in geo.solid_geometry:
  963. # geo_final.solid_geometry.append(shape)
  964. #
  965. # except TypeError: # Non-iterable
  966. # geo_final.solid_geometry.append(geo.solid_geometry)
  967. def __init__(self, name):
  968. FlatCAMObj.__init__(self, name)
  969. Geometry.__init__(self)
  970. self.kind = "geometry"
  971. self.options.update({
  972. "plot": True,
  973. "cutz": -0.002,
  974. "travelz": 0.1,
  975. "feedrate": 5.0,
  976. "spindlespeed": None,
  977. "cnctooldia": 0.4 / 25.4,
  978. "painttooldia": 0.0625,
  979. "paintoverlap": 0.15,
  980. "paintmargin": 0.01,
  981. "paintmethod": "standard",
  982. "pathconnect": True,
  983. "paintcontour": True,
  984. "multidepth": False,
  985. "depthperpass": 0.002,
  986. "selectmethod": "single"
  987. })
  988. # Attributes to be included in serialization
  989. # Always append to it because it carries contents
  990. # from predecessors.
  991. self.ser_attrs += ['options', 'kind']
  992. def build_ui(self):
  993. FlatCAMObj.build_ui(self)
  994. def set_ui(self, ui):
  995. FlatCAMObj.set_ui(self, ui)
  996. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  997. assert isinstance(self.ui, GeometryObjectUI), \
  998. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  999. self.form_fields.update({
  1000. "plot": self.ui.plot_cb,
  1001. "cutz": self.ui.cutz_entry,
  1002. "travelz": self.ui.travelz_entry,
  1003. "feedrate": self.ui.cncfeedrate_entry,
  1004. "spindlespeed": self.ui.cncspindlespeed_entry,
  1005. "cnctooldia": self.ui.cnctooldia_entry,
  1006. "painttooldia": self.ui.painttooldia_entry,
  1007. "paintoverlap": self.ui.paintoverlap_entry,
  1008. "paintmargin": self.ui.paintmargin_entry,
  1009. "paintmethod": self.ui.paintmethod_combo,
  1010. "pathconnect": self.ui.pathconnect_cb,
  1011. "paintcontour": self.ui.paintcontour_cb,
  1012. "multidepth": self.ui.mpass_cb,
  1013. "depthperpass": self.ui.maxdepth_entry,
  1014. "selectmethod": self.ui.selectmethod_combo
  1015. })
  1016. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1017. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1018. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  1019. def on_paint_button_click(self, *args):
  1020. self.app.report_usage("geometry_on_paint_button")
  1021. self.read_form()
  1022. tooldia = self.options["painttooldia"]
  1023. overlap = self.options["paintoverlap"]
  1024. if self.options["selectmethod"] == "all":
  1025. self.paint_poly_all(tooldia, overlap,
  1026. connect=self.options["pathconnect"],
  1027. contour=self.options["paintcontour"])
  1028. return
  1029. if self.options["selectmethod"] == "single":
  1030. self.app.info("Click inside the desired polygon.")
  1031. # To be called after clicking on the plot.
  1032. def doit(event):
  1033. self.app.info("Painting polygon...")
  1034. self.app.plotcanvas.mpl_disconnect(subscription)
  1035. point = [event.xdata, event.ydata]
  1036. self.paint_poly_single_click(point, tooldia, overlap,
  1037. connect=self.options["pathconnect"],
  1038. contour=self.options["paintcontour"])
  1039. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  1040. def paint_poly_single_click(self, inside_pt, tooldia, overlap,
  1041. outname=None, connect=True, contour=True):
  1042. """
  1043. Paints a polygon selected by clicking on its interior.
  1044. Note:
  1045. * The margin is taken directly from the form.
  1046. :param inside_pt: [x, y]
  1047. :param tooldia: Diameter of the painting tool
  1048. :param overlap: Overlap of the tool between passes.
  1049. :param outname: Name of the resulting Geometry Object.
  1050. :param connect: Connect lines to avoid tool lifts.
  1051. :param contour: Paint around the edges.
  1052. :return: None
  1053. """
  1054. # Which polygon.
  1055. poly = self.find_polygon(inside_pt)
  1056. # No polygon?
  1057. if poly is None:
  1058. self.app.log.warning('No polygon found.')
  1059. self.app.inform.emit('[warning] No polygon found.')
  1060. return
  1061. proc = self.app.proc_container.new("Painting polygon.")
  1062. name = outname or self.options["name"] + "_paint"
  1063. # Initializes the new geometry object
  1064. def gen_paintarea(geo_obj, app_obj):
  1065. assert isinstance(geo_obj, FlatCAMGeometry), \
  1066. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1067. #assert isinstance(app_obj, App)
  1068. if self.options["paintmethod"] == "seed":
  1069. # Type(cp) == FlatCAMRTreeStorage | None
  1070. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1071. tooldia, overlap=overlap, connect=connect,
  1072. contour=contour)
  1073. elif self.options["paintmethod"] == "lines":
  1074. # Type(cp) == FlatCAMRTreeStorage | None
  1075. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1076. tooldia, overlap=overlap, connect=connect,
  1077. contour=contour)
  1078. else:
  1079. # Type(cp) == FlatCAMRTreeStorage | None
  1080. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1081. tooldia, overlap=overlap, connect=connect,
  1082. contour=contour)
  1083. if cp is not None:
  1084. geo_obj.solid_geometry = list(cp.get_objects())
  1085. geo_obj.options["cnctooldia"] = tooldia
  1086. # Experimental...
  1087. print("Indexing...")
  1088. geo_obj.make_index()
  1089. print("Done")
  1090. self.app.inform.emit("Done.")
  1091. def job_thread(app_obj):
  1092. try:
  1093. app_obj.new_object("geometry", name, gen_paintarea)
  1094. except Exception as e:
  1095. proc.done()
  1096. raise e
  1097. proc.done()
  1098. self.app.inform.emit("Polygon Paint started ...")
  1099. # Promise object with the new name
  1100. self.app.collection.promise(name)
  1101. # Background
  1102. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1103. def paint_poly_all(self, tooldia, overlap, outname=None,
  1104. connect=True, contour=True):
  1105. """
  1106. Paints all polygons in this object.
  1107. :param tooldia:
  1108. :param overlap:
  1109. :param outname:
  1110. :param connect: Connect lines to avoid tool lifts.
  1111. :param contour: Paint around the edges.
  1112. :return:
  1113. """
  1114. proc = self.app.proc_container.new("Painting polygon.")
  1115. name = outname or self.options["name"] + "_paint"
  1116. # This is a recursive generator of individual Polygons.
  1117. # Note: Double check correct implementation. Might exit
  1118. # early if it finds something that is not a Polygon?
  1119. def recurse(geo):
  1120. try:
  1121. for subg in geo:
  1122. for subsubg in recurse(subg):
  1123. yield subsubg
  1124. except TypeError:
  1125. if isinstance(geo, Polygon):
  1126. yield geo
  1127. raise StopIteration
  1128. # Initializes the new geometry object
  1129. def gen_paintarea(geo_obj, app_obj):
  1130. assert isinstance(geo_obj, FlatCAMGeometry), \
  1131. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1132. geo_obj.solid_geometry = []
  1133. for poly in recurse(self.solid_geometry):
  1134. if self.options["paintmethod"] == "seed":
  1135. # Type(cp) == FlatCAMRTreeStorage | None
  1136. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1137. tooldia, overlap=overlap, contour=contour,
  1138. connect=connect)
  1139. elif self.options["paintmethod"] == "lines":
  1140. # Type(cp) == FlatCAMRTreeStorage | None
  1141. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1142. tooldia, overlap=overlap, contour=contour,
  1143. connect=connect)
  1144. else:
  1145. # Type(cp) == FlatCAMRTreeStorage | None
  1146. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1147. tooldia, overlap=overlap, contour=contour,
  1148. connect=connect)
  1149. if cp is not None:
  1150. geo_obj.solid_geometry += list(cp.get_objects())
  1151. geo_obj.options["cnctooldia"] = tooldia
  1152. # Experimental...
  1153. print("Indexing...")
  1154. geo_obj.make_index()
  1155. print("Done")
  1156. self.app.inform.emit("Done.")
  1157. def job_thread(app_obj):
  1158. try:
  1159. app_obj.new_object("geometry", name, gen_paintarea)
  1160. except Exception as e:
  1161. proc.done()
  1162. traceback.print_stack()
  1163. raise e
  1164. proc.done()
  1165. self.app.inform.emit("Polygon Paint started ...")
  1166. # Promise object with the new name
  1167. self.app.collection.promise(name)
  1168. # Background
  1169. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1170. def on_generatecnc_button_click(self, *args):
  1171. self.app.report_usage("geometry_on_generatecnc_button")
  1172. self.read_form()
  1173. self.generatecncjob()
  1174. def generatecncjob(self,
  1175. z_cut=None,
  1176. z_move=None,
  1177. feedrate=None,
  1178. tooldia=None,
  1179. outname=None,
  1180. spindlespeed=None,
  1181. multidepth=None,
  1182. depthperpass=None,
  1183. use_thread=True):
  1184. """
  1185. Creates a CNCJob out of this Geometry object. The actual
  1186. work is done by the target FlatCAMCNCjob object's
  1187. `generate_from_geometry_2()` method.
  1188. :param z_cut: Cut depth (negative)
  1189. :param z_move: Hight of the tool when travelling (not cutting)
  1190. :param feedrate: Feed rate while cutting
  1191. :param tooldia: Tool diameter
  1192. :param outname: Name of the new object
  1193. :param spindlespeed: Spindle speed (RPM)
  1194. :return: None
  1195. """
  1196. outname = outname if outname is not None else self.options["name"] + "_cnc"
  1197. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  1198. z_move = z_move if z_move is not None else self.options["travelz"]
  1199. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  1200. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  1201. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  1202. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  1203. # To allow default value to be "" (optional in gui) and translate to None
  1204. # if not isinstance(spindlespeed, int):
  1205. # if isinstance(self.options["spindlespeed"], int) or \
  1206. # isinstance(self.options["spindlespeed"], float):
  1207. # spindlespeed = int(self.options["spindlespeed"])
  1208. # else:
  1209. # spindlespeed = None
  1210. if spindlespeed is None:
  1211. # int or None.
  1212. spindlespeed = self.options['spindlespeed']
  1213. # Object initialization function for app.new_object()
  1214. # RUNNING ON SEPARATE THREAD!
  1215. def job_init(job_obj, app_obj):
  1216. assert isinstance(job_obj, FlatCAMCNCjob), \
  1217. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1218. # Propagate options
  1219. job_obj.options["tooldia"] = tooldia
  1220. app_obj.progress.emit(20)
  1221. job_obj.z_cut = z_cut
  1222. job_obj.z_move = z_move
  1223. job_obj.feedrate = feedrate
  1224. job_obj.spindlespeed = spindlespeed
  1225. app_obj.progress.emit(40)
  1226. # TODO: The tolerance should not be hard coded. Just for testing.
  1227. job_obj.generate_from_geometry_2(self,
  1228. multidepth=multidepth,
  1229. depthpercut=depthperpass,
  1230. tolerance=0.0005)
  1231. app_obj.progress.emit(50)
  1232. job_obj.gcode_parse()
  1233. app_obj.progress.emit(80)
  1234. if use_thread:
  1235. # To be run in separate thread
  1236. def job_thread(app_obj):
  1237. with self.app.proc_container.new("Generating CNC Job."):
  1238. app_obj.new_object("cncjob", outname, job_init)
  1239. app_obj.inform.emit("CNCjob created: %s" % outname)
  1240. app_obj.progress.emit(100)
  1241. # Create a promise with the name
  1242. self.app.collection.promise(outname)
  1243. # Send to worker
  1244. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1245. else:
  1246. self.app.new_object("cncjob", outname, job_init)
  1247. def on_plot_cb_click(self, *args): # TODO: args not needed
  1248. if self.muted_ui:
  1249. return
  1250. self.read_form_item('plot')
  1251. self.plot()
  1252. def scale(self, factor):
  1253. """
  1254. Scales all geometry by a given factor.
  1255. :param factor: Factor by which to scale the object's geometry/
  1256. :type factor: float
  1257. :return: None
  1258. :rtype: None
  1259. """
  1260. if type(self.solid_geometry) == list:
  1261. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  1262. for g in self.solid_geometry]
  1263. else:
  1264. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  1265. origin=(0, 0))
  1266. def offset(self, vect):
  1267. """
  1268. Offsets all geometry by a given vector/
  1269. :param vect: (x, y) vector by which to offset the object's geometry.
  1270. :type vect: tuple
  1271. :return: None
  1272. :rtype: None
  1273. """
  1274. dx, dy = vect
  1275. def translate_recursion(geom):
  1276. if type(geom) == list:
  1277. geoms=list()
  1278. for local_geom in geom:
  1279. geoms.append(translate_recursion(local_geom))
  1280. return geoms
  1281. else:
  1282. return affinity.translate(geom, xoff=dx, yoff=dy)
  1283. self.solid_geometry=translate_recursion(self.solid_geometry)
  1284. def convert_units(self, units):
  1285. factor = Geometry.convert_units(self, units)
  1286. self.options['cutz'] *= factor
  1287. self.options['travelz'] *= factor
  1288. self.options['feedrate'] *= factor
  1289. self.options['cnctooldia'] *= factor
  1290. self.options['painttooldia'] *= factor
  1291. self.options['paintmargin'] *= factor
  1292. return factor
  1293. def plot_element(self, element):
  1294. try:
  1295. for sub_el in element:
  1296. self.plot_element(sub_el)
  1297. except TypeError: # Element is not iterable...
  1298. if type(element) == Polygon:
  1299. x, y = element.exterior.coords.xy
  1300. self.axes.plot(x, y, 'r-')
  1301. for ints in element.interiors:
  1302. x, y = ints.coords.xy
  1303. self.axes.plot(x, y, 'r-')
  1304. return
  1305. if type(element) == LineString or type(element) == LinearRing:
  1306. x, y = element.coords.xy
  1307. self.axes.plot(x, y, 'r-')
  1308. return
  1309. FlatCAMApp.App.log.warning("Did not plot:" + str(type(element)))
  1310. def plot(self):
  1311. """
  1312. Plots the object into its axes. If None, of if the axes
  1313. are not part of the app's figure, it fetches new ones.
  1314. :return: None
  1315. """
  1316. # Does all the required setup and returns False
  1317. # if the 'ptint' option is set to False.
  1318. if not FlatCAMObj.plot(self):
  1319. return
  1320. # Make sure solid_geometry is iterable.
  1321. # TODO: This method should not modify the object !!!
  1322. # try:
  1323. # _ = iter(self.solid_geometry)
  1324. # except TypeError:
  1325. # if self.solid_geometry is None:
  1326. # self.solid_geometry = []
  1327. # else:
  1328. # self.solid_geometry = [self.solid_geometry]
  1329. #
  1330. # for geo in self.solid_geometry:
  1331. #
  1332. # if type(geo) == Polygon:
  1333. # x, y = geo.exterior.coords.xy
  1334. # self.axes.plot(x, y, 'r-')
  1335. # for ints in geo.interiors:
  1336. # x, y = ints.coords.xy
  1337. # self.axes.plot(x, y, 'r-')
  1338. # continue
  1339. #
  1340. # if type(geo) == LineString or type(geo) == LinearRing:
  1341. # x, y = geo.coords.xy
  1342. # self.axes.plot(x, y, 'r-')
  1343. # continue
  1344. #
  1345. # if type(geo) == MultiPolygon:
  1346. # for poly in geo:
  1347. # x, y = poly.exterior.coords.xy
  1348. # self.axes.plot(x, y, 'r-')
  1349. # for ints in poly.interiors:
  1350. # x, y = ints.coords.xy
  1351. # self.axes.plot(x, y, 'r-')
  1352. # continue
  1353. #
  1354. # FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  1355. self.plot_element(self.solid_geometry)
  1356. self.app.plotcanvas.auto_adjust_axes()