ToolNonCopperClear.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified by: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/2019 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from FlatCAMTool import FlatCAMTool
  9. from copy import copy, deepcopy
  10. from ObjectCollection import *
  11. import time
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. from shapely.geometry import base
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. class NonCopperClear(FlatCAMTool, Gerber):
  20. toolName = _("Non-Copper Clearing")
  21. def __init__(self, app):
  22. self.app = app
  23. FlatCAMTool.__init__(self, app)
  24. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  25. self.tools_frame = QtWidgets.QFrame()
  26. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  27. self.layout.addWidget(self.tools_frame)
  28. self.tools_box = QtWidgets.QVBoxLayout()
  29. self.tools_box.setContentsMargins(0, 0, 0, 0)
  30. self.tools_frame.setLayout(self.tools_box)
  31. # ## Title
  32. title_label = QtWidgets.QLabel("%s" % self.toolName)
  33. title_label.setStyleSheet("""
  34. QLabel
  35. {
  36. font-size: 16px;
  37. font-weight: bold;
  38. }
  39. """)
  40. self.tools_box.addWidget(title_label)
  41. # ## Form Layout
  42. form_layout = QtWidgets.QFormLayout()
  43. self.tools_box.addLayout(form_layout)
  44. # ## Object
  45. self.object_combo = QtWidgets.QComboBox()
  46. self.object_combo.setModel(self.app.collection)
  47. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  48. self.object_combo.setCurrentIndex(1)
  49. self.object_label = QtWidgets.QLabel("Gerber:")
  50. self.object_label.setToolTip(
  51. _("Gerber object to be cleared of excess copper. ")
  52. )
  53. e_lab_0 = QtWidgets.QLabel('')
  54. form_layout.addRow(self.object_label, self.object_combo)
  55. form_layout.addRow(e_lab_0)
  56. #### Tools ## ##
  57. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  58. self.tools_table_label.setToolTip(
  59. _("Tools pool from which the algorithm\n"
  60. "will pick the ones used for copper clearing.")
  61. )
  62. self.tools_box.addWidget(self.tools_table_label)
  63. self.tools_table = FCTable()
  64. self.tools_box.addWidget(self.tools_table)
  65. self.tools_table.setColumnCount(4)
  66. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), 'TT', ''])
  67. self.tools_table.setColumnHidden(3, True)
  68. self.tools_table.setSortingEnabled(False)
  69. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  70. self.tools_table.horizontalHeaderItem(0).setToolTip(
  71. _("This is the Tool Number.\n"
  72. "Non copper clearing will start with the tool with the biggest \n"
  73. "diameter, continuing until there are no more tools.\n"
  74. "Only tools that create NCC clearing geometry will still be present\n"
  75. "in the resulting geometry. This is because with some tools\n"
  76. "this function will not be able to create painting geometry.")
  77. )
  78. self.tools_table.horizontalHeaderItem(1).setToolTip(
  79. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  80. "is the cut width into the material."))
  81. self.tools_table.horizontalHeaderItem(2).setToolTip(
  82. _("The Tool Type (TT) can be:<BR>"
  83. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  84. "the cut width in material is exactly the tool diameter.<BR>"
  85. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  86. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  87. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  88. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  89. "as the cut width into material will be equal with the value in the Tool Diameter "
  90. "column of this table.<BR>"
  91. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  92. "in the resulting geometry as Isolation."))
  93. self.empty_label = QtWidgets.QLabel('')
  94. self.tools_box.addWidget(self.empty_label)
  95. # ### Add a new Tool ####
  96. hlay = QtWidgets.QHBoxLayout()
  97. self.tools_box.addLayout(hlay)
  98. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  99. self.addtool_entry_lbl.setToolTip(
  100. _("Diameter for the new tool to add in the Tool Table")
  101. )
  102. self.addtool_entry = FCEntry2()
  103. # hlay.addWidget(self.addtool_label)
  104. # hlay.addStretch()
  105. hlay.addWidget(self.addtool_entry_lbl)
  106. hlay.addWidget(self.addtool_entry)
  107. grid2 = QtWidgets.QGridLayout()
  108. self.tools_box.addLayout(grid2)
  109. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  110. self.addtool_btn.setToolTip(
  111. _("Add a new tool to the Tool Table\n"
  112. "with the diameter specified above.")
  113. )
  114. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  115. # self.copytool_btn.setToolTip(
  116. # "Copy a selection of tools in the Tool Table\n"
  117. # "by first selecting a row in the Tool Table."
  118. # )
  119. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  120. self.deltool_btn.setToolTip(
  121. _("Delete a selection of tools in the Tool Table\n"
  122. "by first selecting a row(s) in the Tool Table.")
  123. )
  124. grid2.addWidget(self.addtool_btn, 0, 0)
  125. # grid2.addWidget(self.copytool_btn, 0, 1)
  126. grid2.addWidget(self.deltool_btn, 0, 2)
  127. self.empty_label_0 = QtWidgets.QLabel('')
  128. self.tools_box.addWidget(self.empty_label_0)
  129. grid3 = QtWidgets.QGridLayout()
  130. self.tools_box.addLayout(grid3)
  131. e_lab_1 = QtWidgets.QLabel('')
  132. grid3.addWidget(e_lab_1, 0, 0)
  133. nccoverlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  134. nccoverlabel.setToolTip(
  135. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  136. "Example:\n"
  137. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  138. "Adjust the value starting with lower values\n"
  139. "and increasing it if areas that should be cleared are still \n"
  140. "not cleared.\n"
  141. "Lower values = faster processing, faster execution on PCB.\n"
  142. "Higher values = slow processing and slow execution on CNC\n"
  143. "due of too many paths.")
  144. )
  145. grid3.addWidget(nccoverlabel, 1, 0)
  146. self.ncc_overlap_entry = FCEntry()
  147. grid3.addWidget(self.ncc_overlap_entry, 1, 1)
  148. nccmarginlabel = QtWidgets.QLabel(_('Margin:'))
  149. nccmarginlabel.setToolTip(
  150. _("Bounding box margin.")
  151. )
  152. grid3.addWidget(nccmarginlabel, 2, 0)
  153. self.ncc_margin_entry = FCEntry()
  154. grid3.addWidget(self.ncc_margin_entry, 2, 1)
  155. # Method
  156. methodlabel = QtWidgets.QLabel(_('Method:'))
  157. methodlabel.setToolTip(
  158. _("Algorithm for non-copper clearing:<BR>"
  159. "<B>Standard</B>: Fixed step inwards.<BR>"
  160. "<B>Seed-based</B>: Outwards from seed.<BR>"
  161. "<B>Line-based</B>: Parallel lines.")
  162. )
  163. grid3.addWidget(methodlabel, 3, 0)
  164. self.ncc_method_radio = RadioSet([
  165. {"label": _("Standard"), "value": "standard"},
  166. {"label": _("Seed-based"), "value": "seed"},
  167. {"label": _("Straight lines"), "value": "lines"}
  168. ], orientation='vertical', stretch=False)
  169. grid3.addWidget(self.ncc_method_radio, 3, 1)
  170. # Connect lines
  171. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  172. pathconnectlabel.setToolTip(
  173. _("Draw lines between resulting\n"
  174. "segments to minimize tool lifts.")
  175. )
  176. grid3.addWidget(pathconnectlabel, 4, 0)
  177. self.ncc_connect_cb = FCCheckBox()
  178. grid3.addWidget(self.ncc_connect_cb, 4, 1)
  179. contourlabel = QtWidgets.QLabel(_("Contour:"))
  180. contourlabel.setToolTip(
  181. _("Cut around the perimeter of the polygon\n"
  182. "to trim rough edges.")
  183. )
  184. grid3.addWidget(contourlabel, 5, 0)
  185. self.ncc_contour_cb = FCCheckBox()
  186. grid3.addWidget(self.ncc_contour_cb, 5, 1)
  187. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  188. restlabel.setToolTip(
  189. _("If checked, use 'rest machining'.\n"
  190. "Basically it will clear copper outside PCB features,\n"
  191. "using the biggest tool and continue with the next tools,\n"
  192. "from bigger to smaller, to clear areas of copper that\n"
  193. "could not be cleared by previous tool, until there is\n"
  194. "no more copper to clear or there are no more tools.\n"
  195. "If not checked, use the standard algorithm.")
  196. )
  197. grid3.addWidget(restlabel, 6, 0)
  198. self.ncc_rest_cb = FCCheckBox()
  199. grid3.addWidget(self.ncc_rest_cb, 6, 1)
  200. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  201. self.generate_ncc_button.setToolTip(
  202. _("Create the Geometry Object\n"
  203. "for non-copper routing.")
  204. )
  205. self.tools_box.addWidget(self.generate_ncc_button)
  206. self.units = ''
  207. self.ncc_tools = {}
  208. self.tooluid = 0
  209. # store here the default data for Geometry Data
  210. self.default_data = {}
  211. self.obj_name = ""
  212. self.ncc_obj = None
  213. self.tools_box.addStretch()
  214. self.addtool_btn.clicked.connect(self.on_tool_add)
  215. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  216. self.deltool_btn.clicked.connect(self.on_tool_delete)
  217. self.generate_ncc_button.clicked.connect(self.on_ncc)
  218. def install(self, icon=None, separator=None, **kwargs):
  219. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  220. def run(self, toggle=True):
  221. self.app.report_usage("ToolNonCopperClear()")
  222. if toggle:
  223. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  224. if self.app.ui.splitter.sizes()[0] == 0:
  225. self.app.ui.splitter.setSizes([1, 1])
  226. else:
  227. try:
  228. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  229. self.app.ui.splitter.setSizes([0, 1])
  230. except AttributeError:
  231. pass
  232. else:
  233. if self.app.ui.splitter.sizes()[0] == 0:
  234. self.app.ui.splitter.setSizes([1, 1])
  235. FlatCAMTool.run(self)
  236. self.set_tool_ui()
  237. self.build_ui()
  238. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  239. def set_tool_ui(self):
  240. self.tools_frame.show()
  241. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  242. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  243. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  244. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  245. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  246. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  247. self.tools_table.setupContextMenu()
  248. self.tools_table.addContextMenu(
  249. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  250. self.tools_table.addContextMenu(
  251. "Delete", lambda:
  252. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  253. # init the working variables
  254. self.default_data.clear()
  255. self.default_data.update({
  256. "name": '_ncc',
  257. "plot": self.app.defaults["geometry_plot"],
  258. "cutz": self.app.defaults["geometry_cutz"],
  259. "vtipdia": 0.1,
  260. "vtipangle": 30,
  261. "travelz": self.app.defaults["geometry_travelz"],
  262. "feedrate": self.app.defaults["geometry_feedrate"],
  263. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  264. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  265. "dwell": self.app.defaults["geometry_dwell"],
  266. "dwelltime": self.app.defaults["geometry_dwelltime"],
  267. "multidepth": self.app.defaults["geometry_multidepth"],
  268. "ppname_g": self.app.defaults["geometry_ppname_g"],
  269. "depthperpass": self.app.defaults["geometry_depthperpass"],
  270. "extracut": self.app.defaults["geometry_extracut"],
  271. "toolchange": self.app.defaults["geometry_toolchange"],
  272. "toolchangez": self.app.defaults["geometry_toolchangez"],
  273. "endz": self.app.defaults["geometry_endz"],
  274. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  275. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  276. "startz": self.app.defaults["geometry_startz"],
  277. "tooldia": self.app.defaults["tools_painttooldia"],
  278. "paintmargin": self.app.defaults["tools_paintmargin"],
  279. "paintmethod": self.app.defaults["tools_paintmethod"],
  280. "selectmethod": self.app.defaults["tools_selectmethod"],
  281. "pathconnect": self.app.defaults["tools_pathconnect"],
  282. "paintcontour": self.app.defaults["tools_paintcontour"],
  283. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  284. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  285. "nccmargin": self.app.defaults["tools_nccmargin"],
  286. "nccmethod": self.app.defaults["tools_nccmethod"],
  287. "nccconnect": self.app.defaults["tools_nccconnect"],
  288. "ncccontour": self.app.defaults["tools_ncccontour"],
  289. "nccrest": self.app.defaults["tools_nccrest"]
  290. })
  291. try:
  292. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  293. except Exception as e:
  294. log.error("At least one tool diameter needed. "
  295. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  296. return
  297. self.tooluid = 0
  298. self.ncc_tools.clear()
  299. for tool_dia in dias:
  300. self.tooluid += 1
  301. self.ncc_tools.update({
  302. int(self.tooluid): {
  303. 'tooldia': float('%.4f' % tool_dia),
  304. 'offset': 'Path',
  305. 'offset_value': 0.0,
  306. 'type': 'Iso',
  307. 'tool_type': 'V',
  308. 'data': dict(self.default_data),
  309. 'solid_geometry': []
  310. }
  311. })
  312. self.obj_name = ""
  313. self.ncc_obj = None
  314. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  315. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  316. def build_ui(self):
  317. self.ui_disconnect()
  318. # updated units
  319. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  320. if self.units == "IN":
  321. self.addtool_entry.set_value(0.039)
  322. else:
  323. self.addtool_entry.set_value(1)
  324. sorted_tools = []
  325. for k, v in self.ncc_tools.items():
  326. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  327. sorted_tools.sort()
  328. n = len(sorted_tools)
  329. self.tools_table.setRowCount(n)
  330. tool_id = 0
  331. for tool_sorted in sorted_tools:
  332. for tooluid_key, tooluid_value in self.ncc_tools.items():
  333. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  334. tool_id += 1
  335. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  336. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  337. row_no = tool_id - 1
  338. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  339. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  340. # There are no drill bits in MM with more than 3 decimals diameter
  341. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  342. if self.units == 'MM':
  343. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  344. else:
  345. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  346. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  347. tool_type_item = QtWidgets.QComboBox()
  348. for item in self.tool_type_item_options:
  349. tool_type_item.addItem(item)
  350. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  351. idx = tool_type_item.findText(tooluid_value['tool_type'])
  352. tool_type_item.setCurrentIndex(idx)
  353. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  354. self.tools_table.setItem(row_no, 1, dia) # Diameter
  355. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  356. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  357. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  358. # make the diameter column editable
  359. for row in range(tool_id):
  360. self.tools_table.item(row, 1).setFlags(
  361. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  362. # all the tools are selected by default
  363. self.tools_table.selectColumn(0)
  364. #
  365. self.tools_table.resizeColumnsToContents()
  366. self.tools_table.resizeRowsToContents()
  367. vertical_header = self.tools_table.verticalHeader()
  368. vertical_header.hide()
  369. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  370. horizontal_header = self.tools_table.horizontalHeader()
  371. horizontal_header.setMinimumSectionSize(10)
  372. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  373. horizontal_header.resizeSection(0, 20)
  374. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  375. # self.tools_table.setSortingEnabled(True)
  376. # sort by tool diameter
  377. # self.tools_table.sortItems(1)
  378. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  379. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  380. self.ui_connect()
  381. def ui_connect(self):
  382. self.tools_table.itemChanged.connect(self.on_tool_edit)
  383. def ui_disconnect(self):
  384. try:
  385. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  386. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  387. except:
  388. pass
  389. def on_tool_add(self, dia=None, muted=None):
  390. self.ui_disconnect()
  391. if dia:
  392. tool_dia = dia
  393. else:
  394. try:
  395. tool_dia = float(self.addtool_entry.get_value())
  396. except ValueError:
  397. # try to convert comma to decimal point. if it's still not working error message and return
  398. try:
  399. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  400. except ValueError:
  401. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  402. "use a number."))
  403. return
  404. if tool_dia is None:
  405. self.build_ui()
  406. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  407. return
  408. if tool_dia == 0:
  409. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, "
  410. "in Float format."))
  411. return
  412. # construct a list of all 'tooluid' in the self.tools
  413. tool_uid_list = []
  414. for tooluid_key in self.ncc_tools:
  415. tool_uid_item = int(tooluid_key)
  416. tool_uid_list.append(tool_uid_item)
  417. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  418. if not tool_uid_list:
  419. max_uid = 0
  420. else:
  421. max_uid = max(tool_uid_list)
  422. self.tooluid = int(max_uid + 1)
  423. tool_dias = []
  424. for k, v in self.ncc_tools.items():
  425. for tool_v in v.keys():
  426. if tool_v == 'tooldia':
  427. tool_dias.append(float('%.4f' % v[tool_v]))
  428. if float('%.4f' % tool_dia) in tool_dias:
  429. if muted is None:
  430. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  431. self.tools_table.itemChanged.connect(self.on_tool_edit)
  432. return
  433. else:
  434. if muted is None:
  435. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  436. self.ncc_tools.update({
  437. int(self.tooluid): {
  438. 'tooldia': float('%.4f' % tool_dia),
  439. 'offset': 'Path',
  440. 'offset_value': 0.0,
  441. 'type': 'Iso',
  442. 'tool_type': 'V',
  443. 'data': dict(self.default_data),
  444. 'solid_geometry': []
  445. }
  446. })
  447. self.build_ui()
  448. def on_tool_edit(self):
  449. self.ui_disconnect()
  450. tool_dias = []
  451. for k, v in self.ncc_tools.items():
  452. for tool_v in v.keys():
  453. if tool_v == 'tooldia':
  454. tool_dias.append(float('%.4f' % v[tool_v]))
  455. for row in range(self.tools_table.rowCount()):
  456. try:
  457. new_tool_dia = float(self.tools_table.item(row, 1).text())
  458. except ValueError:
  459. # try to convert comma to decimal point. if it's still not working error message and return
  460. try:
  461. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  462. except ValueError:
  463. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  464. "use a number."))
  465. return
  466. tooluid = int(self.tools_table.item(row, 3).text())
  467. # identify the tool that was edited and get it's tooluid
  468. if new_tool_dia not in tool_dias:
  469. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  470. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  471. self.build_ui()
  472. return
  473. else:
  474. # identify the old tool_dia and restore the text in tool table
  475. for k, v in self.ncc_tools.items():
  476. if k == tooluid:
  477. old_tool_dia = v['tooldia']
  478. break
  479. restore_dia_item = self.tools_table.item(row, 1)
  480. restore_dia_item.setText(str(old_tool_dia))
  481. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  482. "New diameter value is already in the Tool Table."))
  483. self.build_ui()
  484. def on_tool_delete(self, rows_to_delete=None, all=None):
  485. self.ui_disconnect()
  486. deleted_tools_list = []
  487. if all:
  488. self.paint_tools.clear()
  489. self.build_ui()
  490. return
  491. if rows_to_delete:
  492. try:
  493. for row in rows_to_delete:
  494. tooluid_del = int(self.tools_table.item(row, 3).text())
  495. deleted_tools_list.append(tooluid_del)
  496. except TypeError:
  497. deleted_tools_list.append(rows_to_delete)
  498. for t in deleted_tools_list:
  499. self.ncc_tools.pop(t, None)
  500. self.build_ui()
  501. return
  502. try:
  503. if self.tools_table.selectedItems():
  504. for row_sel in self.tools_table.selectedItems():
  505. row = row_sel.row()
  506. if row < 0:
  507. continue
  508. tooluid_del = int(self.tools_table.item(row, 3).text())
  509. deleted_tools_list.append(tooluid_del)
  510. for t in deleted_tools_list:
  511. self.ncc_tools.pop(t, None)
  512. except AttributeError:
  513. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  514. return
  515. except Exception as e:
  516. log.debug(str(e))
  517. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  518. self.build_ui()
  519. def on_ncc(self):
  520. try:
  521. over = float(self.ncc_overlap_entry.get_value())
  522. except ValueError:
  523. # try to convert comma to decimal point. if it's still not working error message and return
  524. try:
  525. over = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  526. except ValueError:
  527. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  528. "use a number."))
  529. return
  530. over = over if over else self.app.defaults["tools_nccoverlap"]
  531. if over >= 1 or over < 0:
  532. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  533. "0 (inclusive) and 1 (exclusive), "))
  534. return
  535. try:
  536. margin = float(self.ncc_margin_entry.get_value())
  537. except ValueError:
  538. # try to convert comma to decimal point. if it's still not working error message and return
  539. try:
  540. margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  541. except ValueError:
  542. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  543. "use a number."))
  544. return
  545. margin = margin if margin else self.app.defaults["tools_nccmargin"]
  546. connect = self.ncc_connect_cb.get_value()
  547. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  548. contour = self.ncc_contour_cb.get_value()
  549. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  550. clearing_method = self.ncc_rest_cb.get_value()
  551. clearing_method = clearing_method if clearing_method else self.app.defaults["tools_nccrest"]
  552. pol_method = self.ncc_method_radio.get_value()
  553. pol_method = pol_method if pol_method else self.app.defaults["tools_nccmethod"]
  554. self.obj_name = self.object_combo.currentText()
  555. # Get source object.
  556. try:
  557. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  558. except Exception as e:
  559. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  560. return "Could not retrieve object: %s" % self.obj_name
  561. # Prepare non-copper polygons
  562. try:
  563. bounding_box = self.ncc_obj.solid_geometry.envelope.buffer(distance=margin,
  564. join_style=base.JOIN_STYLE.mitre)
  565. except AttributeError:
  566. self.app.inform.emit(_("[ERROR_NOTCL] No Gerber file available."))
  567. return
  568. # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  569. empty = self.ncc_obj.get_empty_area(bounding_box)
  570. if type(empty) is Polygon:
  571. empty = MultiPolygon([empty])
  572. # clear non copper using standard algorithm
  573. if clearing_method is False:
  574. self.clear_non_copper(
  575. empty=empty,
  576. over=over,
  577. pol_method=pol_method,
  578. connect=connect,
  579. contour=contour
  580. )
  581. # clear non copper using rest machining algorithm
  582. else:
  583. self.clear_non_copper_rest(
  584. empty=empty,
  585. over=over,
  586. pol_method=pol_method,
  587. connect=connect,
  588. contour=contour
  589. )
  590. def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  591. name = outname if outname else self.obj_name + "_ncc"
  592. # Sort tools in descending order
  593. sorted_tools = []
  594. for k, v in self.ncc_tools.items():
  595. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  596. sorted_tools.sort(reverse=True)
  597. # Do job in background
  598. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  599. def initialize(geo_obj, app_obj):
  600. assert isinstance(geo_obj, FlatCAMGeometry), \
  601. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  602. cleared_geo = []
  603. # Already cleared area
  604. cleared = MultiPolygon()
  605. # flag for polygons not cleared
  606. app_obj.poly_not_cleared = False
  607. # Generate area for each tool
  608. offset = sum(sorted_tools)
  609. current_uid = int(1)
  610. for tool in sorted_tools:
  611. self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  612. cleared_geo[:] = []
  613. # Get remaining tools offset
  614. offset -= (tool - 1e-12)
  615. # Area to clear
  616. area = empty.buffer(-offset)
  617. try:
  618. area = area.difference(cleared)
  619. except Exception as e:
  620. continue
  621. # Transform area to MultiPolygon
  622. if type(area) is Polygon:
  623. area = MultiPolygon([area])
  624. if area.geoms:
  625. if len(area.geoms) > 0:
  626. for p in area.geoms:
  627. try:
  628. if pol_method == 'standard':
  629. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  630. overlap=over, contour=contour, connect=connect)
  631. elif pol_method == 'seed':
  632. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  633. overlap=over, contour=contour, connect=connect)
  634. else:
  635. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  636. overlap=over, contour=contour, connect=connect)
  637. if cp:
  638. cleared_geo += list(cp.get_objects())
  639. except Exception as e:
  640. log.warning("Polygon can not be cleared. %s" % str(e))
  641. app_obj.poly_not_cleared = True
  642. continue
  643. # check if there is a geometry at all in the cleared geometry
  644. if cleared_geo:
  645. # Overall cleared area
  646. cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  647. tool / 1.999999)
  648. # clean-up cleared geo
  649. cleared = cleared.buffer(0)
  650. # find the tooluid associated with the current tool_dia so we know where to add the tool
  651. # solid_geometry
  652. for k, v in self.ncc_tools.items():
  653. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  654. current_uid = int(k)
  655. # add the solid_geometry to the current too in self.paint_tools dictionary
  656. # and then reset the temporary list that stored that solid_geometry
  657. v['solid_geometry'] = deepcopy(cleared_geo)
  658. v['data']['name'] = name
  659. break
  660. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  661. else:
  662. log.debug("There are no geometries in the cleared polygon.")
  663. geo_obj.options["cnctooldia"] = str(tool)
  664. geo_obj.multigeo = True
  665. def job_thread(app_obj):
  666. try:
  667. app_obj.new_object("geometry", name, initialize)
  668. except Exception as e:
  669. proc.done()
  670. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  671. return
  672. proc.done()
  673. if app_obj.poly_not_cleared is False:
  674. self.app.inform.emit(_('[success] NCC Tool finished.'))
  675. else:
  676. self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  677. 'Check the result.'))
  678. # reset the variable for next use
  679. app_obj.poly_not_cleared = False
  680. # focus on Selected Tab
  681. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  682. self.tools_frame.hide()
  683. self.app.ui.notebook.setTabText(2, _("Tools"))
  684. # Promise object with the new name
  685. self.app.collection.promise(name)
  686. # Background
  687. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  688. # clear copper with 'rest-machining' algorithm
  689. def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  690. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  691. # Sort tools in descending order
  692. sorted_tools = []
  693. for k, v in self.ncc_tools.items():
  694. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  695. sorted_tools.sort(reverse=True)
  696. # Do job in background
  697. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  698. def initialize_rm(geo_obj, app_obj):
  699. assert isinstance(geo_obj, FlatCAMGeometry), \
  700. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  701. cleared_geo = []
  702. cleared_by_last_tool = []
  703. rest_geo = []
  704. current_uid = 1
  705. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  706. app_obj.poly_not_cleared = True
  707. area = empty.buffer(0)
  708. # Generate area for each tool
  709. while sorted_tools:
  710. tool = sorted_tools.pop(0)
  711. self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  712. tool_used = tool - 1e-12
  713. cleared_geo[:] = []
  714. # Area to clear
  715. for poly in cleared_by_last_tool:
  716. try:
  717. area = area.difference(poly)
  718. except:
  719. pass
  720. cleared_by_last_tool[:] = []
  721. # Transform area to MultiPolygon
  722. if type(area) is Polygon:
  723. area = MultiPolygon([area])
  724. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  725. # and rest_geo it's a list
  726. allparts = [p.buffer(0) for p in area.geoms]
  727. allparts += deepcopy(rest_geo)
  728. rest_geo[:] = []
  729. area = MultiPolygon(deepcopy(allparts))
  730. allparts[:] = []
  731. if area.geoms:
  732. if len(area.geoms) > 0:
  733. for p in area.geoms:
  734. try:
  735. if pol_method == 'standard':
  736. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  737. overlap=over, contour=contour, connect=connect)
  738. elif pol_method == 'seed':
  739. cp = self.clear_polygon2(p, tool_used,
  740. self.app.defaults["gerber_circle_steps"],
  741. overlap=over, contour=contour, connect=connect)
  742. else:
  743. cp = self.clear_polygon3(p, tool_used,
  744. self.app.defaults["gerber_circle_steps"],
  745. overlap=over, contour=contour, connect=connect)
  746. cleared_geo.append(list(cp.get_objects()))
  747. except:
  748. log.warning("Polygon can't be cleared.")
  749. # this polygon should be added to a list and then try clear it with a smaller tool
  750. rest_geo.append(p)
  751. # check if there is a geometry at all in the cleared geometry
  752. if cleared_geo:
  753. # Overall cleared area
  754. cleared_area = list(self.flatten_list(cleared_geo))
  755. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  756. # for p in cleared_area])
  757. # here we store the poly's already processed in the original geometry by the current tool
  758. # into cleared_by_last_tool list
  759. # this will be sustracted from the original geometry_to_be_cleared and make data for
  760. # the next tool
  761. buffer_value = tool_used / 2
  762. for p in cleared_area:
  763. poly = p.buffer(buffer_value)
  764. cleared_by_last_tool.append(poly)
  765. # find the tooluid associated with the current tool_dia so we know
  766. # where to add the tool solid_geometry
  767. for k, v in self.ncc_tools.items():
  768. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  769. current_uid = int(k)
  770. # add the solid_geometry to the current too in self.paint_tools dictionary
  771. # and then reset the temporary list that stored that solid_geometry
  772. v['solid_geometry'] = deepcopy(cleared_area)
  773. v['data']['name'] = name
  774. cleared_area[:] = []
  775. break
  776. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  777. else:
  778. log.debug("There are no geometries in the cleared polygon.")
  779. geo_obj.multigeo = True
  780. geo_obj.options["cnctooldia"] = str(tool)
  781. # check to see if geo_obj.tools is empty
  782. # it will be updated only if there is a solid_geometry for tools
  783. if geo_obj.tools:
  784. return
  785. else:
  786. # I will use this variable for this purpose although it was meant for something else
  787. # signal that we have no geo in the object therefore don't create it
  788. app_obj.poly_not_cleared = False
  789. return "fail"
  790. def job_thread(app_obj):
  791. try:
  792. app_obj.new_object("geometry", name, initialize_rm)
  793. except Exception as e:
  794. proc.done()
  795. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  796. return
  797. if app_obj.poly_not_cleared is True:
  798. self.app.inform.emit('[success] NCC Tool finished.')
  799. # focus on Selected Tab
  800. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  801. else:
  802. self.app.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  803. 'with current settings.'))
  804. # focus on Project Tab
  805. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  806. proc.done()
  807. # reset the variable for next use
  808. app_obj.poly_not_cleared = False
  809. self.tools_frame.hide()
  810. self.app.ui.notebook.setTabText(2, "Tools")
  811. # Promise object with the new name
  812. self.app.collection.promise(name)
  813. # Background
  814. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  815. def reset_fields(self):
  816. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))