FlatCAMGerber.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. from AppParsers.ParseGerber import Gerber
  14. from AppObjects.FlatCAMObj import *
  15. import math
  16. import numpy as np
  17. from copy import deepcopy
  18. import gettext
  19. import AppTranslation as fcTranslate
  20. import builtins
  21. fcTranslate.apply_language('strings')
  22. if '_' not in builtins.__dict__:
  23. _ = gettext.gettext
  24. class GerberObject(FlatCAMObj, Gerber):
  25. """
  26. Represents Gerber code.
  27. """
  28. optionChanged = QtCore.pyqtSignal(str)
  29. replotApertures = QtCore.pyqtSignal()
  30. ui_type = GerberObjectUI
  31. @staticmethod
  32. def merge(grb_list, grb_final):
  33. """
  34. Merges the geometry of objects in geo_list into
  35. the geometry of geo_final.
  36. :param grb_list: List of GerberObject Objects to join.
  37. :param grb_final: Destination GeometryObject object.
  38. :return: None
  39. """
  40. if grb_final.solid_geometry is None:
  41. grb_final.solid_geometry = []
  42. grb_final.follow_geometry = []
  43. if not grb_final.apertures:
  44. grb_final.apertures = {}
  45. if type(grb_final.solid_geometry) is not list:
  46. grb_final.solid_geometry = [grb_final.solid_geometry]
  47. grb_final.follow_geometry = [grb_final.follow_geometry]
  48. for grb in grb_list:
  49. # Expand lists
  50. if type(grb) is list:
  51. GerberObject.merge(grb_list=grb, grb_final=grb_final)
  52. else: # If not list, just append
  53. for option in grb.options:
  54. if option != 'name':
  55. try:
  56. grb_final.options[option] = grb.options[option]
  57. except KeyError:
  58. log.warning("Failed to copy option.", option)
  59. try:
  60. for geos in grb.solid_geometry:
  61. grb_final.solid_geometry.append(geos)
  62. grb_final.follow_geometry.append(geos)
  63. except TypeError:
  64. grb_final.solid_geometry.append(grb.solid_geometry)
  65. grb_final.follow_geometry.append(grb.solid_geometry)
  66. for ap in grb.apertures:
  67. if ap not in grb_final.apertures:
  68. grb_final.apertures[ap] = grb.apertures[ap]
  69. else:
  70. # create a list of integers out of the grb.apertures keys and find the max of that value
  71. # then, the aperture duplicate is assigned an id value incremented with 1,
  72. # and finally made string because the apertures dict keys are strings
  73. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  74. grb_final.apertures[max_ap] = {}
  75. grb_final.apertures[max_ap]['geometry'] = []
  76. for k, v in grb.apertures[ap].items():
  77. grb_final.apertures[max_ap][k] = deepcopy(v)
  78. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  79. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  80. def __init__(self, name):
  81. self.decimals = self.app.decimals
  82. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  83. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  84. FlatCAMObj.__init__(self, name)
  85. self.kind = "gerber"
  86. # The 'name' is already in self.options from FlatCAMObj
  87. # Automatically updates the UI
  88. self.options.update({
  89. "plot": True,
  90. "multicolored": False,
  91. "solid": False,
  92. "noncoppermargin": 0.0,
  93. "noncopperrounded": False,
  94. "bboxmargin": 0.0,
  95. "bboxrounded": False,
  96. "aperture_display": False,
  97. "follow": False,
  98. })
  99. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  100. self.iso_type = 2
  101. self.multigeo = False
  102. self.follow = False
  103. self.apertures_row = 0
  104. # store the source file here
  105. self.source_file = ""
  106. # list of rows with apertures plotted
  107. self.marked_rows = []
  108. # Mouse events
  109. self.mr = None
  110. self.mm = None
  111. self.mp = None
  112. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  113. self.poly_dict = {}
  114. # store the status of grid snapping
  115. self.grid_status_memory = None
  116. self.units_found = self.app.defaults['units']
  117. self.fill_color = self.app.defaults['gerber_plot_fill']
  118. self.outline_color = self.app.defaults['gerber_plot_line']
  119. self.alpha_level = 'bf'
  120. # keep track if the UI is built so we don't have to build it every time
  121. self.ui_build = False
  122. # build only once the aperture storage (takes time)
  123. self.build_aperture_storage = False
  124. # Attributes to be included in serialization
  125. # Always append to it because it carries contents
  126. # from predecessors.
  127. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  128. def set_ui(self, ui):
  129. """
  130. Maps options with GUI inputs.
  131. Connects GUI events to methods.
  132. :param ui: GUI object.
  133. :type ui: GerberObjectUI
  134. :return: None
  135. """
  136. FlatCAMObj.set_ui(self, ui)
  137. log.debug("GerberObject.set_ui()")
  138. self.units = self.app.defaults['units'].upper()
  139. self.replotApertures.connect(self.on_mark_cb_click_table)
  140. self.form_fields.update({
  141. "plot": self.ui.plot_cb,
  142. "multicolored": self.ui.multicolored_cb,
  143. "solid": self.ui.solid_cb,
  144. "noncoppermargin": self.ui.noncopper_margin_entry,
  145. "noncopperrounded": self.ui.noncopper_rounded_cb,
  146. "bboxmargin": self.ui.bbmargin_entry,
  147. "bboxrounded": self.ui.bbrounded_cb,
  148. "aperture_display": self.ui.aperture_table_visibility_cb,
  149. "follow": self.ui.follow_cb
  150. })
  151. # Fill form fields only on object create
  152. self.to_form()
  153. assert isinstance(self.ui, GerberObjectUI)
  154. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  155. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  156. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  157. # Tools
  158. self.ui.iso_button.clicked.connect(self.app.isolation_tool.run)
  159. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  160. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  161. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  162. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  163. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  164. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  165. # Show/Hide Advanced Options
  166. if self.app.defaults["global_app_level"] == 'b':
  167. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  168. self.ui.apertures_table_label.hide()
  169. self.ui.aperture_table_visibility_cb.hide()
  170. self.ui.follow_cb.hide()
  171. else:
  172. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  173. if self.app.defaults["gerber_buffering"] == 'no':
  174. self.ui.create_buffer_button.show()
  175. try:
  176. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  177. except TypeError:
  178. pass
  179. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  180. else:
  181. self.ui.create_buffer_button.hide()
  182. # set initial state of the aperture table and associated widgets
  183. self.on_aperture_table_visibility_change()
  184. self.build_ui()
  185. self.units_found = self.app.defaults['units']
  186. def build_ui(self):
  187. FlatCAMObj.build_ui(self)
  188. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  189. self.ui_build = True
  190. try:
  191. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  192. self.ui.apertures_table.itemChanged.disconnect()
  193. except (TypeError, AttributeError):
  194. pass
  195. self.apertures_row = 0
  196. aper_no = self.apertures_row + 1
  197. sort = []
  198. for k, v in list(self.apertures.items()):
  199. sort.append(int(k))
  200. sorted_apertures = sorted(sort)
  201. n = len(sorted_apertures)
  202. self.ui.apertures_table.setRowCount(n)
  203. for ap_code in sorted_apertures:
  204. ap_code = str(ap_code)
  205. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  206. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  207. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  208. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  209. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  210. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  211. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  212. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  213. ap_dim_item = QtWidgets.QTableWidgetItem(
  214. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  215. self.decimals, self.apertures[ap_code]['height']
  216. )
  217. )
  218. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  219. elif str(self.apertures[ap_code]['type']) == 'P':
  220. ap_dim_item = QtWidgets.QTableWidgetItem(
  221. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  222. self.decimals, self.apertures[ap_code]['nVertices'])
  223. )
  224. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  225. else:
  226. ap_dim_item = QtWidgets.QTableWidgetItem('')
  227. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  228. try:
  229. if self.apertures[ap_code]['size'] is not None:
  230. ap_size_item = QtWidgets.QTableWidgetItem(
  231. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  232. else:
  233. ap_size_item = QtWidgets.QTableWidgetItem('')
  234. except KeyError:
  235. ap_size_item = QtWidgets.QTableWidgetItem('')
  236. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  237. mark_item = FCCheckBox()
  238. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  239. # if self.ui.aperture_table_visibility_cb.isChecked():
  240. # mark_item.setChecked(True)
  241. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  242. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  243. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  244. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  245. empty_plot_item = QtWidgets.QTableWidgetItem('')
  246. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  247. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  248. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  249. self.apertures_row += 1
  250. self.ui.apertures_table.selectColumn(0)
  251. self.ui.apertures_table.resizeColumnsToContents()
  252. self.ui.apertures_table.resizeRowsToContents()
  253. vertical_header = self.ui.apertures_table.verticalHeader()
  254. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  255. vertical_header.hide()
  256. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  257. horizontal_header = self.ui.apertures_table.horizontalHeader()
  258. horizontal_header.setMinimumSectionSize(10)
  259. horizontal_header.setDefaultSectionSize(70)
  260. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  261. horizontal_header.resizeSection(0, 27)
  262. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  263. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  264. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  265. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  266. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  267. horizontal_header.resizeSection(5, 17)
  268. self.ui.apertures_table.setColumnWidth(5, 17)
  269. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  270. self.ui.apertures_table.setSortingEnabled(False)
  271. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  272. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  273. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  274. if self.marked_rows:
  275. for row in range(self.ui.apertures_table.rowCount()):
  276. try:
  277. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  278. except IndexError:
  279. pass
  280. self.ui_connect()
  281. def ui_connect(self):
  282. for row in range(self.ui.apertures_table.rowCount()):
  283. try:
  284. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  285. except (TypeError, AttributeError):
  286. pass
  287. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  288. try:
  289. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  290. except (TypeError, AttributeError):
  291. pass
  292. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  293. def ui_disconnect(self):
  294. for row in range(self.ui.apertures_table.rowCount()):
  295. try:
  296. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  297. except (TypeError, AttributeError):
  298. pass
  299. try:
  300. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  301. except (TypeError, AttributeError):
  302. pass
  303. def on_generate_buffer(self):
  304. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  305. def buffer_task():
  306. with self.app.proc_container.new('%s...' % _("Buffering")):
  307. if isinstance(self.solid_geometry, list):
  308. self.solid_geometry = MultiPolygon(self.solid_geometry)
  309. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  310. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  311. self.app.inform.emit('[success] %s.' % _("Done"))
  312. self.plot_single_object.emit()
  313. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  314. def on_generatenoncopper_button_click(self, *args):
  315. self.app.defaults.report_usage("gerber_on_generatenoncopper_button")
  316. self.read_form()
  317. name = self.options["name"] + "_noncopper"
  318. def geo_init(geo_obj, app_obj):
  319. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  320. if isinstance(self.solid_geometry, list):
  321. try:
  322. self.solid_geometry = MultiPolygon(self.solid_geometry)
  323. except Exception:
  324. self.solid_geometry = cascaded_union(self.solid_geometry)
  325. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  326. if not self.options["noncopperrounded"]:
  327. bounding_box = bounding_box.envelope
  328. non_copper = bounding_box.difference(self.solid_geometry)
  329. if non_copper is None or non_copper.is_empty:
  330. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  331. return "fail"
  332. geo_obj.solid_geometry = non_copper
  333. self.app.app_obj.new_object("geometry", name, geo_init)
  334. def on_generatebb_button_click(self, *args):
  335. self.app.defaults.report_usage("gerber_on_generatebb_button")
  336. self.read_form()
  337. name = self.options["name"] + "_bbox"
  338. def geo_init(geo_obj, app_obj):
  339. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  340. if isinstance(self.solid_geometry, list):
  341. try:
  342. self.solid_geometry = MultiPolygon(self.solid_geometry)
  343. except Exception:
  344. self.solid_geometry = cascaded_union(self.solid_geometry)
  345. # Bounding box with rounded corners
  346. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  347. if not self.options["bboxrounded"]: # Remove rounded corners
  348. bounding_box = bounding_box.envelope
  349. if bounding_box is None or bounding_box.is_empty:
  350. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  351. return "fail"
  352. geo_obj.solid_geometry = bounding_box
  353. self.app.app_obj.new_object("geometry", name, geo_init)
  354. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  355. # isolation_geometry produces an envelope that is going on the left of the geometry
  356. # (the copper features). To leave the least amount of burrs on the features
  357. # the tool needs to travel on the right side of the features (this is called conventional milling)
  358. # the first pass is the one cutting all of the features, so it needs to be reversed
  359. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  360. # to cut on the right side of the left over copper i.e on the left side of the features.
  361. if follow:
  362. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  363. else:
  364. try:
  365. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  366. except Exception as e:
  367. log.debug('GerberObject.isolate().generate_envelope() --> %s' % str(e))
  368. return 'fail'
  369. if invert:
  370. try:
  371. pl = []
  372. for p in geom:
  373. if p is not None:
  374. if isinstance(p, Polygon):
  375. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  376. elif isinstance(p, LinearRing):
  377. pl.append(Polygon(p.coords[::-1]))
  378. geom = MultiPolygon(pl)
  379. except TypeError:
  380. if isinstance(geom, Polygon) and geom is not None:
  381. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  382. elif isinstance(geom, LinearRing) and geom is not None:
  383. geom = Polygon(geom.coords[::-1])
  384. else:
  385. log.debug("GerberObject.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  386. type(geom))
  387. except Exception as e:
  388. log.debug("GerberObject.isolate().generate_envelope() Error --> %s" % str(e))
  389. return 'fail'
  390. return geom
  391. def follow_geo(self, outname=None):
  392. """
  393. Creates a geometry object "following" the gerber paths.
  394. :return: None
  395. """
  396. if outname is None:
  397. follow_name = self.options["name"] + "_follow"
  398. else:
  399. follow_name = outname
  400. def follow_init(follow_obj, app):
  401. # Propagate options
  402. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  403. follow_obj.solid_geometry = self.follow_geometry
  404. # TODO: Do something if this is None. Offer changing name?
  405. try:
  406. self.app.app_obj.new_object("geometry", follow_name, follow_init)
  407. except Exception as e:
  408. return "Operation failed: %s" % str(e)
  409. def on_plot_cb_click(self, *args):
  410. if self.muted_ui:
  411. return
  412. self.read_form_item('plot')
  413. self.plot()
  414. def on_solid_cb_click(self, *args):
  415. if self.muted_ui:
  416. return
  417. self.read_form_item('solid')
  418. self.plot()
  419. def on_multicolored_cb_click(self, *args):
  420. if self.muted_ui:
  421. return
  422. self.read_form_item('multicolored')
  423. self.plot()
  424. def on_follow_cb_click(self):
  425. if self.muted_ui:
  426. return
  427. self.plot()
  428. def on_aperture_table_visibility_change(self):
  429. if self.ui.aperture_table_visibility_cb.isChecked():
  430. # add the shapes storage for marking apertures
  431. if self.build_aperture_storage is False:
  432. self.build_aperture_storage = True
  433. if self.app.is_legacy is False:
  434. for ap_code in self.apertures:
  435. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  436. else:
  437. for ap_code in self.apertures:
  438. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  439. name=self.options['name'] + str(ap_code))
  440. self.ui.apertures_table.setVisible(True)
  441. for ap in self.mark_shapes:
  442. self.mark_shapes[ap].enabled = True
  443. self.ui.mark_all_cb.setVisible(True)
  444. self.ui.mark_all_cb.setChecked(False)
  445. self.build_ui()
  446. else:
  447. self.ui.apertures_table.setVisible(False)
  448. self.ui.mark_all_cb.setVisible(False)
  449. # on hide disable all mark plots
  450. try:
  451. for row in range(self.ui.apertures_table.rowCount()):
  452. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  453. self.clear_plot_apertures()
  454. # for ap in list(self.mark_shapes.keys()):
  455. # # self.mark_shapes[ap].enabled = False
  456. # del self.mark_shapes[ap]
  457. except Exception as e:
  458. log.debug(" GerberObject.on_aperture_visibility_changed() --> %s" % str(e))
  459. def convert_units(self, units):
  460. """
  461. Converts the units of the object by scaling dimensions in all geometry
  462. and options.
  463. :param units: Units to which to convert the object: "IN" or "MM".
  464. :type units: str
  465. :return: None
  466. :rtype: None
  467. """
  468. # units conversion to get a conversion should be done only once even if we found multiple
  469. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  470. if self.conversion_done is True:
  471. log.debug("Gerber units conversion cancelled. Already done.")
  472. return
  473. log.debug("FlatCAMObj.GerberObject.convert_units()")
  474. factor = Gerber.convert_units(self, units)
  475. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  476. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  477. def plot(self, kind=None, **kwargs):
  478. """
  479. :param kind: Not used, for compatibility with the plot method for other objects
  480. :param kwargs: Color and face_color, visible
  481. :return:
  482. """
  483. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot()")
  484. # Does all the required setup and returns False
  485. # if the 'ptint' option is set to False.
  486. if not FlatCAMObj.plot(self):
  487. return
  488. if 'color' in kwargs:
  489. color = kwargs['color']
  490. else:
  491. color = self.outline_color
  492. if 'face_color' in kwargs:
  493. face_color = kwargs['face_color']
  494. else:
  495. face_color = self.fill_color
  496. if 'visible' not in kwargs:
  497. visible = self.options['plot']
  498. else:
  499. visible = kwargs['visible']
  500. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  501. if self.ui.follow_cb.get_value():
  502. geometry = self.follow_geometry
  503. else:
  504. geometry = self.solid_geometry
  505. # Make sure geometry is iterable.
  506. try:
  507. __ = iter(geometry)
  508. except TypeError:
  509. geometry = [geometry]
  510. if self.app.is_legacy is False:
  511. def random_color():
  512. r_color = np.random.rand(4)
  513. r_color[3] = 1
  514. return r_color
  515. else:
  516. def random_color():
  517. while True:
  518. r_color = np.random.rand(4)
  519. r_color[3] = 1
  520. new_color = '#'
  521. for idx in range(len(r_color)):
  522. new_color += '%x' % int(r_color[idx] * 255)
  523. # do it until a valid color is generated
  524. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  525. # for a total of 9 chars
  526. if len(new_color) == 9:
  527. break
  528. return new_color
  529. try:
  530. if self.options["solid"]:
  531. for g in geometry:
  532. if type(g) == Polygon or type(g) == LineString:
  533. self.add_shape(shape=g, color=color,
  534. face_color=random_color() if self.options['multicolored']
  535. else face_color, visible=visible)
  536. elif type(g) == Point:
  537. pass
  538. else:
  539. try:
  540. for el in g:
  541. self.add_shape(shape=el, color=color,
  542. face_color=random_color() if self.options['multicolored']
  543. else face_color, visible=visible)
  544. except TypeError:
  545. self.add_shape(shape=g, color=color,
  546. face_color=random_color() if self.options['multicolored']
  547. else face_color, visible=visible)
  548. else:
  549. for g in geometry:
  550. if type(g) == Polygon or type(g) == LineString:
  551. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  552. visible=visible)
  553. elif type(g) == Point:
  554. pass
  555. else:
  556. for el in g:
  557. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  558. visible=visible)
  559. self.shapes.redraw(
  560. # update_colors=(self.fill_color, self.outline_color),
  561. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  562. )
  563. except (ObjectDeleted, AttributeError):
  564. self.shapes.clear(update=True)
  565. except Exception as e:
  566. log.debug("GerberObject.plot() --> %s" % str(e))
  567. # experimental plot() when the solid_geometry is stored in the self.apertures
  568. def plot_aperture(self, run_thread=True, **kwargs):
  569. """
  570. :param run_thread: if True run the aperture plot as a thread in a worker
  571. :param kwargs: color and face_color
  572. :return:
  573. """
  574. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot_aperture()")
  575. # Does all the required setup and returns False
  576. # if the 'ptint' option is set to False.
  577. # if not FlatCAMObj.plot(self):
  578. # return
  579. # for marking apertures, line color and fill color are the same
  580. if 'color' in kwargs:
  581. color = kwargs['color']
  582. else:
  583. color = self.app.defaults['gerber_plot_fill']
  584. if 'marked_aperture' not in kwargs:
  585. return
  586. else:
  587. aperture_to_plot_mark = kwargs['marked_aperture']
  588. if aperture_to_plot_mark is None:
  589. return
  590. if 'visible' not in kwargs:
  591. visibility = True
  592. else:
  593. visibility = kwargs['visible']
  594. with self.app.proc_container.new(_("Plotting Apertures")):
  595. def job_thread(app_obj):
  596. try:
  597. if aperture_to_plot_mark in self.apertures:
  598. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  599. if 'solid' in elem:
  600. geo = elem['solid']
  601. if type(geo) == Polygon or type(geo) == LineString:
  602. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  603. face_color=color, visible=visibility)
  604. else:
  605. for el in geo:
  606. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  607. face_color=color, visible=visibility)
  608. self.mark_shapes[aperture_to_plot_mark].redraw()
  609. except (ObjectDeleted, AttributeError):
  610. self.clear_plot_apertures()
  611. except Exception as e:
  612. log.debug("GerberObject.plot_aperture() --> %s" % str(e))
  613. if run_thread:
  614. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  615. else:
  616. job_thread(self)
  617. def clear_plot_apertures(self, aperture='all'):
  618. """
  619. :param aperture: string; aperture for which to clear the mark shapes
  620. :return:
  621. """
  622. if self.mark_shapes:
  623. if aperture == 'all':
  624. for apid in list(self.apertures.keys()):
  625. try:
  626. if self.app.is_legacy is True:
  627. self.mark_shapes[apid].clear(update=False)
  628. else:
  629. self.mark_shapes[apid].clear(update=True)
  630. except Exception as e:
  631. log.debug("GerberObject.clear_plot_apertures() 'all' --> %s" % str(e))
  632. else:
  633. try:
  634. if self.app.is_legacy is True:
  635. self.mark_shapes[aperture].clear(update=False)
  636. else:
  637. self.mark_shapes[aperture].clear(update=True)
  638. except Exception as e:
  639. log.debug("GerberObject.clear_plot_apertures() 'aperture' --> %s" % str(e))
  640. def clear_mark_all(self):
  641. self.ui.mark_all_cb.set_value(False)
  642. self.marked_rows[:] = []
  643. def on_mark_cb_click_table(self):
  644. """
  645. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  646. :return:
  647. """
  648. self.ui_disconnect()
  649. try:
  650. cw = self.sender()
  651. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  652. cw_row = cw_index.row()
  653. except AttributeError:
  654. cw_row = 0
  655. except TypeError:
  656. return
  657. self.marked_rows[:] = []
  658. try:
  659. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  660. except AttributeError:
  661. return
  662. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  663. self.marked_rows.append(True)
  664. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  665. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  666. marked_aperture=aperture, visible=True, run_thread=True)
  667. # self.mark_shapes[aperture].redraw()
  668. else:
  669. self.marked_rows.append(False)
  670. self.clear_plot_apertures(aperture=aperture)
  671. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  672. # if all the row mark's are enabled also enable the Mark All checkbox
  673. cb_cnt = 0
  674. total_row = self.ui.apertures_table.rowCount()
  675. for row in range(total_row):
  676. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  677. cb_cnt += 1
  678. else:
  679. cb_cnt -= 1
  680. if cb_cnt < total_row:
  681. self.ui.mark_all_cb.setChecked(False)
  682. else:
  683. self.ui.mark_all_cb.setChecked(True)
  684. self.ui_connect()
  685. def on_mark_all_click(self):
  686. self.ui_disconnect()
  687. mark_all = self.ui.mark_all_cb.isChecked()
  688. for row in range(self.ui.apertures_table.rowCount()):
  689. # update the mark_rows list
  690. if mark_all:
  691. self.marked_rows.append(True)
  692. else:
  693. self.marked_rows[:] = []
  694. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  695. mark_cb.setChecked(mark_all)
  696. if mark_all:
  697. for aperture in self.apertures:
  698. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  699. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  700. marked_aperture=aperture, visible=True)
  701. # HACK: enable/disable the grid for a better look
  702. self.app.ui.grid_snap_btn.trigger()
  703. self.app.ui.grid_snap_btn.trigger()
  704. else:
  705. self.clear_plot_apertures()
  706. self.marked_rows[:] = []
  707. self.ui_connect()
  708. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  709. """
  710. Creates a Gerber file content to be exported to a file.
  711. :param whole: how many digits in the whole part of coordinates
  712. :param fract: how many decimals in coordinates
  713. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  714. :param factor: factor to be applied onto the Gerber coordinates
  715. :return: Gerber_code
  716. """
  717. log.debug("GerberObject.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  718. def tz_format(x, y, fac):
  719. x_c = x * fac
  720. y_c = y * fac
  721. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  722. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  723. # extract whole part and decimal part
  724. x_form = x_form.partition('.')
  725. y_form = y_form.partition('.')
  726. # left padd the 'whole' part with zeros
  727. x_whole = x_form[0].rjust(whole, '0')
  728. y_whole = y_form[0].rjust(whole, '0')
  729. # restore the coordinate padded in the left with 0 and added the decimal part
  730. # without the decinal dot
  731. x_form = x_whole + x_form[2]
  732. y_form = y_whole + y_form[2]
  733. return x_form, y_form
  734. def lz_format(x, y, fac):
  735. x_c = x * fac
  736. y_c = y * fac
  737. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  738. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  739. # pad with rear zeros
  740. x_form.ljust(length, '0')
  741. y_form.ljust(length, '0')
  742. return x_form, y_form
  743. # Gerber code is stored here
  744. gerber_code = ''
  745. # apertures processing
  746. try:
  747. length = whole + fract
  748. if '0' in self.apertures:
  749. if 'geometry' in self.apertures['0']:
  750. for geo_elem in self.apertures['0']['geometry']:
  751. if 'solid' in geo_elem:
  752. geo = geo_elem['solid']
  753. if not geo.is_empty:
  754. gerber_code += 'G36*\n'
  755. geo_coords = list(geo.exterior.coords)
  756. # first command is a move with pen-up D02 at the beginning of the geo
  757. if g_zeros == 'T':
  758. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  759. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  760. yform=y_formatted)
  761. else:
  762. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  763. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  764. yform=y_formatted)
  765. for coord in geo_coords[1:]:
  766. if g_zeros == 'T':
  767. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  768. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  769. yform=y_formatted)
  770. else:
  771. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  772. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  773. yform=y_formatted)
  774. gerber_code += 'D02*\n'
  775. gerber_code += 'G37*\n'
  776. clear_list = list(geo.interiors)
  777. if clear_list:
  778. gerber_code += '%LPC*%\n'
  779. for clear_geo in clear_list:
  780. gerber_code += 'G36*\n'
  781. geo_coords = list(clear_geo.coords)
  782. # first command is a move with pen-up D02 at the beginning of the geo
  783. if g_zeros == 'T':
  784. x_formatted, y_formatted = tz_format(
  785. geo_coords[0][0], geo_coords[0][1], factor)
  786. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  787. yform=y_formatted)
  788. else:
  789. x_formatted, y_formatted = lz_format(
  790. geo_coords[0][0], geo_coords[0][1], factor)
  791. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  792. yform=y_formatted)
  793. prev_coord = geo_coords[0]
  794. for coord in geo_coords[1:]:
  795. if coord != prev_coord:
  796. if g_zeros == 'T':
  797. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  798. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  799. yform=y_formatted)
  800. else:
  801. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  802. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  803. yform=y_formatted)
  804. prev_coord = coord
  805. gerber_code += 'D02*\n'
  806. gerber_code += 'G37*\n'
  807. gerber_code += '%LPD*%\n'
  808. if 'clear' in geo_elem:
  809. geo = geo_elem['clear']
  810. if not geo.is_empty:
  811. gerber_code += '%LPC*%\n'
  812. gerber_code += 'G36*\n'
  813. geo_coords = list(geo.exterior.coords)
  814. # first command is a move with pen-up D02 at the beginning of the geo
  815. if g_zeros == 'T':
  816. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  817. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  818. yform=y_formatted)
  819. else:
  820. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  821. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  822. yform=y_formatted)
  823. prev_coord = geo_coords[0]
  824. for coord in geo_coords[1:]:
  825. if coord != prev_coord:
  826. if g_zeros == 'T':
  827. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  828. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  829. yform=y_formatted)
  830. else:
  831. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  832. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  833. yform=y_formatted)
  834. prev_coord = coord
  835. gerber_code += 'D02*\n'
  836. gerber_code += 'G37*\n'
  837. gerber_code += '%LPD*%\n'
  838. except Exception as e:
  839. log.debug("FlatCAMObj.GerberObject.export_gerber() '0' aperture --> %s" % str(e))
  840. for apid in self.apertures:
  841. if apid == '0':
  842. continue
  843. else:
  844. gerber_code += 'D%s*\n' % str(apid)
  845. if 'geometry' in self.apertures[apid]:
  846. for geo_elem in self.apertures[apid]['geometry']:
  847. try:
  848. if 'follow' in geo_elem:
  849. geo = geo_elem['follow']
  850. if not geo.is_empty:
  851. if isinstance(geo, Point):
  852. if g_zeros == 'T':
  853. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  854. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  855. yform=y_formatted)
  856. else:
  857. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  858. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  859. yform=y_formatted)
  860. else:
  861. geo_coords = list(geo.coords)
  862. # first command is a move with pen-up D02 at the beginning of the geo
  863. if g_zeros == 'T':
  864. x_formatted, y_formatted = tz_format(
  865. geo_coords[0][0], geo_coords[0][1], factor)
  866. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  867. yform=y_formatted)
  868. else:
  869. x_formatted, y_formatted = lz_format(
  870. geo_coords[0][0], geo_coords[0][1], factor)
  871. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  872. yform=y_formatted)
  873. prev_coord = geo_coords[0]
  874. for coord in geo_coords[1:]:
  875. if coord != prev_coord:
  876. if g_zeros == 'T':
  877. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  878. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  879. yform=y_formatted)
  880. else:
  881. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  882. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  883. yform=y_formatted)
  884. prev_coord = coord
  885. # gerber_code += "D02*\n"
  886. except Exception as e:
  887. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  888. try:
  889. if 'clear' in geo_elem:
  890. gerber_code += '%LPC*%\n'
  891. geo = geo_elem['clear']
  892. if not geo.is_empty:
  893. if isinstance(geo, Point):
  894. if g_zeros == 'T':
  895. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  896. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  897. yform=y_formatted)
  898. else:
  899. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  900. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  901. yform=y_formatted)
  902. elif isinstance(geo, Polygon):
  903. geo_coords = list(geo.exterior.coords)
  904. # first command is a move with pen-up D02 at the beginning of the geo
  905. if g_zeros == 'T':
  906. x_formatted, y_formatted = tz_format(
  907. geo_coords[0][0], geo_coords[0][1], factor)
  908. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  909. yform=y_formatted)
  910. else:
  911. x_formatted, y_formatted = lz_format(
  912. geo_coords[0][0], geo_coords[0][1], factor)
  913. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  914. yform=y_formatted)
  915. prev_coord = geo_coords[0]
  916. for coord in geo_coords[1:]:
  917. if coord != prev_coord:
  918. if g_zeros == 'T':
  919. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  920. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  921. yform=y_formatted)
  922. else:
  923. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  924. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  925. yform=y_formatted)
  926. prev_coord = coord
  927. for geo_int in geo.interiors:
  928. geo_coords = list(geo_int.coords)
  929. # first command is a move with pen-up D02 at the beginning of the geo
  930. if g_zeros == 'T':
  931. x_formatted, y_formatted = tz_format(
  932. geo_coords[0][0], geo_coords[0][1], factor)
  933. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  934. yform=y_formatted)
  935. else:
  936. x_formatted, y_formatted = lz_format(
  937. geo_coords[0][0], geo_coords[0][1], factor)
  938. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  939. yform=y_formatted)
  940. prev_coord = geo_coords[0]
  941. for coord in geo_coords[1:]:
  942. if coord != prev_coord:
  943. if g_zeros == 'T':
  944. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  945. gerber_code += "X{xform}Y{yform}D01*\n".format(
  946. xform=x_formatted,
  947. yform=y_formatted)
  948. else:
  949. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  950. gerber_code += "X{xform}Y{yform}D01*\n".format(
  951. xform=x_formatted,
  952. yform=y_formatted)
  953. prev_coord = coord
  954. else:
  955. geo_coords = list(geo.coords)
  956. # first command is a move with pen-up D02 at the beginning of the geo
  957. if g_zeros == 'T':
  958. x_formatted, y_formatted = tz_format(
  959. geo_coords[0][0], geo_coords[0][1], factor)
  960. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  961. yform=y_formatted)
  962. else:
  963. x_formatted, y_formatted = lz_format(
  964. geo_coords[0][0], geo_coords[0][1], factor)
  965. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  966. yform=y_formatted)
  967. prev_coord = geo_coords[0]
  968. for coord in geo_coords[1:]:
  969. if coord != prev_coord:
  970. if g_zeros == 'T':
  971. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  972. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  973. yform=y_formatted)
  974. else:
  975. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  976. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  977. yform=y_formatted)
  978. prev_coord = coord
  979. # gerber_code += "D02*\n"
  980. gerber_code += '%LPD*%\n'
  981. except Exception as e:
  982. log.debug("FlatCAMObj.GerberObject.export_gerber() 'clear' --> %s" % str(e))
  983. if not self.apertures:
  984. log.debug("FlatCAMObj.GerberObject.export_gerber() --> Gerber Object is empty: no apertures.")
  985. return 'fail'
  986. return gerber_code
  987. def mirror(self, axis, point):
  988. Gerber.mirror(self, axis=axis, point=point)
  989. self.replotApertures.emit()
  990. def offset(self, vect):
  991. Gerber.offset(self, vect=vect)
  992. self.replotApertures.emit()
  993. def rotate(self, angle, point):
  994. Gerber.rotate(self, angle=angle, point=point)
  995. self.replotApertures.emit()
  996. def scale(self, xfactor, yfactor=None, point=None):
  997. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  998. self.replotApertures.emit()
  999. def skew(self, angle_x, angle_y, point):
  1000. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1001. self.replotApertures.emit()
  1002. def buffer(self, distance, join, factor=None):
  1003. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1004. self.replotApertures.emit()
  1005. def serialize(self):
  1006. return {
  1007. "options": self.options,
  1008. "kind": self.kind
  1009. }