ToolNonCopperClear.py 52 KB

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