FlatCAMObj.py 51 KB

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