FlatCAMGerber.py 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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. "tool_type": 'circular',
  93. "vtipdia": 0.1,
  94. "vtipangle": 30,
  95. "vcutz": -0.05,
  96. "isotooldia": 0.016,
  97. "isopasses": 1,
  98. "isooverlap": 15,
  99. "milling_type": "cl",
  100. "combine_passes": True,
  101. "noncoppermargin": 0.0,
  102. "noncopperrounded": False,
  103. "bboxmargin": 0.0,
  104. "bboxrounded": False,
  105. "aperture_display": False,
  106. "follow": False,
  107. "iso_scope": 'all',
  108. "iso_type": 'full'
  109. })
  110. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  111. self.iso_type = 2
  112. self.multigeo = False
  113. self.follow = False
  114. self.apertures_row = 0
  115. # store the source file here
  116. self.source_file = ""
  117. # list of rows with apertures plotted
  118. self.marked_rows = []
  119. # Mouse events
  120. self.mr = None
  121. self.mm = None
  122. self.mp = None
  123. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  124. self.poly_dict = {}
  125. # store the status of grid snapping
  126. self.grid_status_memory = None
  127. self.units_found = self.app.defaults['units']
  128. self.fill_color = self.app.defaults['gerber_plot_fill']
  129. self.outline_color = self.app.defaults['gerber_plot_line']
  130. self.alpha_level = 'bf'
  131. # keep track if the UI is built so we don't have to build it every time
  132. self.ui_build = False
  133. # build only once the aperture storage (takes time)
  134. self.build_aperture_storage = False
  135. # Attributes to be included in serialization
  136. # Always append to it because it carries contents
  137. # from predecessors.
  138. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  139. def set_ui(self, ui):
  140. """
  141. Maps options with GUI inputs.
  142. Connects GUI events to methods.
  143. :param ui: GUI object.
  144. :type ui: GerberObjectUI
  145. :return: None
  146. """
  147. FlatCAMObj.set_ui(self, ui)
  148. log.debug("GerberObject.set_ui()")
  149. self.units = self.app.defaults['units'].upper()
  150. self.replotApertures.connect(self.on_mark_cb_click_table)
  151. self.form_fields.update({
  152. "plot": self.ui.plot_cb,
  153. "multicolored": self.ui.multicolored_cb,
  154. "solid": self.ui.solid_cb,
  155. "tool_type": self.ui.tool_type_radio,
  156. "vtipdia": self.ui.tipdia_spinner,
  157. "vtipangle": self.ui.tipangle_spinner,
  158. "vcutz": self.ui.cutz_spinner,
  159. "isotooldia": self.ui.iso_tool_dia_entry,
  160. "isopasses": self.ui.iso_width_entry,
  161. "isooverlap": self.ui.iso_overlap_entry,
  162. "milling_type": self.ui.milling_type_radio,
  163. "combine_passes": self.ui.combine_passes_cb,
  164. "noncoppermargin": self.ui.noncopper_margin_entry,
  165. "noncopperrounded": self.ui.noncopper_rounded_cb,
  166. "bboxmargin": self.ui.bbmargin_entry,
  167. "bboxrounded": self.ui.bbrounded_cb,
  168. "aperture_display": self.ui.aperture_table_visibility_cb,
  169. "follow": self.ui.follow_cb,
  170. "iso_scope": self.ui.iso_scope_radio,
  171. "iso_type": self.ui.iso_type_radio
  172. })
  173. # Fill form fields only on object create
  174. self.to_form()
  175. assert isinstance(self.ui, GerberObjectUI)
  176. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  177. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  178. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  179. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  180. # Tools
  181. self.ui.iso_button.clicked.connect(self.app.isolation_tool.run)
  182. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  183. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  184. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  185. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  186. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  187. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  188. # set the model for the Area Exception comboboxes
  189. self.ui.obj_combo.setModel(self.app.collection)
  190. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  191. self.ui.obj_combo.is_last = True
  192. self.ui.obj_combo.obj_type = {
  193. _("Gerber"): "Gerber", _("Geometry"): "Geometry"
  194. }[self.ui.type_obj_combo.get_value()]
  195. self.on_type_obj_index_changed()
  196. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  197. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type_change)
  198. # establish visibility for the GUI elements found in the slot function
  199. self.ui.tool_type_radio.activated_custom.emit(self.options['tool_type'])
  200. # Show/Hide Advanced Options
  201. if self.app.defaults["global_app_level"] == 'b':
  202. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  203. self.options['tool_type'] = 'circular'
  204. self.ui.tool_type_label.hide()
  205. self.ui.tool_type_radio.hide()
  206. # override the Preferences Value; in Basic mode the Tool Type is always Circular ('C1')
  207. self.ui.tool_type_radio.set_value('circular')
  208. self.ui.tipdialabel.hide()
  209. self.ui.tipdia_spinner.hide()
  210. self.ui.tipanglelabel.hide()
  211. self.ui.tipangle_spinner.hide()
  212. self.ui.cutzlabel.hide()
  213. self.ui.cutz_spinner.hide()
  214. self.ui.apertures_table_label.hide()
  215. self.ui.aperture_table_visibility_cb.hide()
  216. self.ui.milling_type_label.hide()
  217. self.ui.milling_type_radio.hide()
  218. self.ui.iso_type_label.hide()
  219. self.ui.iso_type_radio.hide()
  220. self.ui.follow_cb.hide()
  221. self.ui.except_cb.setChecked(False)
  222. self.ui.except_cb.hide()
  223. else:
  224. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  225. self.ui.tipdia_spinner.valueChanged.connect(self.on_calculate_tooldia)
  226. self.ui.tipangle_spinner.valueChanged.connect(self.on_calculate_tooldia)
  227. self.ui.cutz_spinner.valueChanged.connect(self.on_calculate_tooldia)
  228. if self.app.defaults["gerber_buffering"] == 'no':
  229. self.ui.create_buffer_button.show()
  230. try:
  231. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  232. except TypeError:
  233. pass
  234. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  235. else:
  236. self.ui.create_buffer_button.hide()
  237. # set initial state of the aperture table and associated widgets
  238. self.on_aperture_table_visibility_change()
  239. self.build_ui()
  240. self.units_found = self.app.defaults['units']
  241. def on_calculate_tooldia(self):
  242. try:
  243. tdia = float(self.ui.tipdia_spinner.get_value())
  244. except Exception:
  245. return
  246. try:
  247. dang = float(self.ui.tipangle_spinner.get_value())
  248. except Exception:
  249. return
  250. try:
  251. cutz = float(self.ui.cutz_spinner.get_value())
  252. except Exception:
  253. return
  254. cutz *= -1
  255. if cutz < 0:
  256. cutz *= -1
  257. half_tip_angle = dang / 2
  258. tool_diameter = tdia + (2 * cutz * math.tan(math.radians(half_tip_angle)))
  259. self.ui.iso_tool_dia_entry.set_value(tool_diameter)
  260. def on_type_obj_index_changed(self):
  261. val = self.ui.type_obj_combo.get_value()
  262. obj_type = {"Gerber": 0, "Geometry": 2}[val]
  263. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  264. self.ui.obj_combo.setCurrentIndex(0)
  265. self.ui.obj_combo.obj_type = {_("Gerber"): "Gerber", _("Geometry"): "Geometry"}[val]
  266. def on_tool_type_change(self, state):
  267. if state == 'circular':
  268. self.ui.tipdialabel.hide()
  269. self.ui.tipdia_spinner.hide()
  270. self.ui.tipanglelabel.hide()
  271. self.ui.tipangle_spinner.hide()
  272. self.ui.cutzlabel.hide()
  273. self.ui.cutz_spinner.hide()
  274. self.ui.iso_tool_dia_entry.setDisabled(False)
  275. # update the value in the self.iso_tool_dia_entry once this is selected
  276. self.ui.iso_tool_dia_entry.set_value(self.options['isotooldia'])
  277. else:
  278. self.ui.tipdialabel.show()
  279. self.ui.tipdia_spinner.show()
  280. self.ui.tipanglelabel.show()
  281. self.ui.tipangle_spinner.show()
  282. self.ui.cutzlabel.show()
  283. self.ui.cutz_spinner.show()
  284. self.ui.iso_tool_dia_entry.setDisabled(True)
  285. # update the value in the self.iso_tool_dia_entry once this is selected
  286. self.on_calculate_tooldia()
  287. def build_ui(self):
  288. FlatCAMObj.build_ui(self)
  289. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  290. self.ui_build = True
  291. try:
  292. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  293. self.ui.apertures_table.itemChanged.disconnect()
  294. except (TypeError, AttributeError):
  295. pass
  296. self.apertures_row = 0
  297. aper_no = self.apertures_row + 1
  298. sort = []
  299. for k, v in list(self.apertures.items()):
  300. sort.append(int(k))
  301. sorted_apertures = sorted(sort)
  302. n = len(sorted_apertures)
  303. self.ui.apertures_table.setRowCount(n)
  304. for ap_code in sorted_apertures:
  305. ap_code = str(ap_code)
  306. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  307. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  308. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  309. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  310. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  311. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  312. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  313. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  314. ap_dim_item = QtWidgets.QTableWidgetItem(
  315. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  316. self.decimals, self.apertures[ap_code]['height']
  317. )
  318. )
  319. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  320. elif str(self.apertures[ap_code]['type']) == 'P':
  321. ap_dim_item = QtWidgets.QTableWidgetItem(
  322. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  323. self.decimals, self.apertures[ap_code]['nVertices'])
  324. )
  325. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  326. else:
  327. ap_dim_item = QtWidgets.QTableWidgetItem('')
  328. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  329. try:
  330. if self.apertures[ap_code]['size'] is not None:
  331. ap_size_item = QtWidgets.QTableWidgetItem(
  332. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  333. else:
  334. ap_size_item = QtWidgets.QTableWidgetItem('')
  335. except KeyError:
  336. ap_size_item = QtWidgets.QTableWidgetItem('')
  337. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  338. mark_item = FCCheckBox()
  339. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  340. # if self.ui.aperture_table_visibility_cb.isChecked():
  341. # mark_item.setChecked(True)
  342. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  343. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  344. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  345. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  346. empty_plot_item = QtWidgets.QTableWidgetItem('')
  347. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  348. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  349. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  350. self.apertures_row += 1
  351. self.ui.apertures_table.selectColumn(0)
  352. self.ui.apertures_table.resizeColumnsToContents()
  353. self.ui.apertures_table.resizeRowsToContents()
  354. vertical_header = self.ui.apertures_table.verticalHeader()
  355. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  356. vertical_header.hide()
  357. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  358. horizontal_header = self.ui.apertures_table.horizontalHeader()
  359. horizontal_header.setMinimumSectionSize(10)
  360. horizontal_header.setDefaultSectionSize(70)
  361. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  362. horizontal_header.resizeSection(0, 27)
  363. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  364. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  365. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  366. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  367. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  368. horizontal_header.resizeSection(5, 17)
  369. self.ui.apertures_table.setColumnWidth(5, 17)
  370. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  371. self.ui.apertures_table.setSortingEnabled(False)
  372. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  373. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  374. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  375. if self.marked_rows:
  376. for row in range(self.ui.apertures_table.rowCount()):
  377. try:
  378. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  379. except IndexError:
  380. pass
  381. self.ui_connect()
  382. def ui_connect(self):
  383. for row in range(self.ui.apertures_table.rowCount()):
  384. try:
  385. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  386. except (TypeError, AttributeError):
  387. pass
  388. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  389. try:
  390. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  391. except (TypeError, AttributeError):
  392. pass
  393. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  394. def ui_disconnect(self):
  395. for row in range(self.ui.apertures_table.rowCount()):
  396. try:
  397. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  398. except (TypeError, AttributeError):
  399. pass
  400. try:
  401. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  402. except (TypeError, AttributeError):
  403. pass
  404. def on_generate_buffer(self):
  405. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  406. def buffer_task():
  407. with self.app.proc_container.new('%s...' % _("Buffering")):
  408. if isinstance(self.solid_geometry, list):
  409. self.solid_geometry = MultiPolygon(self.solid_geometry)
  410. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  411. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  412. self.app.inform.emit('[success] %s.' % _("Done"))
  413. self.plot_single_object.emit()
  414. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  415. def on_generatenoncopper_button_click(self, *args):
  416. self.app.defaults.report_usage("gerber_on_generatenoncopper_button")
  417. self.read_form()
  418. name = self.options["name"] + "_noncopper"
  419. def geo_init(geo_obj, app_obj):
  420. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  421. if isinstance(self.solid_geometry, list):
  422. try:
  423. self.solid_geometry = MultiPolygon(self.solid_geometry)
  424. except Exception:
  425. self.solid_geometry = cascaded_union(self.solid_geometry)
  426. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  427. if not self.options["noncopperrounded"]:
  428. bounding_box = bounding_box.envelope
  429. non_copper = bounding_box.difference(self.solid_geometry)
  430. if non_copper is None or non_copper.is_empty:
  431. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  432. return "fail"
  433. geo_obj.solid_geometry = non_copper
  434. self.app.app_obj.new_object("geometry", name, geo_init)
  435. def on_generatebb_button_click(self, *args):
  436. self.app.defaults.report_usage("gerber_on_generatebb_button")
  437. self.read_form()
  438. name = self.options["name"] + "_bbox"
  439. def geo_init(geo_obj, app_obj):
  440. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  441. if isinstance(self.solid_geometry, list):
  442. try:
  443. self.solid_geometry = MultiPolygon(self.solid_geometry)
  444. except Exception:
  445. self.solid_geometry = cascaded_union(self.solid_geometry)
  446. # Bounding box with rounded corners
  447. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  448. if not self.options["bboxrounded"]: # Remove rounded corners
  449. bounding_box = bounding_box.envelope
  450. if bounding_box is None or bounding_box.is_empty:
  451. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  452. return "fail"
  453. geo_obj.solid_geometry = bounding_box
  454. self.app.app_obj.new_object("geometry", name, geo_init)
  455. def on_iso_button_click(self, *args):
  456. obj = self.app.collection.get_active()
  457. self.iso_type = 2
  458. if self.ui.iso_type_radio.get_value() == 'ext':
  459. self.iso_type = 0
  460. if self.ui.iso_type_radio.get_value() == 'int':
  461. self.iso_type = 1
  462. def worker_task(iso_obj, app_obj):
  463. with self.app.proc_container.new(_("Isolating...")):
  464. if self.ui.follow_cb.get_value() is True:
  465. iso_obj.follow_geo()
  466. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  467. iso_obj.ui.plot_cb.toggle()
  468. else:
  469. app_obj.defaults.report_usage("gerber_on_iso_button")
  470. self.read_form()
  471. iso_scope = 'all' if self.ui.iso_scope_radio.get_value() == 'all' else 'single'
  472. self.isolate_handler(iso_type=self.iso_type, iso_scope=iso_scope)
  473. self.app.worker_task.emit({'fcn': worker_task, 'params': [obj, self.app]})
  474. def follow_geo(self, outname=None):
  475. """
  476. Creates a geometry object "following" the gerber paths.
  477. :return: None
  478. """
  479. # default_name = self.options["name"] + "_follow"
  480. # follow_name = outname or default_name
  481. if outname is None:
  482. follow_name = self.options["name"] + "_follow"
  483. else:
  484. follow_name = outname
  485. def follow_init(follow_obj, app):
  486. # Propagate options
  487. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  488. follow_obj.solid_geometry = self.follow_geometry
  489. # TODO: Do something if this is None. Offer changing name?
  490. try:
  491. self.app.app_obj.new_object("geometry", follow_name, follow_init)
  492. except Exception as e:
  493. return "Operation failed: %s" % str(e)
  494. def isolate_handler(self, iso_type, iso_scope):
  495. if iso_scope == 'all':
  496. self.isolate(iso_type=iso_type)
  497. else:
  498. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  499. if self.app.ui.grid_snap_btn.isChecked():
  500. self.grid_status_memory = True
  501. self.app.ui.grid_snap_btn.trigger()
  502. else:
  503. self.grid_status_memory = False
  504. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  505. if self.app.is_legacy is False:
  506. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  507. else:
  508. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  509. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  510. def on_mouse_click_release(self, event):
  511. if self.app.is_legacy is False:
  512. event_pos = event.pos
  513. right_button = 2
  514. self.app.event_is_dragging = self.app.event_is_dragging
  515. else:
  516. event_pos = (event.xdata, event.ydata)
  517. right_button = 3
  518. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  519. try:
  520. x = float(event_pos[0])
  521. y = float(event_pos[1])
  522. except TypeError:
  523. return
  524. event_pos = (x, y)
  525. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  526. if self.app.grid_status():
  527. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  528. else:
  529. curr_pos = (curr_pos[0], curr_pos[1])
  530. if event.button == 1:
  531. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]))
  532. if self.app.selection_type is not None:
  533. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  534. self.app.selection_type = None
  535. elif clicked_poly:
  536. if clicked_poly not in self.poly_dict.values():
  537. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  538. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  539. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  540. visible=True)
  541. self.poly_dict[shape_id] = clicked_poly
  542. self.app.inform.emit(
  543. '%s: %d. %s' % (_("Added polygon"), int(len(self.poly_dict)),
  544. _("Click to add next polygon or right click to start isolation."))
  545. )
  546. else:
  547. try:
  548. for k, v in list(self.poly_dict.items()):
  549. if v == clicked_poly:
  550. self.app.tool_shapes.remove(k)
  551. self.poly_dict.pop(k)
  552. break
  553. except TypeError:
  554. return
  555. self.app.inform.emit(
  556. '%s. %s' % (_("Removed polygon"),
  557. _("Click to add/remove next polygon or right click to start isolation."))
  558. )
  559. self.app.tool_shapes.redraw()
  560. else:
  561. self.app.inform.emit(_("No polygon detected under click position."))
  562. elif event.button == right_button and self.app.event_is_dragging is False:
  563. # restore the Grid snapping if it was active before
  564. if self.grid_status_memory is True:
  565. self.app.ui.grid_snap_btn.trigger()
  566. if self.app.is_legacy is False:
  567. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  568. else:
  569. self.app.plotcanvas.graph_event_disconnect(self.mr)
  570. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  571. self.app.on_mouse_click_release_over_plot)
  572. self.app.tool_shapes.clear(update=True)
  573. if self.poly_dict:
  574. poly_list = deepcopy(list(self.poly_dict.values()))
  575. self.isolate(iso_type=self.iso_type, geometry=poly_list)
  576. self.poly_dict.clear()
  577. else:
  578. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  579. def selection_area_handler(self, start_pos, end_pos, sel_type):
  580. """
  581. :param start_pos: mouse position when the selection LMB click was done
  582. :param end_pos: mouse position when the left mouse button is released
  583. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  584. :return:
  585. """
  586. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  587. # delete previous selection shape
  588. self.app.delete_selection_shape()
  589. added_poly_count = 0
  590. try:
  591. for geo in self.solid_geometry:
  592. if geo not in self.poly_dict.values():
  593. if sel_type is True:
  594. if geo.within(poly_selection):
  595. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  596. shape=geo,
  597. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  598. face_color=self.app.defaults[
  599. 'global_sel_draw_color'] + 'AF',
  600. visible=True)
  601. self.poly_dict[shape_id] = geo
  602. added_poly_count += 1
  603. else:
  604. if poly_selection.intersects(geo):
  605. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  606. shape=geo,
  607. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  608. face_color=self.app.defaults[
  609. 'global_sel_draw_color'] + 'AF',
  610. visible=True)
  611. self.poly_dict[shape_id] = geo
  612. added_poly_count += 1
  613. except TypeError:
  614. if self.solid_geometry not in self.poly_dict.values():
  615. if sel_type is True:
  616. if self.solid_geometry.within(poly_selection):
  617. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  618. shape=self.solid_geometry,
  619. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  620. face_color=self.app.defaults[
  621. 'global_sel_draw_color'] + 'AF',
  622. visible=True)
  623. self.poly_dict[shape_id] = self.solid_geometry
  624. added_poly_count += 1
  625. else:
  626. if poly_selection.intersects(self.solid_geometry):
  627. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  628. shape=self.solid_geometry,
  629. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  630. face_color=self.app.defaults[
  631. 'global_sel_draw_color'] + 'AF',
  632. visible=True)
  633. self.poly_dict[shape_id] = self.solid_geometry
  634. added_poly_count += 1
  635. if added_poly_count > 0:
  636. self.app.tool_shapes.redraw()
  637. self.app.inform.emit(
  638. '%s: %d. %s' % (_("Added polygon"),
  639. int(added_poly_count),
  640. _("Click to add next polygon or right click to start isolation."))
  641. )
  642. else:
  643. self.app.inform.emit(_("No polygon in selection."))
  644. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  645. milling_type=None, follow=None, plot=True):
  646. """
  647. Creates an isolation routing geometry object in the project.
  648. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  649. :param geometry: specific geometry to isolate
  650. :param dia: Tool diameter
  651. :param passes: Number of tool widths to cut
  652. :param overlap: Overlap between passes in fraction of tool diameter
  653. :param outname: Base name of the output object
  654. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  655. :param milling_type: type of milling: conventional or climbing
  656. :param follow: Boolean: if to generate a 'follow' geometry
  657. :param plot: Boolean: if to plot the resulting geometry object
  658. :return: None
  659. """
  660. if geometry is None:
  661. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  662. else:
  663. work_geo = geometry
  664. if dia is None:
  665. dia = float(self.options["isotooldia"])
  666. if passes is None:
  667. passes = int(self.options["isopasses"])
  668. if overlap is None:
  669. overlap = float(self.options["isooverlap"])
  670. overlap /= 100.0
  671. combine = self.options["combine_passes"] if combine is None else bool(combine)
  672. if milling_type is None:
  673. milling_type = self.options["milling_type"]
  674. if iso_type is None:
  675. iso_t = 2
  676. else:
  677. iso_t = iso_type
  678. base_name = self.options["name"]
  679. if combine:
  680. if outname is None:
  681. if self.iso_type == 0:
  682. iso_name = base_name + "_ext_iso"
  683. elif self.iso_type == 1:
  684. iso_name = base_name + "_int_iso"
  685. else:
  686. iso_name = base_name + "_iso"
  687. else:
  688. iso_name = outname
  689. def iso_init(geo_obj, app_obj):
  690. # Propagate options
  691. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  692. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  693. geo_obj.solid_geometry = []
  694. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  695. if self.ui.tool_type_radio.get_value() == 'v':
  696. new_cutz = self.ui.cutz_spinner.get_value()
  697. new_vtipdia = self.ui.tipdia_spinner.get_value()
  698. new_vtipangle = self.ui.tipangle_spinner.get_value()
  699. tool_type = 'V'
  700. else:
  701. new_cutz = self.app.defaults['geometry_cutz']
  702. new_vtipdia = self.app.defaults['geometry_vtipdia']
  703. new_vtipangle = self.app.defaults['geometry_vtipangle']
  704. tool_type = 'C1'
  705. # store here the default data for Geometry Data
  706. default_data = {}
  707. default_data.update({
  708. "name": iso_name,
  709. "plot": self.app.defaults['geometry_plot'],
  710. "cutz": new_cutz,
  711. "vtipdia": new_vtipdia,
  712. "vtipangle": new_vtipangle,
  713. "travelz": self.app.defaults['geometry_travelz'],
  714. "feedrate": self.app.defaults['geometry_feedrate'],
  715. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  716. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  717. "dwell": self.app.defaults['geometry_dwell'],
  718. "dwelltime": self.app.defaults['geometry_dwelltime'],
  719. "multidepth": self.app.defaults['geometry_multidepth'],
  720. "ppname_g": self.app.defaults['geometry_ppname_g'],
  721. "depthperpass": self.app.defaults['geometry_depthperpass'],
  722. "extracut": self.app.defaults['geometry_extracut'],
  723. "extracut_length": self.app.defaults['geometry_extracut_length'],
  724. "toolchange": self.app.defaults['geometry_toolchange'],
  725. "toolchangez": self.app.defaults['geometry_toolchangez'],
  726. "endz": self.app.defaults['geometry_endz'],
  727. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  728. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  729. "startz": self.app.defaults['geometry_startz']
  730. })
  731. geo_obj.tools = {}
  732. geo_obj.tools['1'] = {}
  733. geo_obj.tools.update({
  734. '1': {
  735. 'tooldia': float(self.options["isotooldia"]),
  736. 'offset': 'Path',
  737. 'offset_value': 0.0,
  738. 'type': _('Rough'),
  739. 'tool_type': tool_type,
  740. 'data': default_data,
  741. 'solid_geometry': geo_obj.solid_geometry
  742. }
  743. })
  744. for nr_pass in range(passes):
  745. iso_offset = dia * ((2 * nr_pass + 1) / 2.0000001) - (nr_pass * overlap * dia)
  746. # if milling type is climb then the move is counter-clockwise around features
  747. mill_dir = 1 if milling_type == 'cl' else 0
  748. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  749. follow=follow, nr_passes=nr_pass)
  750. if geom == 'fail':
  751. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  752. return 'fail'
  753. geo_obj.solid_geometry.append(geom)
  754. # update the geometry in the tools
  755. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  756. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  757. # or just looking in the lists (they are one level depth) and if any is not empty
  758. # proceed with object creation, if there are empty and the number of them is the length
  759. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  760. empty_cnt = 0
  761. if not isinstance(geo_obj.solid_geometry, list) and \
  762. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  763. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  764. for g in geo_obj.solid_geometry:
  765. if g:
  766. break
  767. else:
  768. empty_cnt += 1
  769. if empty_cnt == len(geo_obj.solid_geometry):
  770. raise ValidationError("Empty Geometry", None)
  771. else:
  772. app_obj.inform.emit('[success] %s" %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  773. # even if combine is checked, one pass is still single-geo
  774. geo_obj.multigeo = True if passes > 1 else False
  775. # ############################################################
  776. # ########## AREA SUBTRACTION ################################
  777. # ############################################################
  778. if self.ui.except_cb.get_value():
  779. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  780. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  781. # TODO: Do something if this is None. Offer changing name?
  782. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  783. else:
  784. for i in range(passes):
  785. offset = dia * ((2 * i + 1) / 2.0000001) - (i * overlap * dia)
  786. if passes > 1:
  787. if outname is None:
  788. if self.iso_type == 0:
  789. iso_name = base_name + "_ext_iso" + str(i + 1)
  790. elif self.iso_type == 1:
  791. iso_name = base_name + "_int_iso" + str(i + 1)
  792. else:
  793. iso_name = base_name + "_iso" + str(i + 1)
  794. else:
  795. iso_name = outname
  796. else:
  797. if outname is None:
  798. if self.iso_type == 0:
  799. iso_name = base_name + "_ext_iso"
  800. elif self.iso_type == 1:
  801. iso_name = base_name + "_int_iso"
  802. else:
  803. iso_name = base_name + "_iso"
  804. else:
  805. iso_name = outname
  806. def iso_init(geo_obj, fc_obj):
  807. # Propagate options
  808. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  809. if self.ui.tool_type_radio.get_value() == 'v':
  810. geo_obj.tool_type = 'V'
  811. else:
  812. geo_obj.tool_type = 'C1'
  813. # if milling type is climb then the move is counter-clockwise around features
  814. mill_dir = 1 if milling_type == 'cl' else 0
  815. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  816. follow=follow,
  817. nr_passes=i)
  818. if geom == 'fail':
  819. fc_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  820. return 'fail'
  821. geo_obj.solid_geometry = geom
  822. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  823. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  824. # required to be transfered to the Geometry object
  825. if self.ui.tool_type_radio.get_value() == 'v':
  826. new_cutz = self.ui.cutz_spinner.get_value()
  827. new_vtipdia = self.ui.tipdia_spinner.get_value()
  828. new_vtipangle = self.ui.tipangle_spinner.get_value()
  829. tool_type = 'V'
  830. else:
  831. new_cutz = self.app.defaults['geometry_cutz']
  832. new_vtipdia = self.app.defaults['geometry_vtipdia']
  833. new_vtipangle = self.app.defaults['geometry_vtipangle']
  834. tool_type = 'C1'
  835. # store here the default data for Geometry Data
  836. default_data = {}
  837. default_data.update({
  838. "name": iso_name,
  839. "plot": self.app.defaults['geometry_plot'],
  840. "cutz": new_cutz,
  841. "vtipdia": new_vtipdia,
  842. "vtipangle": new_vtipangle,
  843. "travelz": self.app.defaults['geometry_travelz'],
  844. "feedrate": self.app.defaults['geometry_feedrate'],
  845. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  846. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  847. "dwell": self.app.defaults['geometry_dwell'],
  848. "dwelltime": self.app.defaults['geometry_dwelltime'],
  849. "multidepth": self.app.defaults['geometry_multidepth'],
  850. "ppname_g": self.app.defaults['geometry_ppname_g'],
  851. "depthperpass": self.app.defaults['geometry_depthperpass'],
  852. "extracut": self.app.defaults['geometry_extracut'],
  853. "extracut_length": self.app.defaults['geometry_extracut_length'],
  854. "toolchange": self.app.defaults['geometry_toolchange'],
  855. "toolchangez": self.app.defaults['geometry_toolchangez'],
  856. "endz": self.app.defaults['geometry_endz'],
  857. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  858. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  859. "startz": self.app.defaults['geometry_startz']
  860. })
  861. geo_obj.tools = {}
  862. geo_obj.tools['1'] = {}
  863. geo_obj.tools.update({
  864. '1': {
  865. 'tooldia': float(self.options["isotooldia"]),
  866. 'offset': 'Path',
  867. 'offset_value': 0.0,
  868. 'type': _('Rough'),
  869. 'tool_type': tool_type,
  870. 'data': default_data,
  871. 'solid_geometry': geo_obj.solid_geometry
  872. }
  873. })
  874. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  875. # or just looking in the lists (they are one level depth) and if any is not empty
  876. # proceed with object creation, if there are empty and the number of them is the length
  877. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  878. empty_cnt = 0
  879. if not isinstance(geo_obj.solid_geometry, list):
  880. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  881. for g in geo_obj.solid_geometry:
  882. if g:
  883. break
  884. else:
  885. empty_cnt += 1
  886. if empty_cnt == len(geo_obj.solid_geometry):
  887. raise ValidationError("Empty Geometry", None)
  888. else:
  889. fc_obj.inform.emit('[success] %s: %s' %
  890. (_("Isolation geometry created"), geo_obj.options["name"]))
  891. geo_obj.multigeo = False
  892. # ############################################################
  893. # ########## AREA SUBTRACTION ################################
  894. # ############################################################
  895. if self.ui.except_cb.get_value():
  896. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  897. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  898. # TODO: Do something if this is None. Offer changing name?
  899. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  900. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  901. # isolation_geometry produces an envelope that is going on the left of the geometry
  902. # (the copper features). To leave the least amount of burrs on the features
  903. # the tool needs to travel on the right side of the features (this is called conventional milling)
  904. # the first pass is the one cutting all of the features, so it needs to be reversed
  905. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  906. # to cut on the right side of the left over copper i.e on the left side of the features.
  907. if follow:
  908. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  909. else:
  910. try:
  911. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  912. except Exception as e:
  913. log.debug('GerberObject.isolate().generate_envelope() --> %s' % str(e))
  914. return 'fail'
  915. if invert:
  916. try:
  917. pl = []
  918. for p in geom:
  919. if p is not None:
  920. if isinstance(p, Polygon):
  921. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  922. elif isinstance(p, LinearRing):
  923. pl.append(Polygon(p.coords[::-1]))
  924. geom = MultiPolygon(pl)
  925. except TypeError:
  926. if isinstance(geom, Polygon) and geom is not None:
  927. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  928. elif isinstance(geom, LinearRing) and geom is not None:
  929. geom = Polygon(geom.coords[::-1])
  930. else:
  931. log.debug("GerberObject.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  932. type(geom))
  933. except Exception as e:
  934. log.debug("GerberObject.isolate().generate_envelope() Error --> %s" % str(e))
  935. return 'fail'
  936. return geom
  937. def area_subtraction(self, geo, subtractor_geo=None):
  938. """
  939. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  940. :param geo: target geometry from which to subtract
  941. :param subtractor_geo: geometry that acts as subtractor
  942. :return:
  943. """
  944. new_geometry = []
  945. target_geo = geo
  946. if subtractor_geo:
  947. sub_union = cascaded_union(subtractor_geo)
  948. else:
  949. name = self.ui.obj_combo.currentText()
  950. subtractor_obj = self.app.collection.get_by_name(name)
  951. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  952. try:
  953. for geo_elem in target_geo:
  954. if isinstance(geo_elem, Polygon):
  955. for ring in self.poly2rings(geo_elem):
  956. new_geo = ring.difference(sub_union)
  957. if new_geo and not new_geo.is_empty:
  958. new_geometry.append(new_geo)
  959. elif isinstance(geo_elem, MultiPolygon):
  960. for poly in geo_elem:
  961. for ring in self.poly2rings(poly):
  962. new_geo = ring.difference(sub_union)
  963. if new_geo and not new_geo.is_empty:
  964. new_geometry.append(new_geo)
  965. elif isinstance(geo_elem, LineString):
  966. new_geo = geo_elem.difference(sub_union)
  967. if new_geo:
  968. if not new_geo.is_empty:
  969. new_geometry.append(new_geo)
  970. elif isinstance(geo_elem, MultiLineString):
  971. for line_elem in geo_elem:
  972. new_geo = line_elem.difference(sub_union)
  973. if new_geo and not new_geo.is_empty:
  974. new_geometry.append(new_geo)
  975. except TypeError:
  976. if isinstance(target_geo, Polygon):
  977. for ring in self.poly2rings(target_geo):
  978. new_geo = ring.difference(sub_union)
  979. if new_geo:
  980. if not new_geo.is_empty:
  981. new_geometry.append(new_geo)
  982. elif isinstance(target_geo, LineString):
  983. new_geo = target_geo.difference(sub_union)
  984. if new_geo and not new_geo.is_empty:
  985. new_geometry.append(new_geo)
  986. elif isinstance(target_geo, MultiLineString):
  987. for line_elem in target_geo:
  988. new_geo = line_elem.difference(sub_union)
  989. if new_geo and not new_geo.is_empty:
  990. new_geometry.append(new_geo)
  991. return new_geometry
  992. def on_plot_cb_click(self, *args):
  993. if self.muted_ui:
  994. return
  995. self.read_form_item('plot')
  996. self.plot()
  997. def on_solid_cb_click(self, *args):
  998. if self.muted_ui:
  999. return
  1000. self.read_form_item('solid')
  1001. self.plot()
  1002. def on_multicolored_cb_click(self, *args):
  1003. if self.muted_ui:
  1004. return
  1005. self.read_form_item('multicolored')
  1006. self.plot()
  1007. def on_follow_cb_click(self):
  1008. if self.muted_ui:
  1009. return
  1010. self.plot()
  1011. def on_aperture_table_visibility_change(self):
  1012. if self.ui.aperture_table_visibility_cb.isChecked():
  1013. # add the shapes storage for marking apertures
  1014. if self.build_aperture_storage is False:
  1015. self.build_aperture_storage = True
  1016. if self.app.is_legacy is False:
  1017. for ap_code in self.apertures:
  1018. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  1019. else:
  1020. for ap_code in self.apertures:
  1021. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  1022. name=self.options['name'] + str(ap_code))
  1023. self.ui.apertures_table.setVisible(True)
  1024. for ap in self.mark_shapes:
  1025. self.mark_shapes[ap].enabled = True
  1026. self.ui.mark_all_cb.setVisible(True)
  1027. self.ui.mark_all_cb.setChecked(False)
  1028. self.build_ui()
  1029. else:
  1030. self.ui.apertures_table.setVisible(False)
  1031. self.ui.mark_all_cb.setVisible(False)
  1032. # on hide disable all mark plots
  1033. try:
  1034. for row in range(self.ui.apertures_table.rowCount()):
  1035. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  1036. self.clear_plot_apertures()
  1037. # for ap in list(self.mark_shapes.keys()):
  1038. # # self.mark_shapes[ap].enabled = False
  1039. # del self.mark_shapes[ap]
  1040. except Exception as e:
  1041. log.debug(" GerberObject.on_aperture_visibility_changed() --> %s" % str(e))
  1042. def convert_units(self, units):
  1043. """
  1044. Converts the units of the object by scaling dimensions in all geometry
  1045. and options.
  1046. :param units: Units to which to convert the object: "IN" or "MM".
  1047. :type units: str
  1048. :return: None
  1049. :rtype: None
  1050. """
  1051. # units conversion to get a conversion should be done only once even if we found multiple
  1052. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  1053. if self.conversion_done is True:
  1054. log.debug("Gerber units conversion cancelled. Already done.")
  1055. return
  1056. log.debug("FlatCAMObj.GerberObject.convert_units()")
  1057. factor = Gerber.convert_units(self, units)
  1058. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  1059. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  1060. def plot(self, kind=None, **kwargs):
  1061. """
  1062. :param kind: Not used, for compatibility with the plot method for other objects
  1063. :param kwargs: Color and face_color, visible
  1064. :return:
  1065. """
  1066. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot()")
  1067. # Does all the required setup and returns False
  1068. # if the 'ptint' option is set to False.
  1069. if not FlatCAMObj.plot(self):
  1070. return
  1071. if 'color' in kwargs:
  1072. color = kwargs['color']
  1073. else:
  1074. color = self.outline_color
  1075. if 'face_color' in kwargs:
  1076. face_color = kwargs['face_color']
  1077. else:
  1078. face_color = self.fill_color
  1079. if 'visible' not in kwargs:
  1080. visible = self.options['plot']
  1081. else:
  1082. visible = kwargs['visible']
  1083. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  1084. if self.ui.follow_cb.get_value():
  1085. geometry = self.follow_geometry
  1086. else:
  1087. geometry = self.solid_geometry
  1088. # Make sure geometry is iterable.
  1089. try:
  1090. __ = iter(geometry)
  1091. except TypeError:
  1092. geometry = [geometry]
  1093. if self.app.is_legacy is False:
  1094. def random_color():
  1095. r_color = np.random.rand(4)
  1096. r_color[3] = 1
  1097. return r_color
  1098. else:
  1099. def random_color():
  1100. while True:
  1101. r_color = np.random.rand(4)
  1102. r_color[3] = 1
  1103. new_color = '#'
  1104. for idx in range(len(r_color)):
  1105. new_color += '%x' % int(r_color[idx] * 255)
  1106. # do it until a valid color is generated
  1107. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1108. # for a total of 9 chars
  1109. if len(new_color) == 9:
  1110. break
  1111. return new_color
  1112. try:
  1113. if self.options["solid"]:
  1114. for g in geometry:
  1115. if type(g) == Polygon or type(g) == LineString:
  1116. self.add_shape(shape=g, color=color,
  1117. face_color=random_color() if self.options['multicolored']
  1118. else face_color, visible=visible)
  1119. elif type(g) == Point:
  1120. pass
  1121. else:
  1122. try:
  1123. for el in g:
  1124. self.add_shape(shape=el, color=color,
  1125. face_color=random_color() if self.options['multicolored']
  1126. else face_color, visible=visible)
  1127. except TypeError:
  1128. self.add_shape(shape=g, color=color,
  1129. face_color=random_color() if self.options['multicolored']
  1130. else face_color, visible=visible)
  1131. else:
  1132. for g in geometry:
  1133. if type(g) == Polygon or type(g) == LineString:
  1134. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  1135. visible=visible)
  1136. elif type(g) == Point:
  1137. pass
  1138. else:
  1139. for el in g:
  1140. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  1141. visible=visible)
  1142. self.shapes.redraw(
  1143. # update_colors=(self.fill_color, self.outline_color),
  1144. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  1145. )
  1146. except (ObjectDeleted, AttributeError):
  1147. self.shapes.clear(update=True)
  1148. except Exception as e:
  1149. log.debug("GerberObject.plot() --> %s" % str(e))
  1150. # experimental plot() when the solid_geometry is stored in the self.apertures
  1151. def plot_aperture(self, run_thread=True, **kwargs):
  1152. """
  1153. :param run_thread: if True run the aperture plot as a thread in a worker
  1154. :param kwargs: color and face_color
  1155. :return:
  1156. """
  1157. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot_aperture()")
  1158. # Does all the required setup and returns False
  1159. # if the 'ptint' option is set to False.
  1160. # if not FlatCAMObj.plot(self):
  1161. # return
  1162. # for marking apertures, line color and fill color are the same
  1163. if 'color' in kwargs:
  1164. color = kwargs['color']
  1165. else:
  1166. color = self.app.defaults['gerber_plot_fill']
  1167. if 'marked_aperture' not in kwargs:
  1168. return
  1169. else:
  1170. aperture_to_plot_mark = kwargs['marked_aperture']
  1171. if aperture_to_plot_mark is None:
  1172. return
  1173. if 'visible' not in kwargs:
  1174. visibility = True
  1175. else:
  1176. visibility = kwargs['visible']
  1177. with self.app.proc_container.new(_("Plotting Apertures")):
  1178. def job_thread(app_obj):
  1179. try:
  1180. if aperture_to_plot_mark in self.apertures:
  1181. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  1182. if 'solid' in elem:
  1183. geo = elem['solid']
  1184. if type(geo) == Polygon or type(geo) == LineString:
  1185. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  1186. face_color=color, visible=visibility)
  1187. else:
  1188. for el in geo:
  1189. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  1190. face_color=color, visible=visibility)
  1191. self.mark_shapes[aperture_to_plot_mark].redraw()
  1192. except (ObjectDeleted, AttributeError):
  1193. self.clear_plot_apertures()
  1194. except Exception as e:
  1195. log.debug("GerberObject.plot_aperture() --> %s" % str(e))
  1196. if run_thread:
  1197. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  1198. else:
  1199. job_thread(self)
  1200. def clear_plot_apertures(self, aperture='all'):
  1201. """
  1202. :param aperture: string; aperture for which to clear the mark shapes
  1203. :return:
  1204. """
  1205. if self.mark_shapes:
  1206. if aperture == 'all':
  1207. for apid in list(self.apertures.keys()):
  1208. try:
  1209. if self.app.is_legacy is True:
  1210. self.mark_shapes[apid].clear(update=False)
  1211. else:
  1212. self.mark_shapes[apid].clear(update=True)
  1213. except Exception as e:
  1214. log.debug("GerberObject.clear_plot_apertures() 'all' --> %s" % str(e))
  1215. else:
  1216. try:
  1217. if self.app.is_legacy is True:
  1218. self.mark_shapes[aperture].clear(update=False)
  1219. else:
  1220. self.mark_shapes[aperture].clear(update=True)
  1221. except Exception as e:
  1222. log.debug("GerberObject.clear_plot_apertures() 'aperture' --> %s" % str(e))
  1223. def clear_mark_all(self):
  1224. self.ui.mark_all_cb.set_value(False)
  1225. self.marked_rows[:] = []
  1226. def on_mark_cb_click_table(self):
  1227. """
  1228. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  1229. :return:
  1230. """
  1231. self.ui_disconnect()
  1232. try:
  1233. cw = self.sender()
  1234. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  1235. cw_row = cw_index.row()
  1236. except AttributeError:
  1237. cw_row = 0
  1238. except TypeError:
  1239. return
  1240. self.marked_rows[:] = []
  1241. try:
  1242. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  1243. except AttributeError:
  1244. return
  1245. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  1246. self.marked_rows.append(True)
  1247. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1248. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1249. marked_aperture=aperture, visible=True, run_thread=True)
  1250. # self.mark_shapes[aperture].redraw()
  1251. else:
  1252. self.marked_rows.append(False)
  1253. self.clear_plot_apertures(aperture=aperture)
  1254. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1255. # if all the row mark's are enabled also enable the Mark All checkbox
  1256. cb_cnt = 0
  1257. total_row = self.ui.apertures_table.rowCount()
  1258. for row in range(total_row):
  1259. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1260. cb_cnt += 1
  1261. else:
  1262. cb_cnt -= 1
  1263. if cb_cnt < total_row:
  1264. self.ui.mark_all_cb.setChecked(False)
  1265. else:
  1266. self.ui.mark_all_cb.setChecked(True)
  1267. self.ui_connect()
  1268. def on_mark_all_click(self):
  1269. self.ui_disconnect()
  1270. mark_all = self.ui.mark_all_cb.isChecked()
  1271. for row in range(self.ui.apertures_table.rowCount()):
  1272. # update the mark_rows list
  1273. if mark_all:
  1274. self.marked_rows.append(True)
  1275. else:
  1276. self.marked_rows[:] = []
  1277. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1278. mark_cb.setChecked(mark_all)
  1279. if mark_all:
  1280. for aperture in self.apertures:
  1281. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1282. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1283. marked_aperture=aperture, visible=True)
  1284. # HACK: enable/disable the grid for a better look
  1285. self.app.ui.grid_snap_btn.trigger()
  1286. self.app.ui.grid_snap_btn.trigger()
  1287. else:
  1288. self.clear_plot_apertures()
  1289. self.marked_rows[:] = []
  1290. self.ui_connect()
  1291. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1292. """
  1293. Creates a Gerber file content to be exported to a file.
  1294. :param whole: how many digits in the whole part of coordinates
  1295. :param fract: how many decimals in coordinates
  1296. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  1297. :param factor: factor to be applied onto the Gerber coordinates
  1298. :return: Gerber_code
  1299. """
  1300. log.debug("GerberObject.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  1301. def tz_format(x, y, fac):
  1302. x_c = x * fac
  1303. y_c = y * fac
  1304. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1305. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1306. # extract whole part and decimal part
  1307. x_form = x_form.partition('.')
  1308. y_form = y_form.partition('.')
  1309. # left padd the 'whole' part with zeros
  1310. x_whole = x_form[0].rjust(whole, '0')
  1311. y_whole = y_form[0].rjust(whole, '0')
  1312. # restore the coordinate padded in the left with 0 and added the decimal part
  1313. # without the decinal dot
  1314. x_form = x_whole + x_form[2]
  1315. y_form = y_whole + y_form[2]
  1316. return x_form, y_form
  1317. def lz_format(x, y, fac):
  1318. x_c = x * fac
  1319. y_c = y * fac
  1320. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1321. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1322. # pad with rear zeros
  1323. x_form.ljust(length, '0')
  1324. y_form.ljust(length, '0')
  1325. return x_form, y_form
  1326. # Gerber code is stored here
  1327. gerber_code = ''
  1328. # apertures processing
  1329. try:
  1330. length = whole + fract
  1331. if '0' in self.apertures:
  1332. if 'geometry' in self.apertures['0']:
  1333. for geo_elem in self.apertures['0']['geometry']:
  1334. if 'solid' in geo_elem:
  1335. geo = geo_elem['solid']
  1336. if not geo.is_empty:
  1337. gerber_code += 'G36*\n'
  1338. geo_coords = list(geo.exterior.coords)
  1339. # first command is a move with pen-up D02 at the beginning of the geo
  1340. if g_zeros == 'T':
  1341. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1342. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1343. yform=y_formatted)
  1344. else:
  1345. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1346. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1347. yform=y_formatted)
  1348. for coord in geo_coords[1:]:
  1349. if g_zeros == 'T':
  1350. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1351. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1352. yform=y_formatted)
  1353. else:
  1354. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1355. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1356. yform=y_formatted)
  1357. gerber_code += 'D02*\n'
  1358. gerber_code += 'G37*\n'
  1359. clear_list = list(geo.interiors)
  1360. if clear_list:
  1361. gerber_code += '%LPC*%\n'
  1362. for clear_geo in clear_list:
  1363. gerber_code += 'G36*\n'
  1364. geo_coords = list(clear_geo.coords)
  1365. # first command is a move with pen-up D02 at the beginning of the geo
  1366. if g_zeros == 'T':
  1367. x_formatted, y_formatted = tz_format(
  1368. geo_coords[0][0], geo_coords[0][1], factor)
  1369. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1370. yform=y_formatted)
  1371. else:
  1372. x_formatted, y_formatted = lz_format(
  1373. geo_coords[0][0], geo_coords[0][1], factor)
  1374. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1375. yform=y_formatted)
  1376. prev_coord = geo_coords[0]
  1377. for coord in geo_coords[1:]:
  1378. if coord != prev_coord:
  1379. if g_zeros == 'T':
  1380. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1381. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1382. yform=y_formatted)
  1383. else:
  1384. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1385. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1386. yform=y_formatted)
  1387. prev_coord = coord
  1388. gerber_code += 'D02*\n'
  1389. gerber_code += 'G37*\n'
  1390. gerber_code += '%LPD*%\n'
  1391. if 'clear' in geo_elem:
  1392. geo = geo_elem['clear']
  1393. if not geo.is_empty:
  1394. gerber_code += '%LPC*%\n'
  1395. gerber_code += 'G36*\n'
  1396. geo_coords = list(geo.exterior.coords)
  1397. # first command is a move with pen-up D02 at the beginning of the geo
  1398. if g_zeros == 'T':
  1399. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1400. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1401. yform=y_formatted)
  1402. else:
  1403. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1404. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1405. yform=y_formatted)
  1406. prev_coord = geo_coords[0]
  1407. for coord in geo_coords[1:]:
  1408. if coord != prev_coord:
  1409. if g_zeros == 'T':
  1410. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1411. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1412. yform=y_formatted)
  1413. else:
  1414. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1415. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1416. yform=y_formatted)
  1417. prev_coord = coord
  1418. gerber_code += 'D02*\n'
  1419. gerber_code += 'G37*\n'
  1420. gerber_code += '%LPD*%\n'
  1421. except Exception as e:
  1422. log.debug("FlatCAMObj.GerberObject.export_gerber() '0' aperture --> %s" % str(e))
  1423. for apid in self.apertures:
  1424. if apid == '0':
  1425. continue
  1426. else:
  1427. gerber_code += 'D%s*\n' % str(apid)
  1428. if 'geometry' in self.apertures[apid]:
  1429. for geo_elem in self.apertures[apid]['geometry']:
  1430. try:
  1431. if 'follow' in geo_elem:
  1432. geo = geo_elem['follow']
  1433. if not geo.is_empty:
  1434. if isinstance(geo, Point):
  1435. if g_zeros == 'T':
  1436. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1437. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1438. yform=y_formatted)
  1439. else:
  1440. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1441. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1442. yform=y_formatted)
  1443. else:
  1444. geo_coords = list(geo.coords)
  1445. # first command is a move with pen-up D02 at the beginning of the geo
  1446. if g_zeros == 'T':
  1447. x_formatted, y_formatted = tz_format(
  1448. geo_coords[0][0], geo_coords[0][1], factor)
  1449. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1450. yform=y_formatted)
  1451. else:
  1452. x_formatted, y_formatted = lz_format(
  1453. geo_coords[0][0], geo_coords[0][1], factor)
  1454. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1455. yform=y_formatted)
  1456. prev_coord = geo_coords[0]
  1457. for coord in geo_coords[1:]:
  1458. if coord != prev_coord:
  1459. if g_zeros == 'T':
  1460. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1461. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1462. yform=y_formatted)
  1463. else:
  1464. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1465. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1466. yform=y_formatted)
  1467. prev_coord = coord
  1468. # gerber_code += "D02*\n"
  1469. except Exception as e:
  1470. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  1471. try:
  1472. if 'clear' in geo_elem:
  1473. gerber_code += '%LPC*%\n'
  1474. geo = geo_elem['clear']
  1475. if not geo.is_empty:
  1476. if isinstance(geo, Point):
  1477. if g_zeros == 'T':
  1478. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1479. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1480. yform=y_formatted)
  1481. else:
  1482. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1483. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1484. yform=y_formatted)
  1485. elif isinstance(geo, Polygon):
  1486. geo_coords = list(geo.exterior.coords)
  1487. # first command is a move with pen-up D02 at the beginning of the geo
  1488. if g_zeros == 'T':
  1489. x_formatted, y_formatted = tz_format(
  1490. geo_coords[0][0], geo_coords[0][1], factor)
  1491. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1492. yform=y_formatted)
  1493. else:
  1494. x_formatted, y_formatted = lz_format(
  1495. geo_coords[0][0], geo_coords[0][1], factor)
  1496. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1497. yform=y_formatted)
  1498. prev_coord = geo_coords[0]
  1499. for coord in geo_coords[1:]:
  1500. if coord != prev_coord:
  1501. if g_zeros == 'T':
  1502. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1503. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1504. yform=y_formatted)
  1505. else:
  1506. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1507. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1508. yform=y_formatted)
  1509. prev_coord = coord
  1510. for geo_int in geo.interiors:
  1511. geo_coords = list(geo_int.coords)
  1512. # first command is a move with pen-up D02 at the beginning of the geo
  1513. if g_zeros == 'T':
  1514. x_formatted, y_formatted = tz_format(
  1515. geo_coords[0][0], geo_coords[0][1], factor)
  1516. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1517. yform=y_formatted)
  1518. else:
  1519. x_formatted, y_formatted = lz_format(
  1520. geo_coords[0][0], geo_coords[0][1], factor)
  1521. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1522. yform=y_formatted)
  1523. prev_coord = geo_coords[0]
  1524. for coord in geo_coords[1:]:
  1525. if coord != prev_coord:
  1526. if g_zeros == 'T':
  1527. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1528. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1529. xform=x_formatted,
  1530. yform=y_formatted)
  1531. else:
  1532. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1533. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1534. xform=x_formatted,
  1535. yform=y_formatted)
  1536. prev_coord = coord
  1537. else:
  1538. geo_coords = list(geo.coords)
  1539. # first command is a move with pen-up D02 at the beginning of the geo
  1540. if g_zeros == 'T':
  1541. x_formatted, y_formatted = tz_format(
  1542. geo_coords[0][0], geo_coords[0][1], factor)
  1543. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1544. yform=y_formatted)
  1545. else:
  1546. x_formatted, y_formatted = lz_format(
  1547. geo_coords[0][0], geo_coords[0][1], factor)
  1548. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1549. yform=y_formatted)
  1550. prev_coord = geo_coords[0]
  1551. for coord in geo_coords[1:]:
  1552. if coord != prev_coord:
  1553. if g_zeros == 'T':
  1554. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1555. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1556. yform=y_formatted)
  1557. else:
  1558. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1559. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1560. yform=y_formatted)
  1561. prev_coord = coord
  1562. # gerber_code += "D02*\n"
  1563. gerber_code += '%LPD*%\n'
  1564. except Exception as e:
  1565. log.debug("FlatCAMObj.GerberObject.export_gerber() 'clear' --> %s" % str(e))
  1566. if not self.apertures:
  1567. log.debug("FlatCAMObj.GerberObject.export_gerber() --> Gerber Object is empty: no apertures.")
  1568. return 'fail'
  1569. return gerber_code
  1570. def mirror(self, axis, point):
  1571. Gerber.mirror(self, axis=axis, point=point)
  1572. self.replotApertures.emit()
  1573. def offset(self, vect):
  1574. Gerber.offset(self, vect=vect)
  1575. self.replotApertures.emit()
  1576. def rotate(self, angle, point):
  1577. Gerber.rotate(self, angle=angle, point=point)
  1578. self.replotApertures.emit()
  1579. def scale(self, xfactor, yfactor=None, point=None):
  1580. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1581. self.replotApertures.emit()
  1582. def skew(self, angle_x, angle_y, point):
  1583. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1584. self.replotApertures.emit()
  1585. def buffer(self, distance, join, factor=None):
  1586. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1587. self.replotApertures.emit()
  1588. def serialize(self):
  1589. return {
  1590. "options": self.options,
  1591. "kind": self.kind
  1592. }