ToolNonCopperClear.py 54 KB

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