ToolNonCopperClear.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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([
  267. {'label': _('Itself'), 'value': 'itself'},
  268. {"label": _("Area Selection"), "value": "area"},
  269. {'label': _("Reference Object"), 'value': 'box'}
  270. ], orientation='vertical', stretch=False)
  271. self.reference_label = QtWidgets.QLabel(_("Reference:"))
  272. self.reference_label.setToolTip(
  273. _("When choosing the 'Itself' option the non copper clearing extent\n"
  274. "is based on the object that is copper cleared.\n "
  275. "Area Selection - left mouse click to start selection of the area to be painted.\n"
  276. "Choosing the 'Reference Object' option will do non copper clearing within the box\n"
  277. "specified by another object different than the one that is copper cleared.")
  278. )
  279. grid3.addWidget(self.reference_label, 9, 0)
  280. grid3.addWidget(self.reference_radio, 9, 1)
  281. form1 = QtWidgets.QFormLayout()
  282. self.tools_box.addLayout(form1)
  283. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  284. self.box_combo_type_label.setToolTip(
  285. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  286. "It can be Gerber, Excellon or Geometry.")
  287. )
  288. self.box_combo_type = QtWidgets.QComboBox()
  289. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  290. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  291. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  292. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  293. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  294. self.box_combo_label.setToolTip(
  295. _("The FlatCAM object to be used as non copper clearing reference.")
  296. )
  297. self.box_combo = QtWidgets.QComboBox()
  298. self.box_combo.setModel(self.app.collection)
  299. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  300. self.box_combo.setCurrentIndex(1)
  301. form1.addRow(self.box_combo_label, self.box_combo)
  302. self.box_combo.hide()
  303. self.box_combo_label.hide()
  304. self.box_combo_type.hide()
  305. self.box_combo_type_label.hide()
  306. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  307. self.generate_ncc_button.setToolTip(
  308. _("Create the Geometry Object\n"
  309. "for non-copper routing.")
  310. )
  311. self.tools_box.addWidget(self.generate_ncc_button)
  312. self.tools_box.addStretch()
  313. self.units = ''
  314. self.ncc_tools = {}
  315. self.tooluid = 0
  316. # store here the default data for Geometry Data
  317. self.default_data = {}
  318. self.obj_name = ""
  319. self.ncc_obj = None
  320. self.sel_rect = []
  321. self.bound_obj_name = ""
  322. self.bound_obj = None
  323. self.first_click = False
  324. self.cursor_pos = None
  325. self.mouse_is_dragging = False
  326. self.addtool_btn.clicked.connect(self.on_tool_add)
  327. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  328. self.deltool_btn.clicked.connect(self.on_tool_delete)
  329. self.generate_ncc_button.clicked.connect(self.on_ncc_click)
  330. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  331. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  332. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  333. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  334. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  335. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  336. def on_type_obj_index_changed(self, index):
  337. obj_type = self.type_obj_combo.currentIndex()
  338. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  339. self.obj_combo.setCurrentIndex(0)
  340. def install(self, icon=None, separator=None, **kwargs):
  341. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  342. def run(self, toggle=True):
  343. self.app.report_usage("ToolNonCopperClear()")
  344. if toggle:
  345. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  346. if self.app.ui.splitter.sizes()[0] == 0:
  347. self.app.ui.splitter.setSizes([1, 1])
  348. else:
  349. try:
  350. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  351. self.app.ui.splitter.setSizes([0, 1])
  352. except AttributeError:
  353. pass
  354. else:
  355. if self.app.ui.splitter.sizes()[0] == 0:
  356. self.app.ui.splitter.setSizes([1, 1])
  357. FlatCAMTool.run(self)
  358. self.set_tool_ui()
  359. # reset those objects on a new run
  360. self.ncc_obj = None
  361. self.bound_obj = None
  362. self.obj_name = ''
  363. self.bound_obj_name = ''
  364. self.build_ui()
  365. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  366. def set_tool_ui(self):
  367. self.tools_frame.show()
  368. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  369. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  370. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  371. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  372. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  373. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  374. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  375. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  376. self.tools_table.setupContextMenu()
  377. self.tools_table.addContextMenu(
  378. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  379. self.tools_table.addContextMenu(
  380. "Delete", lambda:
  381. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  382. # init the working variables
  383. self.default_data.clear()
  384. self.default_data.update({
  385. "name": '_ncc',
  386. "plot": self.app.defaults["geometry_plot"],
  387. "cutz": self.app.defaults["geometry_cutz"],
  388. "vtipdia": 0.1,
  389. "vtipangle": 30,
  390. "travelz": self.app.defaults["geometry_travelz"],
  391. "feedrate": self.app.defaults["geometry_feedrate"],
  392. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  393. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  394. "dwell": self.app.defaults["geometry_dwell"],
  395. "dwelltime": self.app.defaults["geometry_dwelltime"],
  396. "multidepth": self.app.defaults["geometry_multidepth"],
  397. "ppname_g": self.app.defaults["geometry_ppname_g"],
  398. "depthperpass": self.app.defaults["geometry_depthperpass"],
  399. "extracut": self.app.defaults["geometry_extracut"],
  400. "toolchange": self.app.defaults["geometry_toolchange"],
  401. "toolchangez": self.app.defaults["geometry_toolchangez"],
  402. "endz": self.app.defaults["geometry_endz"],
  403. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  404. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  405. "startz": self.app.defaults["geometry_startz"],
  406. "tooldia": self.app.defaults["tools_painttooldia"],
  407. "paintmargin": self.app.defaults["tools_paintmargin"],
  408. "paintmethod": self.app.defaults["tools_paintmethod"],
  409. "selectmethod": self.app.defaults["tools_selectmethod"],
  410. "pathconnect": self.app.defaults["tools_pathconnect"],
  411. "paintcontour": self.app.defaults["tools_paintcontour"],
  412. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  413. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  414. "nccmargin": self.app.defaults["tools_nccmargin"],
  415. "nccmethod": self.app.defaults["tools_nccmethod"],
  416. "nccconnect": self.app.defaults["tools_nccconnect"],
  417. "ncccontour": self.app.defaults["tools_ncccontour"],
  418. "nccrest": self.app.defaults["tools_nccrest"]
  419. })
  420. try:
  421. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  422. except Exception as e:
  423. log.error("At least one tool diameter needed. "
  424. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  425. return
  426. self.tooluid = 0
  427. self.ncc_tools.clear()
  428. for tool_dia in dias:
  429. self.tooluid += 1
  430. self.ncc_tools.update({
  431. int(self.tooluid): {
  432. 'tooldia': float('%.4f' % tool_dia),
  433. 'offset': 'Path',
  434. 'offset_value': 0.0,
  435. 'type': 'Iso',
  436. 'tool_type': 'V',
  437. 'data': dict(self.default_data),
  438. 'solid_geometry': []
  439. }
  440. })
  441. self.obj_name = ""
  442. self.ncc_obj = None
  443. self.bound_obj_name = ""
  444. self.bound_obj = None
  445. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  446. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  447. def build_ui(self):
  448. self.ui_disconnect()
  449. # updated units
  450. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  451. if self.units == "IN":
  452. self.addtool_entry.set_value(0.039)
  453. else:
  454. self.addtool_entry.set_value(1)
  455. sorted_tools = []
  456. for k, v in self.ncc_tools.items():
  457. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  458. order = self.ncc_order_radio.get_value()
  459. if order == 'fwd':
  460. sorted_tools.sort(reverse=False)
  461. elif order == 'rev':
  462. sorted_tools.sort(reverse=True)
  463. else:
  464. pass
  465. n = len(sorted_tools)
  466. self.tools_table.setRowCount(n)
  467. tool_id = 0
  468. for tool_sorted in sorted_tools:
  469. for tooluid_key, tooluid_value in self.ncc_tools.items():
  470. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  471. tool_id += 1
  472. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  473. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  474. row_no = tool_id - 1
  475. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  476. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  477. # There are no drill bits in MM with more than 3 decimals diameter
  478. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  479. if self.units == 'MM':
  480. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  481. else:
  482. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  483. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  484. tool_type_item = QtWidgets.QComboBox()
  485. for item in self.tool_type_item_options:
  486. tool_type_item.addItem(item)
  487. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  488. idx = tool_type_item.findText(tooluid_value['tool_type'])
  489. tool_type_item.setCurrentIndex(idx)
  490. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  491. self.tools_table.setItem(row_no, 1, dia) # Diameter
  492. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  493. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  494. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  495. # make the diameter column editable
  496. for row in range(tool_id):
  497. self.tools_table.item(row, 1).setFlags(
  498. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  499. # all the tools are selected by default
  500. self.tools_table.selectColumn(0)
  501. #
  502. self.tools_table.resizeColumnsToContents()
  503. self.tools_table.resizeRowsToContents()
  504. vertical_header = self.tools_table.verticalHeader()
  505. vertical_header.hide()
  506. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  507. horizontal_header = self.tools_table.horizontalHeader()
  508. horizontal_header.setMinimumSectionSize(10)
  509. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  510. horizontal_header.resizeSection(0, 20)
  511. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  512. # self.tools_table.setSortingEnabled(True)
  513. # sort by tool diameter
  514. # self.tools_table.sortItems(1)
  515. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  516. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  517. self.ui_connect()
  518. def ui_connect(self):
  519. self.tools_table.itemChanged.connect(self.on_tool_edit)
  520. def ui_disconnect(self):
  521. try:
  522. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  523. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  524. except (TypeError, AttributeError):
  525. pass
  526. def on_combo_box_type(self):
  527. obj_type = self.box_combo_type.currentIndex()
  528. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  529. self.box_combo.setCurrentIndex(0)
  530. def on_toggle_reference(self):
  531. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  532. self.box_combo.hide()
  533. self.box_combo_label.hide()
  534. self.box_combo_type.hide()
  535. self.box_combo_type_label.hide()
  536. else:
  537. self.box_combo.show()
  538. self.box_combo_label.show()
  539. self.box_combo_type.show()
  540. self.box_combo_type_label.show()
  541. def on_offset_choice(self, state):
  542. if state:
  543. self.ncc_offset_label.show()
  544. self.ncc_offset_spinner.show()
  545. else:
  546. self.ncc_offset_label.hide()
  547. self.ncc_offset_spinner.hide()
  548. def on_order_changed(self, order):
  549. if order != 'no':
  550. self.build_ui()
  551. def on_rest_machining_check(self, state):
  552. if state:
  553. self.ncc_order_radio.set_value('rev')
  554. self.ncc_order_label.setDisabled(True)
  555. self.ncc_order_radio.setDisabled(True)
  556. else:
  557. self.ncc_order_label.setDisabled(False)
  558. self.ncc_order_radio.setDisabled(False)
  559. def on_tool_add(self, dia=None, muted=None):
  560. self.ui_disconnect()
  561. if dia:
  562. tool_dia = dia
  563. else:
  564. try:
  565. tool_dia = float(self.addtool_entry.get_value())
  566. except ValueError:
  567. # try to convert comma to decimal point. if it's still not working error message and return
  568. try:
  569. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  570. except ValueError:
  571. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  572. "use a number."))
  573. return
  574. if tool_dia is None:
  575. self.build_ui()
  576. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  577. return
  578. if tool_dia == 0:
  579. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, "
  580. "in Float format."))
  581. return
  582. # construct a list of all 'tooluid' in the self.tools
  583. tool_uid_list = []
  584. for tooluid_key in self.ncc_tools:
  585. tool_uid_item = int(tooluid_key)
  586. tool_uid_list.append(tool_uid_item)
  587. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  588. if not tool_uid_list:
  589. max_uid = 0
  590. else:
  591. max_uid = max(tool_uid_list)
  592. self.tooluid = int(max_uid + 1)
  593. tool_dias = []
  594. for k, v in self.ncc_tools.items():
  595. for tool_v in v.keys():
  596. if tool_v == 'tooldia':
  597. tool_dias.append(float('%.4f' % v[tool_v]))
  598. if float('%.4f' % tool_dia) in tool_dias:
  599. if muted is None:
  600. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  601. self.tools_table.itemChanged.connect(self.on_tool_edit)
  602. return
  603. else:
  604. if muted is None:
  605. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  606. self.ncc_tools.update({
  607. int(self.tooluid): {
  608. 'tooldia': float('%.4f' % tool_dia),
  609. 'offset': 'Path',
  610. 'offset_value': 0.0,
  611. 'type': 'Iso',
  612. 'tool_type': 'V',
  613. 'data': dict(self.default_data),
  614. 'solid_geometry': []
  615. }
  616. })
  617. self.build_ui()
  618. def on_tool_edit(self):
  619. self.ui_disconnect()
  620. tool_dias = []
  621. for k, v in self.ncc_tools.items():
  622. for tool_v in v.keys():
  623. if tool_v == 'tooldia':
  624. tool_dias.append(float('%.4f' % v[tool_v]))
  625. for row in range(self.tools_table.rowCount()):
  626. try:
  627. new_tool_dia = float(self.tools_table.item(row, 1).text())
  628. except ValueError:
  629. # try to convert comma to decimal point. if it's still not working error message and return
  630. try:
  631. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  632. except ValueError:
  633. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  634. "use a number."))
  635. return
  636. tooluid = int(self.tools_table.item(row, 3).text())
  637. # identify the tool that was edited and get it's tooluid
  638. if new_tool_dia not in tool_dias:
  639. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  640. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  641. self.build_ui()
  642. return
  643. else:
  644. # identify the old tool_dia and restore the text in tool table
  645. for k, v in self.ncc_tools.items():
  646. if k == tooluid:
  647. old_tool_dia = v['tooldia']
  648. break
  649. restore_dia_item = self.tools_table.item(row, 1)
  650. restore_dia_item.setText(str(old_tool_dia))
  651. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  652. "New diameter value is already in the Tool Table."))
  653. self.build_ui()
  654. def on_tool_delete(self, rows_to_delete=None, all=None):
  655. self.ui_disconnect()
  656. deleted_tools_list = []
  657. if all:
  658. self.paint_tools.clear()
  659. self.build_ui()
  660. return
  661. if rows_to_delete:
  662. try:
  663. for row in rows_to_delete:
  664. tooluid_del = int(self.tools_table.item(row, 3).text())
  665. deleted_tools_list.append(tooluid_del)
  666. except TypeError:
  667. deleted_tools_list.append(rows_to_delete)
  668. for t in deleted_tools_list:
  669. self.ncc_tools.pop(t, None)
  670. self.build_ui()
  671. return
  672. try:
  673. if self.tools_table.selectedItems():
  674. for row_sel in self.tools_table.selectedItems():
  675. row = row_sel.row()
  676. if row < 0:
  677. continue
  678. tooluid_del = int(self.tools_table.item(row, 3).text())
  679. deleted_tools_list.append(tooluid_del)
  680. for t in deleted_tools_list:
  681. self.ncc_tools.pop(t, None)
  682. except AttributeError:
  683. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  684. return
  685. except Exception as e:
  686. log.debug(str(e))
  687. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  688. self.build_ui()
  689. def on_ncc_click(self):
  690. self.bound_obj = None
  691. self.ncc_obj = None
  692. ref_choice = self.reference_radio.get_value()
  693. if ref_choice == 'itself':
  694. self.bound_obj_name = self.object_combo.currentText()
  695. # Get source object.
  696. try:
  697. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  698. except Exception as e:
  699. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  700. return "Could not retrieve object: %s" % self.obj_name
  701. self.on_ncc()
  702. elif ref_choice == 'box':
  703. self.bound_obj_name = self.box_combo.currentText()
  704. # Get source object.
  705. try:
  706. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  707. except Exception as e:
  708. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.bound_obj_name)
  709. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  710. self.on_ncc()
  711. else:
  712. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the area."))
  713. # use the first tool in the tool table; get the diameter
  714. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  715. # To be called after clicking on the plot.
  716. def on_mouse_release(event):
  717. # do paint single only for left mouse clicks
  718. if event.button == 1:
  719. if self.first_click is False:
  720. self.first_click = True
  721. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  722. self.cursor_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  723. if self.app.grid_status() == True:
  724. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  725. else:
  726. self.app.inform.emit(_("Zone added. Right click to finish."))
  727. self.app.delete_selection_shape()
  728. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  729. if self.app.grid_status() == True:
  730. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  731. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  732. x1, y1 = curr_pos[0], curr_pos[1]
  733. pt1 = (x0, y0)
  734. pt2 = (x1, y0)
  735. pt3 = (x1, y1)
  736. pt4 = (x0, y1)
  737. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  738. modifiers = QtWidgets.QApplication.keyboardModifiers()
  739. if modifiers == QtCore.Qt.ShiftModifier:
  740. mod_key = 'Shift'
  741. elif modifiers == QtCore.Qt.ControlModifier:
  742. mod_key = 'Control'
  743. else:
  744. mod_key = None
  745. if mod_key == self.app.defaults["global_mselect_key"]:
  746. self.first_click = False
  747. return
  748. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  749. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  750. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  751. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  752. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  753. self.on_ncc()
  754. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  755. self.first_click = False
  756. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  757. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  758. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  759. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  760. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  761. self.on_ncc()
  762. # called on mouse move
  763. def on_mouse_move(event):
  764. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  765. self.app.app_cursor.enabled = False
  766. if event.button == 2:
  767. if event.is_dragging is True:
  768. self.mouse_is_dragging = True
  769. else:
  770. self.mouse_is_dragging = False
  771. if self.app.grid_status() == True:
  772. self.app.app_cursor.enabled = True
  773. # Update cursor
  774. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  775. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  776. symbol='++', edge_color='black', size=20)
  777. if self.first_click:
  778. self.app.delete_selection_shape()
  779. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  780. coords=(curr_pos[0], curr_pos[1]),
  781. face_alpha=0.0)
  782. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  783. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  784. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  785. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  786. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  787. def on_ncc(self):
  788. try:
  789. over = float(self.ncc_overlap_entry.get_value())
  790. except ValueError:
  791. # try to convert comma to decimal point. if it's still not working error message and return
  792. try:
  793. over = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  794. except ValueError:
  795. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  796. "use a number."))
  797. return
  798. over = over if over else self.app.defaults["tools_nccoverlap"]
  799. if over >= 1 or over < 0:
  800. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  801. "0 (inclusive) and 1 (exclusive), "))
  802. return
  803. try:
  804. margin = float(self.ncc_margin_entry.get_value())
  805. except ValueError:
  806. # try to convert comma to decimal point. if it's still not working error message and return
  807. try:
  808. margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  809. except ValueError:
  810. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  811. "use a number."))
  812. return
  813. margin = margin if margin is not None else float(self.app.defaults["tools_nccmargin"])
  814. try:
  815. ncc_offset_value = float(self.ncc_offset_spinner.get_value())
  816. except ValueError:
  817. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  818. "use a number."))
  819. return
  820. ncc_offset_value = ncc_offset_value if ncc_offset_value is not None \
  821. else float(self.app.defaults["tools_ncc_offset_value"])
  822. connect = self.ncc_connect_cb.get_value()
  823. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  824. contour = self.ncc_contour_cb.get_value()
  825. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  826. clearing_method = self.ncc_rest_cb.get_value()
  827. clearing_method = clearing_method if clearing_method else self.app.defaults["tools_nccrest"]
  828. pol_method = self.ncc_method_radio.get_value()
  829. pol_method = pol_method if pol_method else self.app.defaults["tools_nccmethod"]
  830. self.obj_name = self.obj_combo.currentText()
  831. # Get source object.
  832. try:
  833. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  834. except Exception as e:
  835. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  836. return "Could not retrieve object: %s" % self.obj_name
  837. # Prepare non-copper polygons
  838. if self.reference_radio.get_value() == 'area':
  839. geo_n = self.sel_rect
  840. geo_buff_list = []
  841. for poly in geo_n:
  842. geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  843. bounding_box = cascaded_union(geo_buff_list)
  844. else:
  845. geo_n = self.bound_obj.solid_geometry
  846. try:
  847. if isinstance(geo_n, MultiPolygon):
  848. env_obj = geo_n.convex_hull
  849. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  850. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  851. env_obj = cascaded_union(geo_n)
  852. else:
  853. env_obj = cascaded_union(geo_n)
  854. env_obj = env_obj.convex_hull
  855. bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  856. except Exception as e:
  857. log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  858. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  859. return
  860. # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  861. if isinstance(self.ncc_obj, FlatCAMGerber):
  862. if self.ncc_choice_offset_cb.isChecked():
  863. self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  864. offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  865. self.app.inform.emit(_("[success] Buffering finished ..."))
  866. empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  867. else:
  868. empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  869. elif isinstance(self.ncc_obj, FlatCAMGeometry):
  870. sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  871. if self.ncc_choice_offset_cb.isChecked():
  872. self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  873. offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  874. self.app.inform.emit(_("[success] Buffering finished ..."))
  875. empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  876. else:
  877. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  878. else:
  879. self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  880. return
  881. if type(empty) is Polygon:
  882. empty = MultiPolygon([empty])
  883. if empty.is_empty:
  884. self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  885. return
  886. # clear non copper using standard algorithm
  887. if clearing_method is False:
  888. self.clear_non_copper(
  889. empty=empty,
  890. over=over,
  891. pol_method=pol_method,
  892. connect=connect,
  893. contour=contour
  894. )
  895. # clear non copper using rest machining algorithm
  896. else:
  897. self.clear_non_copper_rest(
  898. empty=empty,
  899. over=over,
  900. pol_method=pol_method,
  901. connect=connect,
  902. contour=contour
  903. )
  904. def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  905. name = outname if outname else self.obj_name + "_ncc"
  906. # Sort tools in descending order
  907. sorted_tools = []
  908. for k, v in self.ncc_tools.items():
  909. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  910. order = self.ncc_order_radio.get_value()
  911. if order == 'fwd':
  912. sorted_tools.sort(reverse=False)
  913. elif order == 'rev':
  914. sorted_tools.sort(reverse=True)
  915. else:
  916. pass
  917. # Do job in background
  918. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  919. def initialize(geo_obj, app_obj):
  920. assert isinstance(geo_obj, FlatCAMGeometry), \
  921. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  922. cleared_geo = []
  923. # Already cleared area
  924. cleared = MultiPolygon()
  925. # flag for polygons not cleared
  926. app_obj.poly_not_cleared = False
  927. # Generate area for each tool
  928. offset = sum(sorted_tools)
  929. current_uid = int(1)
  930. tool = eval(self.app.defaults["tools_ncctools"])[0]
  931. for tool in sorted_tools:
  932. self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  933. cleared_geo[:] = []
  934. # Get remaining tools offset
  935. offset -= (tool - 1e-12)
  936. # Area to clear
  937. area = empty.buffer(-offset)
  938. try:
  939. area = area.difference(cleared)
  940. except Exception as e:
  941. continue
  942. # Transform area to MultiPolygon
  943. if type(area) is Polygon:
  944. area = MultiPolygon([area])
  945. if area.geoms:
  946. if len(area.geoms) > 0:
  947. for p in area.geoms:
  948. try:
  949. if pol_method == 'standard':
  950. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  951. overlap=over, contour=contour, connect=connect)
  952. elif pol_method == 'seed':
  953. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  954. overlap=over, contour=contour, connect=connect)
  955. else:
  956. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  957. overlap=over, contour=contour, connect=connect)
  958. if cp:
  959. cleared_geo += list(cp.get_objects())
  960. except Exception as e:
  961. log.warning("Polygon can not be cleared. %s" % str(e))
  962. app_obj.poly_not_cleared = True
  963. continue
  964. # check if there is a geometry at all in the cleared geometry
  965. if cleared_geo:
  966. # Overall cleared area
  967. cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  968. tool / 1.999999)
  969. # clean-up cleared geo
  970. cleared = cleared.buffer(0)
  971. # find the tooluid associated with the current tool_dia so we know where to add the tool
  972. # solid_geometry
  973. for k, v in self.ncc_tools.items():
  974. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  975. current_uid = int(k)
  976. # add the solid_geometry to the current too in self.paint_tools dictionary
  977. # and then reset the temporary list that stored that solid_geometry
  978. v['solid_geometry'] = deepcopy(cleared_geo)
  979. v['data']['name'] = name
  980. break
  981. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  982. else:
  983. log.debug("There are no geometries in the cleared polygon.")
  984. geo_obj.options["cnctooldia"] = str(tool)
  985. geo_obj.multigeo = True
  986. def job_thread(app_obj):
  987. try:
  988. app_obj.new_object("geometry", name, initialize)
  989. except Exception as e:
  990. proc.done()
  991. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  992. return
  993. proc.done()
  994. if app_obj.poly_not_cleared is False:
  995. self.app.inform.emit(_('[success] NCC Tool finished.'))
  996. else:
  997. self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  998. 'Check the result.'))
  999. # reset the variable for next use
  1000. app_obj.poly_not_cleared = False
  1001. # focus on Selected Tab
  1002. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1003. self.tools_frame.hide()
  1004. self.app.ui.notebook.setTabText(2, _("Tools"))
  1005. # Promise object with the new name
  1006. self.app.collection.promise(name)
  1007. # Background
  1008. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1009. # clear copper with 'rest-machining' algorithm
  1010. def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1011. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1012. # Sort tools in descending order
  1013. sorted_tools = []
  1014. for k, v in self.ncc_tools.items():
  1015. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1016. sorted_tools.sort(reverse=True)
  1017. # Do job in background
  1018. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1019. def initialize_rm(geo_obj, app_obj):
  1020. assert isinstance(geo_obj, FlatCAMGeometry), \
  1021. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1022. cleared_geo = []
  1023. cleared_by_last_tool = []
  1024. rest_geo = []
  1025. current_uid = 1
  1026. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1027. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1028. app_obj.poly_not_cleared = True
  1029. area = empty.buffer(0)
  1030. # Generate area for each tool
  1031. while sorted_tools:
  1032. tool = sorted_tools.pop(0)
  1033. self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1034. tool_used = tool - 1e-12
  1035. cleared_geo[:] = []
  1036. # Area to clear
  1037. for poly in cleared_by_last_tool:
  1038. try:
  1039. area = area.difference(poly)
  1040. except Exception as e:
  1041. pass
  1042. cleared_by_last_tool[:] = []
  1043. # Transform area to MultiPolygon
  1044. if type(area) is Polygon:
  1045. area = MultiPolygon([area])
  1046. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1047. # and rest_geo it's a list
  1048. allparts = [p.buffer(0) for p in area.geoms]
  1049. allparts += deepcopy(rest_geo)
  1050. rest_geo[:] = []
  1051. area = MultiPolygon(deepcopy(allparts))
  1052. allparts[:] = []
  1053. if area.geoms:
  1054. if len(area.geoms) > 0:
  1055. for p in area.geoms:
  1056. try:
  1057. if pol_method == 'standard':
  1058. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1059. overlap=over, contour=contour, connect=connect)
  1060. elif pol_method == 'seed':
  1061. cp = self.clear_polygon2(p, tool_used,
  1062. self.app.defaults["gerber_circle_steps"],
  1063. overlap=over, contour=contour, connect=connect)
  1064. else:
  1065. cp = self.clear_polygon3(p, tool_used,
  1066. self.app.defaults["gerber_circle_steps"],
  1067. overlap=over, contour=contour, connect=connect)
  1068. cleared_geo.append(list(cp.get_objects()))
  1069. except:
  1070. log.warning("Polygon can't be cleared.")
  1071. # this polygon should be added to a list and then try clear it with a smaller tool
  1072. rest_geo.append(p)
  1073. # check if there is a geometry at all in the cleared geometry
  1074. if cleared_geo:
  1075. # Overall cleared area
  1076. cleared_area = list(self.flatten_list(cleared_geo))
  1077. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1078. # for p in cleared_area])
  1079. # here we store the poly's already processed in the original geometry by the current tool
  1080. # into cleared_by_last_tool list
  1081. # this will be sustracted from the original geometry_to_be_cleared and make data for
  1082. # the next tool
  1083. buffer_value = tool_used / 2
  1084. for p in cleared_area:
  1085. poly = p.buffer(buffer_value)
  1086. cleared_by_last_tool.append(poly)
  1087. # find the tooluid associated with the current tool_dia so we know
  1088. # where to add the tool solid_geometry
  1089. for k, v in self.ncc_tools.items():
  1090. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1091. current_uid = int(k)
  1092. # add the solid_geometry to the current too in self.paint_tools dictionary
  1093. # and then reset the temporary list that stored that solid_geometry
  1094. v['solid_geometry'] = deepcopy(cleared_area)
  1095. v['data']['name'] = name
  1096. cleared_area[:] = []
  1097. break
  1098. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1099. else:
  1100. log.debug("There are no geometries in the cleared polygon.")
  1101. geo_obj.multigeo = True
  1102. geo_obj.options["cnctooldia"] = str(tool)
  1103. # check to see if geo_obj.tools is empty
  1104. # it will be updated only if there is a solid_geometry for tools
  1105. if geo_obj.tools:
  1106. return
  1107. else:
  1108. # I will use this variable for this purpose although it was meant for something else
  1109. # signal that we have no geo in the object therefore don't create it
  1110. app_obj.poly_not_cleared = False
  1111. return "fail"
  1112. def job_thread(app_obj):
  1113. try:
  1114. app_obj.new_object("geometry", name, initialize_rm)
  1115. except Exception as e:
  1116. proc.done()
  1117. app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  1118. return
  1119. if app_obj.poly_not_cleared is True:
  1120. app_obj.inform.emit('[success] NCC Tool finished.')
  1121. # focus on Selected Tab
  1122. app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1123. else:
  1124. app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  1125. 'with current settings.'))
  1126. # focus on Project Tab
  1127. app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1128. proc.done()
  1129. # reset the variable for next use
  1130. app_obj.poly_not_cleared = False
  1131. self.tools_frame.hide()
  1132. app_obj.ui.notebook.setTabText(2, "Tools")
  1133. # Promise object with the new name
  1134. self.app.collection.promise(name)
  1135. # Background
  1136. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1137. @staticmethod
  1138. def get_ncc_empty_area(target, boundary=None):
  1139. """
  1140. Returns the complement of target geometry within
  1141. the given boundary polygon. If not specified, it defaults to
  1142. the rectangular bounding box of target geometry.
  1143. """
  1144. if boundary is None:
  1145. boundary = target.envelope
  1146. return boundary.difference(target)
  1147. def reset_fields(self):
  1148. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))