ToolNonCopperClear.py 40 KB

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