ToolEtchCompensation.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 2/14/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCButton, FCDoubleSpinner, RadioSet, FCComboBox, NumericalEvalEntry, FCEntry
  10. from shapely.ops import unary_union
  11. from copy import deepcopy
  12. import math
  13. import logging
  14. import gettext
  15. import appTranslation as fcTranslate
  16. import builtins
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class ToolEtchCompensation(AppTool):
  22. toolName = _("Etch Compensation Tool")
  23. def __init__(self, app):
  24. self.app = app
  25. self.decimals = self.app.decimals
  26. AppTool.__init__(self, app)
  27. self.tools_frame = QtWidgets.QFrame()
  28. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  29. self.layout.addWidget(self.tools_frame)
  30. self.tools_box = QtWidgets.QVBoxLayout()
  31. self.tools_box.setContentsMargins(0, 0, 0, 0)
  32. self.tools_frame.setLayout(self.tools_box)
  33. # Title
  34. title_label = QtWidgets.QLabel("%s" % self.toolName)
  35. title_label.setStyleSheet("""
  36. QLabel
  37. {
  38. font-size: 16px;
  39. font-weight: bold;
  40. }
  41. """)
  42. self.tools_box.addWidget(title_label)
  43. # Grid Layout
  44. grid0 = QtWidgets.QGridLayout()
  45. grid0.setColumnStretch(0, 0)
  46. grid0.setColumnStretch(1, 1)
  47. self.tools_box.addLayout(grid0)
  48. grid0.addWidget(QtWidgets.QLabel(''), 0, 0, 1, 2)
  49. # Target Gerber Object
  50. self.gerber_combo = FCComboBox()
  51. self.gerber_combo.setModel(self.app.collection)
  52. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  53. self.gerber_combo.is_last = True
  54. self.gerber_combo.obj_type = "Gerber"
  55. self.gerber_label = QtWidgets.QLabel('<b>%s:</b>' % _("GERBER"))
  56. self.gerber_label.setToolTip(
  57. _("Gerber object that will be inverted.")
  58. )
  59. grid0.addWidget(self.gerber_label, 1, 0, 1, 2)
  60. grid0.addWidget(self.gerber_combo, 2, 0, 1, 2)
  61. separator_line = QtWidgets.QFrame()
  62. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  63. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  64. grid0.addWidget(separator_line, 3, 0, 1, 2)
  65. self.util_label = QtWidgets.QLabel("<b>%s:</b>" % _("Utilities"))
  66. self.util_label.setToolTip('%s.' % _("Conversion utilities"))
  67. grid0.addWidget(self.util_label, 4, 0, 1, 2)
  68. # Oz to um conversion
  69. self.oz_um_label = QtWidgets.QLabel('%s:' % _('Oz to Microns'))
  70. self.oz_um_label.setToolTip(
  71. _("Will convert from oz thickness to microns [um].\n"
  72. "Can use formulas with operators: /, *, +, -, %, .\n"
  73. "The real numbers use the dot decimals separator.")
  74. )
  75. grid0.addWidget(self.oz_um_label, 5, 0, 1, 2)
  76. hlay_1 = QtWidgets.QHBoxLayout()
  77. self.oz_entry = NumericalEvalEntry(border_color='#0069A9')
  78. self.oz_entry.setPlaceholderText(_("Oz value"))
  79. self.oz_to_um_entry = FCEntry()
  80. self.oz_to_um_entry.setPlaceholderText(_("Microns value"))
  81. self.oz_to_um_entry.setReadOnly(True)
  82. hlay_1.addWidget(self.oz_entry)
  83. hlay_1.addWidget(self.oz_to_um_entry)
  84. grid0.addLayout(hlay_1, 6, 0, 1, 2)
  85. # Mils to um conversion
  86. self.mils_um_label = QtWidgets.QLabel('%s:' % _('Mils to Microns'))
  87. self.mils_um_label.setToolTip(
  88. _("Will convert from mils to microns [um].\n"
  89. "Can use formulas with operators: /, *, +, -, %, .\n"
  90. "The real numbers use the dot decimals separator.")
  91. )
  92. grid0.addWidget(self.mils_um_label, 7, 0, 1, 2)
  93. hlay_2 = QtWidgets.QHBoxLayout()
  94. self.mils_entry = NumericalEvalEntry(border_color='#0069A9')
  95. self.mils_entry.setPlaceholderText(_("Mils value"))
  96. self.mils_to_um_entry = FCEntry()
  97. self.mils_to_um_entry.setPlaceholderText(_("Microns value"))
  98. self.mils_to_um_entry.setReadOnly(True)
  99. hlay_2.addWidget(self.mils_entry)
  100. hlay_2.addWidget(self.mils_to_um_entry)
  101. grid0.addLayout(hlay_2, 8, 0, 1, 2)
  102. separator_line = QtWidgets.QFrame()
  103. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  104. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  105. grid0.addWidget(separator_line, 9, 0, 1, 2)
  106. self.param_label = QtWidgets.QLabel("<b>%s:</b>" % _("Parameters"))
  107. self.param_label.setToolTip('%s.' % _("Parameters for this tool"))
  108. grid0.addWidget(self.param_label, 10, 0, 1, 2)
  109. # Thickness
  110. self.thick_label = QtWidgets.QLabel('%s:' % _('Copper Thickness'))
  111. self.thick_label.setToolTip(
  112. _("The thickness of the copper foil.\n"
  113. "In microns [um].")
  114. )
  115. self.thick_entry = FCDoubleSpinner(callback=self.confirmation_message)
  116. self.thick_entry.set_precision(self.decimals)
  117. self.thick_entry.set_range(0.0000, 9999.9999)
  118. self.thick_entry.setObjectName(_("Thickness"))
  119. grid0.addWidget(self.thick_label, 12, 0)
  120. grid0.addWidget(self.thick_entry, 12, 1)
  121. self.ratio_label = QtWidgets.QLabel('%s:' % _("Ratio"))
  122. self.ratio_label.setToolTip(
  123. _("The ratio of lateral etch versus depth etch.\n"
  124. "Can be:\n"
  125. "- custom -> the user will enter a custom value\n"
  126. "- preselection -> value which depends on a selection of etchants")
  127. )
  128. self.ratio_radio = RadioSet([
  129. {'label': _('Etch Factor'), 'value': 'factor'},
  130. {'label': _('Etchants list'), 'value': 'etch_list'},
  131. {'label': _('Manual offset'), 'value': 'manual'}
  132. ], orientation='vertical', stretch=False)
  133. grid0.addWidget(self.ratio_label, 14, 0, 1, 2)
  134. grid0.addWidget(self.ratio_radio, 16, 0, 1, 2)
  135. # Etchants
  136. self.etchants_label = QtWidgets.QLabel('%s:' % _('Etchants'))
  137. self.etchants_label.setToolTip(
  138. _("A list of etchants.")
  139. )
  140. self.etchants_combo = FCComboBox(callback=self.confirmation_message)
  141. self.etchants_combo.setObjectName(_("Etchants"))
  142. self.etchants_combo.addItems(["CuCl2", "Fe3Cl", _("Alkaline baths")])
  143. grid0.addWidget(self.etchants_label, 18, 0)
  144. grid0.addWidget(self.etchants_combo, 18, 1)
  145. # Etch Factor
  146. self.factor_label = QtWidgets.QLabel('%s:' % _('Etch factor'))
  147. self.factor_label.setToolTip(
  148. _("The ratio between depth etch and lateral etch .\n"
  149. "Accepts real numbers and formulas using the operators: /,*,+,-,%")
  150. )
  151. self.factor_entry = NumericalEvalEntry(border_color='#0069A9')
  152. self.factor_entry.setPlaceholderText(_("Real number or formula"))
  153. self.factor_entry.setObjectName(_("Etch_factor"))
  154. grid0.addWidget(self.factor_label, 19, 0)
  155. grid0.addWidget(self.factor_entry, 19, 1)
  156. # Manual Offset
  157. self.offset_label = QtWidgets.QLabel('%s:' % _('Offset'))
  158. self.offset_label.setToolTip(
  159. _("Value with which to increase or decrease (buffer)\n"
  160. "the copper features. In microns [um].")
  161. )
  162. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  163. self.offset_entry.set_precision(self.decimals)
  164. self.offset_entry.set_range(-9999.9999, 9999.9999)
  165. self.offset_entry.setObjectName(_("Offset"))
  166. grid0.addWidget(self.offset_label, 20, 0)
  167. grid0.addWidget(self.offset_entry, 20, 1)
  168. # Hide the Etchants and Etch factor
  169. self.etchants_label.hide()
  170. self.etchants_combo.hide()
  171. self.factor_label.hide()
  172. self.factor_entry.hide()
  173. self.offset_label.hide()
  174. self.offset_entry.hide()
  175. separator_line = QtWidgets.QFrame()
  176. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  177. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  178. grid0.addWidget(separator_line, 22, 0, 1, 2)
  179. self.compensate_btn = FCButton(_('Compensate'))
  180. self.compensate_btn.setToolTip(
  181. _("Will increase the copper features thickness to compensate the lateral etch.")
  182. )
  183. self.compensate_btn.setStyleSheet("""
  184. QPushButton
  185. {
  186. font-weight: bold;
  187. }
  188. """)
  189. grid0.addWidget(self.compensate_btn, 24, 0, 1, 2)
  190. self.tools_box.addStretch()
  191. # ## Reset Tool
  192. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  193. self.reset_button.setToolTip(
  194. _("Will reset the tool parameters.")
  195. )
  196. self.reset_button.setStyleSheet("""
  197. QPushButton
  198. {
  199. font-weight: bold;
  200. }
  201. """)
  202. self.tools_box.addWidget(self.reset_button)
  203. self.compensate_btn.clicked.connect(self.on_compensate)
  204. self.reset_button.clicked.connect(self.set_tool_ui)
  205. self.ratio_radio.activated_custom.connect(self.on_ratio_change)
  206. self.oz_entry.textChanged.connect(self.on_oz_conversion)
  207. self.mils_entry.textChanged.connect(self.on_mils_conversion)
  208. def install(self, icon=None, separator=None, **kwargs):
  209. AppTool.install(self, icon, separator, shortcut='', **kwargs)
  210. def run(self, toggle=True):
  211. self.app.defaults.report_usage("ToolEtchCompensation()")
  212. log.debug("ToolEtchCompensation() is running ...")
  213. if toggle:
  214. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  215. if self.app.ui.splitter.sizes()[0] == 0:
  216. self.app.ui.splitter.setSizes([1, 1])
  217. else:
  218. try:
  219. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  220. # if tab is populated with the tool but it does not have the focus, focus on it
  221. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  222. # focus on Tool Tab
  223. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  224. else:
  225. self.app.ui.splitter.setSizes([0, 1])
  226. except AttributeError:
  227. pass
  228. else:
  229. if self.app.ui.splitter.sizes()[0] == 0:
  230. self.app.ui.splitter.setSizes([1, 1])
  231. AppTool.run(self)
  232. self.set_tool_ui()
  233. self.app.ui.notebook.setTabText(2, _("Etch Compensation Tool"))
  234. def set_tool_ui(self):
  235. self.thick_entry.set_value(18.0)
  236. self.ratio_radio.set_value('factor')
  237. def on_ratio_change(self, val):
  238. """
  239. Called on activated_custom signal of the RadioSet GUI element self.radio_ratio
  240. :param val: 'c' or 'p': 'c' means custom factor and 'p' means preselected etchants
  241. :type val: str
  242. :return: None
  243. :rtype:
  244. """
  245. if val == 'factor':
  246. self.etchants_label.hide()
  247. self.etchants_combo.hide()
  248. self.factor_label.show()
  249. self.factor_entry.show()
  250. self.offset_label.hide()
  251. self.offset_entry.hide()
  252. elif val == 'etch_list':
  253. self.etchants_label.show()
  254. self.etchants_combo.show()
  255. self.factor_label.hide()
  256. self.factor_entry.hide()
  257. self.offset_label.hide()
  258. self.offset_entry.hide()
  259. else:
  260. self.etchants_label.hide()
  261. self.etchants_combo.hide()
  262. self.factor_label.hide()
  263. self.factor_entry.hide()
  264. self.offset_label.show()
  265. self.offset_entry.show()
  266. def on_oz_conversion(self, txt):
  267. try:
  268. val = eval(txt)
  269. # oz thickness to mils by multiplying with 1.37
  270. # mils to microns by multiplying with 25.4
  271. val *= 34.798
  272. except Exception:
  273. self.oz_to_um_entry.set_value('')
  274. return
  275. self.oz_to_um_entry.set_value(val, self.decimals)
  276. def on_mils_conversion(self, txt):
  277. try:
  278. val = eval(txt)
  279. val *= 25.4
  280. except Exception:
  281. self.mils_to_um_entry.set_value('')
  282. return
  283. self.mils_to_um_entry.set_value(val, self.decimals)
  284. def on_compensate(self):
  285. log.debug("ToolEtchCompensation.on_compensate()")
  286. ratio_type = self.ratio_radio.get_value()
  287. thickness = self.thick_entry.get_value() / 1000 # in microns
  288. grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  289. obj_name = self.gerber_combo.currentText()
  290. outname = obj_name + "_comp"
  291. # Get source object.
  292. try:
  293. grb_obj = self.app.collection.get_by_name(obj_name)
  294. except Exception as e:
  295. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  296. return "Could not retrieve object: %s with error: %s" % (obj_name, str(e))
  297. if grb_obj is None:
  298. if obj_name == '':
  299. obj_name = 'None'
  300. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  301. return
  302. if ratio_type == 'factor':
  303. etch_factor = 1 / self.factor_entry.get_value()
  304. offset = thickness / etch_factor
  305. elif ratio_type == 'etch_list':
  306. etchant = self.etchants_combo.get_value()
  307. if etchant == "CuCl2":
  308. etch_factor = 0.33
  309. else:
  310. etch_factor = 0.25
  311. offset = thickness / etch_factor
  312. else:
  313. offset = self.offset_entry.get_value() / 1000 # in microns
  314. try:
  315. __ = iter(grb_obj.solid_geometry)
  316. except TypeError:
  317. grb_obj.solid_geometry = list(grb_obj.solid_geometry)
  318. new_solid_geometry = []
  319. for poly in grb_obj.solid_geometry:
  320. new_solid_geometry.append(poly.buffer(offset, int(grb_circle_steps)))
  321. new_solid_geometry = unary_union(new_solid_geometry)
  322. new_options = {}
  323. for opt in grb_obj.options:
  324. new_options[opt] = deepcopy(grb_obj.options[opt])
  325. new_apertures = deepcopy(grb_obj.apertures)
  326. # update the apertures attributes (keys in the apertures dict)
  327. for ap in new_apertures:
  328. type = new_apertures[ap]['type']
  329. for k in new_apertures[ap]:
  330. if type == 'R' or type == 'O':
  331. if k == 'width' or k == 'height':
  332. new_apertures[ap][k] += offset
  333. else:
  334. if k == 'size' or k == 'width' or k == 'height':
  335. new_apertures[ap][k] += offset
  336. if k == 'geometry':
  337. for geo_el in new_apertures[ap][k]:
  338. if 'solid' in geo_el:
  339. geo_el['solid'] = geo_el['solid'].buffer(offset, int(grb_circle_steps))
  340. # in case of 'R' or 'O' aperture type we need to update the aperture 'size' after
  341. # the 'width' and 'height' keys were updated
  342. for ap in new_apertures:
  343. type = new_apertures[ap]['type']
  344. for k in new_apertures[ap]:
  345. if type == 'R' or type == 'O':
  346. if k == 'size':
  347. new_apertures[ap][k] = math.sqrt(
  348. new_apertures[ap]['width'] ** 2 + new_apertures[ap]['height'] ** 2)
  349. def init_func(new_obj, app_obj):
  350. """
  351. Init a new object in FlatCAM Object collection
  352. :param new_obj: New object
  353. :type new_obj: ObjectCollection
  354. :param app_obj: App
  355. :type app_obj: app_Main.App
  356. :return: None
  357. :rtype:
  358. """
  359. new_obj.options.update(new_options)
  360. new_obj.options['name'] = outname
  361. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  362. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  363. new_obj.apertures = deepcopy(new_apertures)
  364. new_obj.solid_geometry = deepcopy(new_solid_geometry)
  365. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  366. local_use=new_obj, use_thread=False)
  367. self.app.app_obj.new_object('gerber', outname, init_func)
  368. def reset_fields(self):
  369. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  370. @staticmethod
  371. def poly2rings(poly):
  372. return [poly.exterior] + [interior for interior in poly.interiors]
  373. # end of file