FlatCAMObj.py 61 KB

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