ToolNonCopperClear.py 39 KB

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