FlatCAMObj.py 61 KB

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