FlatCAMObj.py 52 KB

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