ToolNonCopperClear.py 40 KB

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