FlatCAMGerber.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  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 unary_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. do_buffer_signal = QtCore.pyqtSignal()
  31. ui_type = GerberObjectUI
  32. def __init__(self, name):
  33. self.decimals = self.app.decimals
  34. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  35. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  36. FlatCAMObj.__init__(self, name)
  37. self.kind = "gerber"
  38. # The 'name' is already in self.options from FlatCAMObj
  39. # Automatically updates the UI
  40. self.options.update({
  41. "plot": True,
  42. "multicolored": False,
  43. "solid": False,
  44. "noncoppermargin": 0.0,
  45. "noncopperrounded": False,
  46. "bboxmargin": 0.0,
  47. "bboxrounded": False,
  48. "aperture_display": False,
  49. "follow": False,
  50. "milling_type": 'cl',
  51. })
  52. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  53. self.iso_type = 2
  54. self.multigeo = False
  55. self.follow = False
  56. self.apertures_row = 0
  57. # store the source file here
  58. self.source_file = ""
  59. # list of rows with apertures plotted
  60. self.marked_rows = []
  61. # Mouse events
  62. self.mr = None
  63. self.mm = None
  64. self.mp = None
  65. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  66. self.poly_dict = {}
  67. # store the status of grid snapping
  68. self.grid_status_memory = None
  69. self.units_found = self.app.defaults['units']
  70. self.fill_color = self.app.defaults['gerber_plot_fill']
  71. self.outline_color = self.app.defaults['gerber_plot_line']
  72. self.alpha_level = 'bf'
  73. # keep track if the UI is built so we don't have to build it every time
  74. self.ui_build = False
  75. # aperture marking storage
  76. self.mark_shapes_storage = {}
  77. # Attributes to be included in serialization
  78. # Always append to it because it carries contents
  79. # from predecessors.
  80. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  81. def set_ui(self, ui):
  82. """
  83. Maps options with GUI inputs.
  84. Connects GUI events to methods.
  85. :param ui: GUI object.
  86. :type ui: GerberObjectUI
  87. :return: None
  88. """
  89. FlatCAMObj.set_ui(self, ui)
  90. log.debug("GerberObject.set_ui()")
  91. self.units = self.app.defaults['units'].upper()
  92. self.replotApertures.connect(self.on_mark_cb_click_table)
  93. self.form_fields.update({
  94. "plot": self.ui.plot_cb,
  95. "multicolored": self.ui.multicolored_cb,
  96. "solid": self.ui.solid_cb,
  97. "noncoppermargin": self.ui.noncopper_margin_entry,
  98. "noncopperrounded": self.ui.noncopper_rounded_cb,
  99. "bboxmargin": self.ui.bbmargin_entry,
  100. "bboxrounded": self.ui.bbrounded_cb,
  101. "aperture_display": self.ui.aperture_table_visibility_cb,
  102. "follow": self.ui.follow_cb
  103. })
  104. # Fill form fields only on object create
  105. self.to_form()
  106. assert isinstance(self.ui, GerberObjectUI), \
  107. "Expected a GerberObjectUI, got %s" % type(self.ui)
  108. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  109. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  110. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  111. # Editor
  112. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  113. # Properties
  114. self.ui.properties_button.toggled.connect(self.on_properties)
  115. self.calculations_finished.connect(self.update_area_chull)
  116. # Tools
  117. self.ui.iso_button.clicked.connect(self.app.isolation_tool.run)
  118. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  119. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  120. # Utilties
  121. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  122. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  123. self.ui.util_button.clicked.connect(lambda st: self.ui.util_frame.show() if st else self.ui.util_frame.hide())
  124. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  125. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  126. self.do_buffer_signal.connect(self.on_generate_buffer)
  127. # Show/Hide Advanced Options
  128. if self.app.defaults["global_app_level"] == 'b':
  129. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  130. self.ui.apertures_table_label.hide()
  131. self.ui.aperture_table_visibility_cb.hide()
  132. self.ui.follow_cb.hide()
  133. else:
  134. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  135. if self.app.defaults["gerber_buffering"] == 'no':
  136. self.ui.create_buffer_button.show()
  137. try:
  138. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  139. except TypeError:
  140. pass
  141. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  142. else:
  143. self.ui.create_buffer_button.hide()
  144. # set initial state of the aperture table and associated widgets
  145. self.on_aperture_table_visibility_change()
  146. self.build_ui()
  147. self.units_found = self.app.defaults['units']
  148. def build_ui(self):
  149. FlatCAMObj.build_ui(self)
  150. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  151. self.ui_build = True
  152. try:
  153. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  154. self.ui.apertures_table.itemChanged.disconnect()
  155. except (TypeError, AttributeError):
  156. pass
  157. self.apertures_row = 0
  158. aper_no = self.apertures_row + 1
  159. sort = []
  160. for k in list(self.apertures.keys()):
  161. sort.append(int(k))
  162. sorted_apertures = sorted(sort)
  163. n = len(sorted_apertures)
  164. self.ui.apertures_table.setRowCount(n)
  165. for ap_code in sorted_apertures:
  166. ap_code = str(ap_code)
  167. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  168. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  169. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  170. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  171. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  172. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  173. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  174. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  175. ap_dim_item = QtWidgets.QTableWidgetItem(
  176. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  177. self.decimals, self.apertures[ap_code]['height']
  178. )
  179. )
  180. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  181. elif str(self.apertures[ap_code]['type']) == 'P':
  182. ap_dim_item = QtWidgets.QTableWidgetItem(
  183. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  184. self.decimals, self.apertures[ap_code]['nVertices'])
  185. )
  186. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  187. else:
  188. ap_dim_item = QtWidgets.QTableWidgetItem('')
  189. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  190. try:
  191. if self.apertures[ap_code]['size'] is not None:
  192. ap_size_item = QtWidgets.QTableWidgetItem(
  193. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  194. else:
  195. ap_size_item = QtWidgets.QTableWidgetItem('')
  196. except KeyError:
  197. ap_size_item = QtWidgets.QTableWidgetItem('')
  198. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  199. mark_item = FCCheckBox()
  200. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  201. # if self.ui.aperture_table_visibility_cb.isChecked():
  202. # mark_item.setChecked(True)
  203. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  204. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  205. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  206. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  207. empty_plot_item = QtWidgets.QTableWidgetItem('')
  208. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  209. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  210. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  211. self.apertures_row += 1
  212. self.ui.apertures_table.selectColumn(0)
  213. self.ui.apertures_table.resizeColumnsToContents()
  214. self.ui.apertures_table.resizeRowsToContents()
  215. vertical_header = self.ui.apertures_table.verticalHeader()
  216. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  217. vertical_header.hide()
  218. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  219. horizontal_header = self.ui.apertures_table.horizontalHeader()
  220. horizontal_header.setMinimumSectionSize(10)
  221. horizontal_header.setDefaultSectionSize(70)
  222. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  223. horizontal_header.resizeSection(0, 27)
  224. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  225. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  226. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  227. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  228. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  229. horizontal_header.resizeSection(5, 17)
  230. self.ui.apertures_table.setColumnWidth(5, 17)
  231. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  232. self.ui.apertures_table.setSortingEnabled(False)
  233. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  234. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  235. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  236. if self.marked_rows:
  237. for row in range(self.ui.apertures_table.rowCount()):
  238. try:
  239. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  240. except IndexError:
  241. pass
  242. self.ui_connect()
  243. def ui_connect(self):
  244. for row in range(self.ui.apertures_table.rowCount()):
  245. try:
  246. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  247. except (TypeError, AttributeError):
  248. pass
  249. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  250. try:
  251. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  252. except (TypeError, AttributeError):
  253. pass
  254. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  255. def ui_disconnect(self):
  256. for row in range(self.ui.apertures_table.rowCount()):
  257. try:
  258. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  259. except (TypeError, AttributeError):
  260. pass
  261. try:
  262. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  263. except (TypeError, AttributeError):
  264. pass
  265. @staticmethod
  266. def buffer_handler(geo):
  267. new_geo = geo
  268. if isinstance(new_geo, list):
  269. new_geo = MultiPolygon(new_geo)
  270. new_geo = new_geo.buffer(0.0000001)
  271. new_geo = new_geo.buffer(-0.0000001)
  272. return new_geo
  273. def on_properties(self, state):
  274. if state:
  275. self.ui.properties_frame.show()
  276. else:
  277. self.ui.properties_frame.hide()
  278. return
  279. self.ui.treeWidget.clear()
  280. self.add_properties_items(obj=self, treeWidget=self.ui.treeWidget)
  281. # make sure that the FCTree widget columns are resized to content
  282. self.ui.treeWidget.resize_sig.emit()
  283. def on_generate_buffer(self):
  284. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  285. def buffer_task():
  286. with self.app.proc_container.new('%s...' % _("Buffering")):
  287. output = self.app.pool.apply_async(self.buffer_handler, args=([self.solid_geometry]))
  288. self.solid_geometry = output.get()
  289. self.app.inform.emit('[success] %s.' % _("Done"))
  290. self.plot_single_object.emit()
  291. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  292. def on_generatenoncopper_button_click(self, *args):
  293. self.app.defaults.report_usage("gerber_on_generatenoncopper_button")
  294. self.read_form()
  295. name = self.options["name"] + "_noncopper"
  296. def geo_init(geo_obj, app_obj):
  297. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  298. if isinstance(self.solid_geometry, list):
  299. try:
  300. self.solid_geometry = MultiPolygon(self.solid_geometry)
  301. except Exception:
  302. self.solid_geometry = unary_union(self.solid_geometry)
  303. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  304. if not self.options["noncopperrounded"]:
  305. bounding_box = bounding_box.envelope
  306. non_copper = bounding_box.difference(self.solid_geometry)
  307. if non_copper is None or non_copper.is_empty:
  308. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  309. return "fail"
  310. geo_obj.solid_geometry = non_copper
  311. self.app.app_obj.new_object("geometry", name, geo_init)
  312. def on_generatebb_button_click(self, *args):
  313. self.app.defaults.report_usage("gerber_on_generatebb_button")
  314. self.read_form()
  315. name = self.options["name"] + "_bbox"
  316. def geo_init(geo_obj, app_obj):
  317. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  318. if isinstance(self.solid_geometry, list):
  319. try:
  320. self.solid_geometry = MultiPolygon(self.solid_geometry)
  321. except Exception:
  322. self.solid_geometry = unary_union(self.solid_geometry)
  323. # Bounding box with rounded corners
  324. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  325. if not self.options["bboxrounded"]: # Remove rounded corners
  326. bounding_box = bounding_box.envelope
  327. if bounding_box is None or bounding_box.is_empty:
  328. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  329. return "fail"
  330. geo_obj.solid_geometry = bounding_box
  331. self.app.app_obj.new_object("geometry", name, geo_init)
  332. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  333. milling_type=None, follow=None, plot=True):
  334. """
  335. Creates an isolation routing geometry object in the project.
  336. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  337. :param geometry: specific geometry to isolate
  338. :param dia: Tool diameter
  339. :param passes: Number of tool widths to cut
  340. :param overlap: Overlap between passes in fraction of tool diameter
  341. :param outname: Base name of the output object
  342. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  343. :param milling_type: type of milling: conventional or climbing
  344. :param follow: Boolean: if to generate a 'follow' geometry
  345. :param plot: Boolean: if to plot the resulting geometry object
  346. :return: None
  347. """
  348. if geometry is None:
  349. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  350. else:
  351. work_geo = geometry
  352. if dia is None:
  353. dia = float(self.app.defaults["tools_iso_tooldia"])
  354. if passes is None:
  355. passes = int(self.app.defaults["tools_iso_passes"])
  356. if overlap is None:
  357. overlap = float(self.app.defaults["tools_iso_overlap"])
  358. overlap /= 100.0
  359. combine = self.app.defaults["tools_iso_combine_passes"] if combine is None else bool(combine)
  360. if milling_type is None:
  361. milling_type = self.app.defaults["tools_iso_milling_type"]
  362. if iso_type is None:
  363. iso_t = 2
  364. else:
  365. iso_t = iso_type
  366. base_name = self.options["name"]
  367. if combine:
  368. if outname is None:
  369. if self.iso_type == 0:
  370. iso_name = base_name + "_ext_iso"
  371. elif self.iso_type == 1:
  372. iso_name = base_name + "_int_iso"
  373. else:
  374. iso_name = base_name + "_iso"
  375. else:
  376. iso_name = outname
  377. def iso_init(geo_obj, app_obj):
  378. # Propagate options
  379. geo_obj.options["cnctooldia"] = str(dia)
  380. geo_obj.tool_type = self.app.defaults["tools_iso_tool_type"]
  381. geo_obj.solid_geometry = []
  382. # transfer the Cut Z and Vtip and Vangle values in case that we use the V-Shape tool in Gerber UI
  383. if geo_obj.tool_type.lower() == 'v':
  384. new_cutz = self.app.defaults["tools_iso_tool_cutz"]
  385. new_vtipdia = self.app.defaults["tools_iso_tool_vtipdia"]
  386. new_vtipangle = self.app.defaults["tools_iso_tool_vtipangle"]
  387. tool_type = 'V'
  388. else:
  389. new_cutz = self.app.defaults['geometry_cutz']
  390. new_vtipdia = self.app.defaults['geometry_vtipdia']
  391. new_vtipangle = self.app.defaults['geometry_vtipangle']
  392. tool_type = 'C1'
  393. # store here the default data for Geometry Data
  394. default_data = {}
  395. default_data.update({
  396. "name": iso_name,
  397. "plot": self.app.defaults['geometry_plot'],
  398. "cutz": new_cutz,
  399. "vtipdia": new_vtipdia,
  400. "vtipangle": new_vtipangle,
  401. "travelz": self.app.defaults['geometry_travelz'],
  402. "feedrate": self.app.defaults['geometry_feedrate'],
  403. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  404. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  405. "dwell": self.app.defaults['geometry_dwell'],
  406. "dwelltime": self.app.defaults['geometry_dwelltime'],
  407. "multidepth": self.app.defaults['geometry_multidepth'],
  408. "ppname_g": self.app.defaults['geometry_ppname_g'],
  409. "depthperpass": self.app.defaults['geometry_depthperpass'],
  410. "extracut": self.app.defaults['geometry_extracut'],
  411. "extracut_length": self.app.defaults['geometry_extracut_length'],
  412. "toolchange": self.app.defaults['geometry_toolchange'],
  413. "toolchangez": self.app.defaults['geometry_toolchangez'],
  414. "endz": self.app.defaults['geometry_endz'],
  415. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  416. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  417. "startz": self.app.defaults['geometry_startz']
  418. })
  419. geo_obj.tools = {}
  420. geo_obj.tools['1'] = {}
  421. geo_obj.tools.update({
  422. '1': {
  423. 'tooldia': dia,
  424. 'offset': 'Path',
  425. 'offset_value': 0.0,
  426. 'type': _('Rough'),
  427. 'tool_type': tool_type,
  428. 'data': default_data,
  429. 'solid_geometry': geo_obj.solid_geometry
  430. }
  431. })
  432. for nr_pass in range(passes):
  433. iso_offset = dia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * dia)
  434. # if milling type is climb then the move is counter-clockwise around features
  435. mill_dir = 1 if milling_type == 'cl' else 0
  436. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  437. follow=follow, nr_passes=nr_pass)
  438. if geom == 'fail':
  439. if plot:
  440. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  441. return 'fail'
  442. geo_obj.solid_geometry.append(geom)
  443. # update the geometry in the tools
  444. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  445. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  446. # or just looking in the lists (they are one level depth) and if any is not empty
  447. # proceed with object creation, if there are empty and the number of them is the length
  448. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  449. empty_cnt = 0
  450. if not isinstance(geo_obj.solid_geometry, list) and \
  451. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  452. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  453. for g in geo_obj.solid_geometry:
  454. if g:
  455. break
  456. else:
  457. empty_cnt += 1
  458. if empty_cnt == len(geo_obj.solid_geometry):
  459. raise ValidationError("Empty Geometry", None)
  460. else:
  461. if plot:
  462. app_obj.inform.emit('[success] %s: %s' %
  463. (_("Isolation geometry created"), geo_obj.options["name"]))
  464. # even if combine is checked, one pass is still single-geo
  465. geo_obj.multigeo = True if passes > 1 else False
  466. # ############################################################
  467. # ########## AREA SUBTRACTION ################################
  468. # ############################################################
  469. # if self.app.defaults["tools_iso_except"]:
  470. # self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  471. # geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  472. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  473. else:
  474. for i in range(passes):
  475. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  476. if passes > 1:
  477. if outname is None:
  478. if self.iso_type == 0:
  479. iso_name = base_name + "_ext_iso" + str(i + 1)
  480. elif self.iso_type == 1:
  481. iso_name = base_name + "_int_iso" + str(i + 1)
  482. else:
  483. iso_name = base_name + "_iso" + str(i + 1)
  484. else:
  485. iso_name = outname
  486. else:
  487. if outname is None:
  488. if self.iso_type == 0:
  489. iso_name = base_name + "_ext_iso"
  490. elif self.iso_type == 1:
  491. iso_name = base_name + "_int_iso"
  492. else:
  493. iso_name = base_name + "_iso"
  494. else:
  495. iso_name = outname
  496. def iso_init(geo_obj, app_obj):
  497. # Propagate options
  498. geo_obj.options["cnctooldia"] = str(dia)
  499. geo_obj.tool_type = self.app.defaults["tools_iso_tool_type"]
  500. # if milling type is climb then the move is counter-clockwise around features
  501. mill_dir = 1 if milling_type == 'cl' else 0
  502. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  503. follow=follow, nr_passes=i)
  504. if geom == 'fail':
  505. if plot:
  506. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  507. return 'fail'
  508. geo_obj.solid_geometry = geom
  509. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  510. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  511. # required to be transfered to the Geometry object
  512. if self.app.defaults["tools_iso_tool_type"].lower() == 'v':
  513. new_cutz = self.app.defaults["tools_iso_tool_cutz"]
  514. new_vtipdia = self.app.defaults["tools_iso_tool_vtipdia"]
  515. new_vtipangle = self.app.defaults["tools_iso_tool_vtipangle"]
  516. tool_type = 'V'
  517. else:
  518. new_cutz = self.app.defaults['geometry_cutz']
  519. new_vtipdia = self.app.defaults['geometry_vtipdia']
  520. new_vtipangle = self.app.defaults['geometry_vtipangle']
  521. tool_type = 'C1'
  522. # store here the default data for Geometry Data
  523. default_data = {}
  524. default_data.update({
  525. "name": iso_name,
  526. "plot": self.app.defaults['geometry_plot'],
  527. "cutz": new_cutz,
  528. "vtipdia": new_vtipdia,
  529. "vtipangle": new_vtipangle,
  530. "travelz": self.app.defaults['geometry_travelz'],
  531. "feedrate": self.app.defaults['geometry_feedrate'],
  532. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  533. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  534. "dwell": self.app.defaults['geometry_dwell'],
  535. "dwelltime": self.app.defaults['geometry_dwelltime'],
  536. "multidepth": self.app.defaults['geometry_multidepth'],
  537. "ppname_g": self.app.defaults['geometry_ppname_g'],
  538. "depthperpass": self.app.defaults['geometry_depthperpass'],
  539. "extracut": self.app.defaults['geometry_extracut'],
  540. "extracut_length": self.app.defaults['geometry_extracut_length'],
  541. "toolchange": self.app.defaults['geometry_toolchange'],
  542. "toolchangez": self.app.defaults['geometry_toolchangez'],
  543. "endz": self.app.defaults['geometry_endz'],
  544. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  545. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  546. "startz": self.app.defaults['geometry_startz']
  547. })
  548. geo_obj.tools = {}
  549. geo_obj.tools['1'] = {}
  550. geo_obj.tools.update({
  551. '1': {
  552. 'tooldia': dia,
  553. 'offset': 'Path',
  554. 'offset_value': 0.0,
  555. 'type': _('Rough'),
  556. 'tool_type': tool_type,
  557. 'data': default_data,
  558. 'solid_geometry': geo_obj.solid_geometry
  559. }
  560. })
  561. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  562. # or just looking in the lists (they are one level depth) and if any is not empty
  563. # proceed with object creation, if there are empty and the number of them is the length
  564. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  565. empty_cnt = 0
  566. if not isinstance(geo_obj.solid_geometry, list):
  567. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  568. for g in geo_obj.solid_geometry:
  569. if g:
  570. break
  571. else:
  572. empty_cnt += 1
  573. if empty_cnt == len(geo_obj.solid_geometry):
  574. raise ValidationError("Empty Geometry", None)
  575. else:
  576. if plot:
  577. app_obj.inform.emit('[success] %s: %s' %
  578. (_("Isolation geometry created"), geo_obj.options["name"]))
  579. geo_obj.multigeo = False
  580. # ############################################################
  581. # ########## AREA SUBTRACTION ################################
  582. # ############################################################
  583. # if self.app.defaults["tools_iso_except"]:
  584. # self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  585. # geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  586. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  587. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  588. # isolation_geometry produces an envelope that is going on the left of the geometry
  589. # (the copper features). To leave the least amount of burrs on the features
  590. # the tool needs to travel on the right side of the features (this is called conventional milling)
  591. # the first pass is the one cutting all of the features, so it needs to be reversed
  592. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  593. # to cut on the right side of the left over copper i.e on the left side of the features.
  594. if follow:
  595. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  596. else:
  597. try:
  598. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  599. except Exception as e:
  600. log.debug('GerberObject.isolate().generate_envelope() --> %s' % str(e))
  601. return 'fail'
  602. if invert:
  603. try:
  604. pl = []
  605. for p in geom:
  606. if p is not None:
  607. if isinstance(p, Polygon):
  608. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  609. elif isinstance(p, LinearRing):
  610. pl.append(Polygon(p.coords[::-1]))
  611. geom = MultiPolygon(pl)
  612. except TypeError:
  613. if isinstance(geom, Polygon) and geom is not None:
  614. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  615. elif isinstance(geom, LinearRing) and geom is not None:
  616. geom = Polygon(geom.coords[::-1])
  617. else:
  618. log.debug("GerberObject.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  619. type(geom))
  620. except Exception as e:
  621. log.debug("GerberObject.isolate().generate_envelope() Error --> %s" % str(e))
  622. return 'fail'
  623. return geom
  624. def follow_geo(self, outname=None):
  625. """
  626. Creates a geometry object "following" the gerber paths.
  627. :return: None
  628. """
  629. if outname is None:
  630. follow_name = self.options["name"] + "_follow"
  631. else:
  632. follow_name = outname
  633. def follow_init(follow_obj, app):
  634. # Propagate options
  635. follow_obj.options["cnctooldia"] = str(self.app.defaults["tools_iso_tooldia"])
  636. follow_obj.solid_geometry = self.follow_geometry
  637. # TODO: Do something if this is None. Offer changing name?
  638. try:
  639. self.app.app_obj.new_object("geometry", follow_name, follow_init)
  640. except Exception as e:
  641. return "Operation failed: %s" % str(e)
  642. def on_plot_cb_click(self, *args):
  643. if self.muted_ui:
  644. return
  645. self.read_form_item('plot')
  646. self.plot()
  647. def on_solid_cb_click(self, *args):
  648. if self.muted_ui:
  649. return
  650. self.read_form_item('solid')
  651. self.plot()
  652. def on_multicolored_cb_click(self, *args):
  653. if self.muted_ui:
  654. return
  655. self.read_form_item('multicolored')
  656. self.plot()
  657. def on_follow_cb_click(self):
  658. if self.muted_ui:
  659. return
  660. self.plot()
  661. def on_aperture_table_visibility_change(self):
  662. if self.ui.aperture_table_visibility_cb.isChecked():
  663. # add the shapes storage for marking apertures
  664. for ap_code in self.apertures:
  665. self.mark_shapes_storage[ap_code] = []
  666. self.ui.apertures_table.setVisible(True)
  667. self.mark_shapes.enabled = True
  668. self.ui.mark_all_cb.setVisible(True)
  669. self.ui.mark_all_cb.setChecked(False)
  670. self.build_ui()
  671. else:
  672. self.ui.apertures_table.setVisible(False)
  673. self.ui.mark_all_cb.setVisible(False)
  674. # on hide disable all mark plots
  675. try:
  676. for row in range(self.ui.apertures_table.rowCount()):
  677. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  678. self.clear_plot_apertures()
  679. self.mark_shapes.enabled = False
  680. except Exception as e:
  681. log.debug(" GerberObject.on_aperture_visibility_changed() --> %s" % str(e))
  682. def convert_units(self, units):
  683. """
  684. Converts the units of the object by scaling dimensions in all geometry
  685. and options.
  686. :param units: Units to which to convert the object: "IN" or "MM".
  687. :type units: str
  688. :return: None
  689. :rtype: None
  690. """
  691. # units conversion to get a conversion should be done only once even if we found multiple
  692. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  693. if self.conversion_done is True:
  694. log.debug("Gerber units conversion cancelled. Already done.")
  695. return
  696. log.debug("FlatCAMObj.GerberObject.convert_units()")
  697. factor = Gerber.convert_units(self, units)
  698. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  699. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  700. def plot(self, kind=None, **kwargs):
  701. """
  702. :param kind: Not used, for compatibility with the plot method for other objects
  703. :param kwargs: Color and face_color, visible
  704. :return:
  705. """
  706. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot()")
  707. # Does all the required setup and returns False
  708. # if the 'ptint' option is set to False.
  709. if not FlatCAMObj.plot(self):
  710. return
  711. if 'color' in kwargs:
  712. color = kwargs['color']
  713. else:
  714. color = self.outline_color
  715. if 'face_color' in kwargs:
  716. face_color = kwargs['face_color']
  717. else:
  718. face_color = self.fill_color
  719. if 'visible' not in kwargs:
  720. visible = self.options['plot']
  721. else:
  722. visible = kwargs['visible']
  723. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  724. if self.ui.follow_cb.get_value():
  725. geometry = self.follow_geometry
  726. else:
  727. geometry = self.solid_geometry
  728. # Make sure geometry is iterable.
  729. try:
  730. __ = iter(geometry)
  731. except TypeError:
  732. geometry = [geometry]
  733. if self.app.is_legacy is False:
  734. def random_color():
  735. r_color = np.random.rand(4)
  736. r_color[3] = 1
  737. return r_color
  738. else:
  739. def random_color():
  740. while True:
  741. r_color = np.random.rand(4)
  742. r_color[3] = 1
  743. new_color = '#'
  744. for idx in range(len(r_color)):
  745. new_color += '%x' % int(r_color[idx] * 255)
  746. # do it until a valid color is generated
  747. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  748. # for a total of 9 chars
  749. if len(new_color) == 9:
  750. break
  751. return new_color
  752. try:
  753. if self.options["solid"]:
  754. for g in geometry:
  755. if type(g) == Polygon or type(g) == LineString:
  756. self.add_shape(shape=g, color=color,
  757. face_color=random_color() if self.options['multicolored']
  758. else face_color, visible=visible)
  759. elif type(g) == Point:
  760. pass
  761. else:
  762. try:
  763. for el in g:
  764. self.add_shape(shape=el, color=color,
  765. face_color=random_color() if self.options['multicolored']
  766. else face_color, visible=visible)
  767. except TypeError:
  768. self.add_shape(shape=g, color=color,
  769. face_color=random_color() if self.options['multicolored']
  770. else face_color, visible=visible)
  771. else:
  772. for g in geometry:
  773. if type(g) == Polygon or type(g) == LineString:
  774. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  775. visible=visible)
  776. elif type(g) == Point:
  777. pass
  778. else:
  779. for el in g:
  780. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  781. visible=visible)
  782. self.shapes.redraw(
  783. # update_colors=(self.fill_color, self.outline_color),
  784. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  785. )
  786. except (ObjectDeleted, AttributeError):
  787. self.shapes.clear(update=True)
  788. except Exception as e:
  789. log.debug("GerberObject.plot() --> %s" % str(e))
  790. # experimental plot() when the solid_geometry is stored in the self.apertures
  791. def plot_aperture(self, only_flashes=False, run_thread=False, **kwargs):
  792. """
  793. :param only_flashes: plot only flashed
  794. :param run_thread: if True run the aperture plot as a thread in a worker
  795. :param kwargs: color and face_color
  796. :return:
  797. """
  798. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot_aperture()")
  799. # Does all the required setup and returns False
  800. # if the 'ptint' option is set to False.
  801. # if not FlatCAMObj.plot(self):
  802. # return
  803. # for marking apertures, line color and fill color are the same
  804. if 'color' in kwargs:
  805. color = kwargs['color']
  806. else:
  807. color = self.app.defaults['gerber_plot_fill']
  808. if 'marked_aperture' in kwargs:
  809. aperture_to_plot_mark = kwargs['marked_aperture']
  810. if aperture_to_plot_mark is None:
  811. return
  812. else:
  813. return
  814. if 'visible' not in kwargs:
  815. visibility = True
  816. else:
  817. visibility = kwargs['visible']
  818. def job_thread(app_obj):
  819. with self.app.proc_container.new(_("Plotting Apertures")):
  820. try:
  821. if aperture_to_plot_mark in self.apertures:
  822. for elem in app_obj.apertures[aperture_to_plot_mark]['geometry']:
  823. if 'solid' in elem:
  824. if only_flashes and not isinstance(elem['follow'], Point):
  825. continue
  826. geo = elem['solid']
  827. try:
  828. for el in geo:
  829. shape_key = app_obj.add_mark_shape(shape=el, color=color, face_color=color,
  830. visible=visibility)
  831. app_obj.mark_shapes_storage[aperture_to_plot_mark].append(shape_key)
  832. except TypeError:
  833. shape_key = app_obj.add_mark_shape(shape=geo, color=color, face_color=color,
  834. visible=visibility)
  835. app_obj.mark_shapes_storage[aperture_to_plot_mark].append(shape_key)
  836. app_obj.mark_shapes.redraw()
  837. except (ObjectDeleted, AttributeError):
  838. app_obj.clear_plot_apertures()
  839. except Exception as e:
  840. log.debug("GerberObject.plot_aperture() --> %s" % str(e))
  841. if run_thread:
  842. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  843. else:
  844. job_thread(self)
  845. def clear_plot_apertures(self, aperture='all'):
  846. """
  847. :param aperture: string; aperture for which to clear the mark shapes
  848. :return:
  849. """
  850. if self.mark_shapes_storage:
  851. if aperture == 'all':
  852. val = False if self.app.is_legacy is True else True
  853. self.mark_shapes.clear(update=val)
  854. else:
  855. for shape_key in self.mark_shapes_storage[aperture]:
  856. try:
  857. self.mark_shapes.remove(shape_key)
  858. except Exception as e:
  859. log.debug("GerberObject.clear_plot_apertures() -> %s" % str(e))
  860. self.mark_shapes_storage[aperture] = []
  861. self.mark_shapes.redraw()
  862. def clear_mark_all(self):
  863. self.ui.mark_all_cb.set_value(False)
  864. self.marked_rows[:] = []
  865. def on_mark_cb_click_table(self):
  866. """
  867. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  868. :return:
  869. """
  870. self.ui_disconnect()
  871. try:
  872. cw = self.sender()
  873. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  874. cw_row = cw_index.row()
  875. except AttributeError:
  876. cw_row = 0
  877. except TypeError:
  878. return
  879. self.marked_rows[:] = []
  880. try:
  881. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  882. except AttributeError:
  883. self.ui_connect()
  884. return
  885. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  886. self.marked_rows.append(True)
  887. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  888. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  889. marked_aperture=aperture, visible=True, run_thread=True)
  890. else:
  891. self.marked_rows.append(False)
  892. self.clear_plot_apertures(aperture=aperture)
  893. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  894. # if all the row mark's are enabled also enable the Mark All checkbox
  895. cb_cnt = 0
  896. total_row = self.ui.apertures_table.rowCount()
  897. for row in range(total_row):
  898. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  899. cb_cnt += 1
  900. else:
  901. cb_cnt -= 1
  902. if cb_cnt < total_row:
  903. self.ui.mark_all_cb.setChecked(False)
  904. else:
  905. self.ui.mark_all_cb.setChecked(True)
  906. self.ui_connect()
  907. def on_mark_all_click(self):
  908. self.ui_disconnect()
  909. mark_all = self.ui.mark_all_cb.isChecked()
  910. for row in range(self.ui.apertures_table.rowCount()):
  911. # update the mark_rows list
  912. if mark_all:
  913. self.marked_rows.append(True)
  914. else:
  915. self.marked_rows[:] = []
  916. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  917. mark_cb.setChecked(mark_all)
  918. if mark_all:
  919. for aperture in self.apertures:
  920. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  921. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  922. marked_aperture=aperture, visible=True)
  923. # HACK: enable/disable the grid for a better look
  924. self.app.ui.grid_snap_btn.trigger()
  925. self.app.ui.grid_snap_btn.trigger()
  926. else:
  927. self.clear_plot_apertures()
  928. self.marked_rows[:] = []
  929. self.ui_connect()
  930. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  931. """
  932. Creates a Gerber file content to be exported to a file.
  933. :param whole: how many digits in the whole part of coordinates
  934. :param fract: how many decimals in coordinates
  935. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  936. :param factor: factor to be applied onto the Gerber coordinates
  937. :return: Gerber_code
  938. """
  939. log.debug("GerberObject.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  940. def tz_format(x, y, fac):
  941. x_c = x * fac
  942. y_c = y * fac
  943. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  944. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  945. # extract whole part and decimal part
  946. x_form = x_form.partition('.')
  947. y_form = y_form.partition('.')
  948. # left padd the 'whole' part with zeros
  949. x_whole = x_form[0].rjust(whole, '0')
  950. y_whole = y_form[0].rjust(whole, '0')
  951. # restore the coordinate padded in the left with 0 and added the decimal part
  952. # without the decinal dot
  953. x_form = x_whole + x_form[2]
  954. y_form = y_whole + y_form[2]
  955. return x_form, y_form
  956. def lz_format(x, y, fac):
  957. x_c = x * fac
  958. y_c = y * fac
  959. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  960. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  961. # pad with rear zeros
  962. x_form.ljust(length, '0')
  963. y_form.ljust(length, '0')
  964. return x_form, y_form
  965. # Gerber code is stored here
  966. gerber_code = ''
  967. # apertures processing
  968. try:
  969. length = whole + fract
  970. if '0' in self.apertures:
  971. if 'geometry' in self.apertures['0']:
  972. for geo_elem in self.apertures['0']['geometry']:
  973. if 'solid' in geo_elem:
  974. geo = geo_elem['solid']
  975. if not geo.is_empty and not isinstance(geo, LineString) and \
  976. not isinstance(geo, MultiLineString) and not isinstance(geo, Point):
  977. gerber_code += 'G36*\n'
  978. geo_coords = list(geo.exterior.coords)
  979. # first command is a move with pen-up D02 at the beginning of the geo
  980. if g_zeros == 'T':
  981. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  982. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  983. yform=y_formatted)
  984. else:
  985. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  986. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  987. yform=y_formatted)
  988. for coord in geo_coords[1:]:
  989. if g_zeros == 'T':
  990. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  991. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  992. yform=y_formatted)
  993. else:
  994. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  995. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  996. yform=y_formatted)
  997. gerber_code += 'D02*\n'
  998. gerber_code += 'G37*\n'
  999. clear_list = list(geo.interiors)
  1000. if clear_list:
  1001. gerber_code += '%LPC*%\n'
  1002. for clear_geo in clear_list:
  1003. gerber_code += 'G36*\n'
  1004. geo_coords = list(clear_geo.coords)
  1005. # first command is a move with pen-up D02 at the beginning of the geo
  1006. if g_zeros == 'T':
  1007. x_formatted, y_formatted = tz_format(
  1008. geo_coords[0][0], geo_coords[0][1], factor)
  1009. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1010. yform=y_formatted)
  1011. else:
  1012. x_formatted, y_formatted = lz_format(
  1013. geo_coords[0][0], geo_coords[0][1], factor)
  1014. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1015. yform=y_formatted)
  1016. prev_coord = geo_coords[0]
  1017. for coord in geo_coords[1:]:
  1018. if coord != prev_coord:
  1019. if g_zeros == 'T':
  1020. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1021. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1022. yform=y_formatted)
  1023. else:
  1024. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1025. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1026. yform=y_formatted)
  1027. prev_coord = coord
  1028. gerber_code += 'D02*\n'
  1029. gerber_code += 'G37*\n'
  1030. gerber_code += '%LPD*%\n'
  1031. elif isinstance(geo, LineString) or isinstance(geo, MultiLineString) or \
  1032. isinstance(geo, Point):
  1033. try:
  1034. if not geo.is_empty:
  1035. if isinstance(geo, Point):
  1036. if g_zeros == 'T':
  1037. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1038. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1039. yform=y_formatted)
  1040. else:
  1041. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1042. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1043. yform=y_formatted)
  1044. else:
  1045. geo_coords = list(geo.coords)
  1046. # first command is a move with pen-up D02 at the beginning of the geo
  1047. if g_zeros == 'T':
  1048. x_formatted, y_formatted = tz_format(
  1049. geo_coords[0][0], geo_coords[0][1], factor)
  1050. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1051. yform=y_formatted)
  1052. else:
  1053. x_formatted, y_formatted = lz_format(
  1054. geo_coords[0][0], geo_coords[0][1], factor)
  1055. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1056. yform=y_formatted)
  1057. prev_coord = geo_coords[0]
  1058. for coord in geo_coords[1:]:
  1059. if coord != prev_coord:
  1060. if g_zeros == 'T':
  1061. x_formatted, y_formatted = tz_format(coord[0], coord[1],
  1062. factor)
  1063. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1064. xform=x_formatted,
  1065. yform=y_formatted)
  1066. else:
  1067. x_formatted, y_formatted = lz_format(coord[0], coord[1],
  1068. factor)
  1069. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1070. xform=x_formatted,
  1071. yform=y_formatted)
  1072. prev_coord = coord
  1073. # gerber_code += "D02*\n"
  1074. except Exception as e:
  1075. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  1076. if 'clear' in geo_elem:
  1077. geo = geo_elem['clear']
  1078. if not geo.is_empty:
  1079. gerber_code += '%LPC*%\n'
  1080. gerber_code += 'G36*\n'
  1081. geo_coords = list(geo.exterior.coords)
  1082. # first command is a move with pen-up D02 at the beginning of the geo
  1083. if g_zeros == 'T':
  1084. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1085. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1086. yform=y_formatted)
  1087. else:
  1088. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1089. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1090. yform=y_formatted)
  1091. prev_coord = geo_coords[0]
  1092. for coord in geo_coords[1:]:
  1093. if coord != prev_coord:
  1094. if g_zeros == 'T':
  1095. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1096. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1097. yform=y_formatted)
  1098. else:
  1099. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1100. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1101. yform=y_formatted)
  1102. prev_coord = coord
  1103. gerber_code += 'D02*\n'
  1104. gerber_code += 'G37*\n'
  1105. gerber_code += '%LPD*%\n'
  1106. except Exception as e:
  1107. log.debug("FlatCAMObj.GerberObject.export_gerber() '0' aperture --> %s" % str(e))
  1108. for apid in self.apertures:
  1109. if apid == '0':
  1110. continue
  1111. else:
  1112. gerber_code += 'D%s*\n' % str(apid)
  1113. if 'geometry' in self.apertures[apid]:
  1114. for geo_elem in self.apertures[apid]['geometry']:
  1115. try:
  1116. if 'follow' in geo_elem:
  1117. geo = geo_elem['follow']
  1118. if not geo.is_empty:
  1119. if isinstance(geo, Point):
  1120. if g_zeros == 'T':
  1121. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1122. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1123. yform=y_formatted)
  1124. else:
  1125. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1126. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1127. yform=y_formatted)
  1128. else:
  1129. geo_coords = list(geo.coords)
  1130. # first command is a move with pen-up D02 at the beginning of the geo
  1131. if g_zeros == 'T':
  1132. x_formatted, y_formatted = tz_format(
  1133. geo_coords[0][0], geo_coords[0][1], factor)
  1134. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1135. yform=y_formatted)
  1136. else:
  1137. x_formatted, y_formatted = lz_format(
  1138. geo_coords[0][0], geo_coords[0][1], factor)
  1139. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1140. yform=y_formatted)
  1141. prev_coord = geo_coords[0]
  1142. for coord in geo_coords[1:]:
  1143. if coord != prev_coord:
  1144. if g_zeros == 'T':
  1145. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1146. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1147. yform=y_formatted)
  1148. else:
  1149. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1150. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1151. yform=y_formatted)
  1152. prev_coord = coord
  1153. # gerber_code += "D02*\n"
  1154. except Exception as e:
  1155. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  1156. try:
  1157. if 'clear' in geo_elem:
  1158. gerber_code += '%LPC*%\n'
  1159. geo = geo_elem['clear']
  1160. if not geo.is_empty:
  1161. if isinstance(geo, Point):
  1162. if g_zeros == 'T':
  1163. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1164. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1165. yform=y_formatted)
  1166. else:
  1167. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1168. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1169. yform=y_formatted)
  1170. elif isinstance(geo, Polygon):
  1171. geo_coords = list(geo.exterior.coords)
  1172. # first command is a move with pen-up D02 at the beginning of the geo
  1173. if g_zeros == 'T':
  1174. x_formatted, y_formatted = tz_format(
  1175. geo_coords[0][0], geo_coords[0][1], factor)
  1176. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1177. yform=y_formatted)
  1178. else:
  1179. x_formatted, y_formatted = lz_format(
  1180. geo_coords[0][0], geo_coords[0][1], factor)
  1181. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1182. yform=y_formatted)
  1183. prev_coord = geo_coords[0]
  1184. for coord in geo_coords[1:]:
  1185. if coord != prev_coord:
  1186. if g_zeros == 'T':
  1187. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1188. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1189. yform=y_formatted)
  1190. else:
  1191. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1192. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1193. yform=y_formatted)
  1194. prev_coord = coord
  1195. for geo_int in geo.interiors:
  1196. geo_coords = list(geo_int.coords)
  1197. # first command is a move with pen-up D02 at the beginning of the geo
  1198. if g_zeros == 'T':
  1199. x_formatted, y_formatted = tz_format(
  1200. geo_coords[0][0], geo_coords[0][1], factor)
  1201. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1202. yform=y_formatted)
  1203. else:
  1204. x_formatted, y_formatted = lz_format(
  1205. geo_coords[0][0], geo_coords[0][1], factor)
  1206. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1207. yform=y_formatted)
  1208. prev_coord = geo_coords[0]
  1209. for coord in geo_coords[1:]:
  1210. if coord != prev_coord:
  1211. if g_zeros == 'T':
  1212. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1213. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1214. xform=x_formatted,
  1215. yform=y_formatted)
  1216. else:
  1217. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1218. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1219. xform=x_formatted,
  1220. yform=y_formatted)
  1221. prev_coord = coord
  1222. else:
  1223. geo_coords = list(geo.coords)
  1224. # first command is a move with pen-up D02 at the beginning of the geo
  1225. if g_zeros == 'T':
  1226. x_formatted, y_formatted = tz_format(
  1227. geo_coords[0][0], geo_coords[0][1], factor)
  1228. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1229. yform=y_formatted)
  1230. else:
  1231. x_formatted, y_formatted = lz_format(
  1232. geo_coords[0][0], geo_coords[0][1], factor)
  1233. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1234. yform=y_formatted)
  1235. prev_coord = geo_coords[0]
  1236. for coord in geo_coords[1:]:
  1237. if coord != prev_coord:
  1238. if g_zeros == 'T':
  1239. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1240. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1241. yform=y_formatted)
  1242. else:
  1243. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1244. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1245. yform=y_formatted)
  1246. prev_coord = coord
  1247. # gerber_code += "D02*\n"
  1248. gerber_code += '%LPD*%\n'
  1249. except Exception as e:
  1250. log.debug("FlatCAMObj.GerberObject.export_gerber() 'clear' --> %s" % str(e))
  1251. if not self.apertures:
  1252. log.debug("FlatCAMObj.GerberObject.export_gerber() --> Gerber Object is empty: no apertures.")
  1253. return 'fail'
  1254. return gerber_code
  1255. @staticmethod
  1256. def merge(grb_list, grb_final):
  1257. """
  1258. Merges the geometry of objects in geo_list into
  1259. the geometry of geo_final.
  1260. :param grb_list: List of GerberObject Objects to join.
  1261. :param grb_final: Destination GeometryObject object.
  1262. :return: None
  1263. """
  1264. if grb_final.solid_geometry is None:
  1265. grb_final.solid_geometry = []
  1266. grb_final.follow_geometry = []
  1267. if not grb_final.apertures:
  1268. grb_final.apertures = {}
  1269. if type(grb_final.solid_geometry) is not list:
  1270. grb_final.solid_geometry = [grb_final.solid_geometry]
  1271. grb_final.follow_geometry = [grb_final.follow_geometry]
  1272. for grb in grb_list:
  1273. # Expand lists
  1274. if type(grb) is list:
  1275. GerberObject.merge(grb_list=grb, grb_final=grb_final)
  1276. else: # If not list, just append
  1277. for option in grb.options:
  1278. if option != 'name':
  1279. try:
  1280. grb_final.options[option] = grb.options[option]
  1281. except KeyError:
  1282. log.warning("Failed to copy option.", option)
  1283. try:
  1284. for geos in grb.solid_geometry:
  1285. grb_final.solid_geometry.append(geos)
  1286. grb_final.follow_geometry.append(geos)
  1287. except TypeError:
  1288. grb_final.solid_geometry.append(grb.solid_geometry)
  1289. grb_final.follow_geometry.append(grb.solid_geometry)
  1290. for ap in grb.apertures:
  1291. if ap not in grb_final.apertures:
  1292. grb_final.apertures[ap] = grb.apertures[ap]
  1293. else:
  1294. # create a list of integers out of the grb.apertures keys and find the max of that value
  1295. # then, the aperture duplicate is assigned an id value incremented with 1,
  1296. # and finally made string because the apertures dict keys are strings
  1297. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  1298. grb_final.apertures[max_ap] = {}
  1299. grb_final.apertures[max_ap]['geometry'] = []
  1300. for k, v in grb.apertures[ap].items():
  1301. grb_final.apertures[max_ap][k] = deepcopy(v)
  1302. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  1303. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  1304. def mirror(self, axis, point):
  1305. Gerber.mirror(self, axis=axis, point=point)
  1306. self.replotApertures.emit()
  1307. def offset(self, vect):
  1308. Gerber.offset(self, vect=vect)
  1309. self.replotApertures.emit()
  1310. def rotate(self, angle, point):
  1311. Gerber.rotate(self, angle=angle, point=point)
  1312. self.replotApertures.emit()
  1313. def scale(self, xfactor, yfactor=None, point=None):
  1314. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1315. self.replotApertures.emit()
  1316. def skew(self, angle_x, angle_y, point):
  1317. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1318. self.replotApertures.emit()
  1319. def buffer(self, distance, join=2, factor=None):
  1320. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1321. self.replotApertures.emit()
  1322. def serialize(self):
  1323. return {
  1324. "options": self.options,
  1325. "kind": self.kind
  1326. }