ToolNonCopperClear.py 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332
  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.object_combo = QtWidgets.QComboBox()
  68. self.object_combo.setModel(self.app.collection)
  69. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  70. self.object_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.object_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(5)
  86. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), '', _("Operation")])
  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:\n"
  103. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  104. "the cut width in material is exactly the tool diameter.\n"
  105. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  106. "- V-Shape -> it will disable de Z-Cut parameter in the resulting geometry UI form\n"
  107. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  108. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  109. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  110. "column of this table.\n"
  111. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  112. "in the resulting geometry as Isolation."))
  113. self.tools_table.horizontalHeaderItem(4).setToolTip(
  114. _("The 'Operation' can be:\n"
  115. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  116. "If it's not successful then the non-copper clearing will fail, too.\n"
  117. "- Clear -> the regular non-copper clearing."))
  118. # Milling Type Radio Button
  119. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  120. self.milling_type_label.setToolTip(
  121. _("Milling type when the selected tool is of type: 'iso_op':\n"
  122. "- climb / best for precision milling and to reduce tool usage\n"
  123. "- conventional / useful when there is no backlash compensation")
  124. )
  125. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  126. {'label': _('Conv.'), 'value': 'cv'}])
  127. self.milling_type_radio.setToolTip(
  128. _("Milling type when the selected tool is of type: 'iso_op':\n"
  129. "- climb / best for precision milling and to reduce tool usage\n"
  130. "- conventional / useful when there is no backlash compensation")
  131. )
  132. # Tool order
  133. self.ncc_order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  134. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  135. "'No' --> means that the used order is the one in the tool table\n"
  136. "'Forward' --> means that the tools will be ordered from small to big\n"
  137. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  138. "WARNING: using rest machining will automatically set the order\n"
  139. "in reverse and disable this control."))
  140. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  141. {'label': _('Forward'), 'value': 'fwd'},
  142. {'label': _('Reverse'), 'value': 'rev'}])
  143. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  144. "'No' --> means that the used order is the one in the tool table\n"
  145. "'Forward' --> means that the tools will be ordered from small to big\n"
  146. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  147. "WARNING: using rest machining will automatically set the order\n"
  148. "in reverse and disable this control."))
  149. form = QtWidgets.QFormLayout()
  150. self.tools_box.addLayout(form)
  151. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  152. form.addRow(self.milling_type_label, self.milling_type_radio)
  153. form.addRow(self.ncc_order_label, self.ncc_order_radio)
  154. self.milling_type_label.hide()
  155. self.milling_type_radio.hide()
  156. # Tool Type Radio Button
  157. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  158. self.tool_type_label.setToolTip(
  159. _("Default tool type:\n"
  160. "- 'V-shape'\n"
  161. "- Circular")
  162. )
  163. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  164. {'label': _('Circular'), 'value': 'C1'}])
  165. self.tool_type_radio.setToolTip(
  166. _("Default tool type:\n"
  167. "- 'V-shape'\n"
  168. "- Circular")
  169. )
  170. form.addRow(self.tool_type_label, self.tool_type_radio)
  171. # ### Add a new Tool ####
  172. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  173. self.addtool_entry_lbl.setToolTip(
  174. _("Diameter for the new tool to add in the Tool Table")
  175. )
  176. self.addtool_entry = FCEntry2()
  177. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  178. # Tip Dia
  179. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  180. self.tipdialabel.setToolTip(
  181. _("The tip diameter for V-Shape Tool"))
  182. self.tipdia_entry = LengthEntry()
  183. form.addRow(self.tipdialabel, self.tipdia_entry)
  184. # Tip Angle
  185. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  186. self.tipanglelabel.setToolTip(
  187. _("The tip angle for V-Shape Tool.\n"
  188. "In degree."))
  189. self.tipangle_entry = LengthEntry()
  190. form.addRow(self.tipanglelabel, self.tipangle_entry)
  191. grid2 = QtWidgets.QGridLayout()
  192. self.tools_box.addLayout(grid2)
  193. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  194. self.addtool_btn.setToolTip(
  195. _("Add a new tool to the Tool Table\n"
  196. "with the diameter specified above.")
  197. )
  198. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  199. # self.copytool_btn.setToolTip(
  200. # "Copy a selection of tools in the Tool Table\n"
  201. # "by first selecting a row in the Tool Table."
  202. # )
  203. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  204. self.deltool_btn.setToolTip(
  205. _("Delete a selection of tools in the Tool Table\n"
  206. "by first selecting a row(s) in the Tool Table.")
  207. )
  208. grid2.addWidget(self.addtool_btn, 0, 0)
  209. # grid2.addWidget(self.copytool_btn, 0, 1)
  210. grid2.addWidget(self.deltool_btn, 0, 2)
  211. self.empty_label_0 = QtWidgets.QLabel('')
  212. self.tools_box.addWidget(self.empty_label_0)
  213. grid3 = QtWidgets.QGridLayout()
  214. self.tools_box.addLayout(grid3)
  215. e_lab_1 = QtWidgets.QLabel('<b>%s:</b>' % _("Parameters"))
  216. grid3.addWidget(e_lab_1, 0, 0)
  217. # Cut Z entry
  218. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  219. cutzlabel.setToolTip(
  220. _("Depth of cut into material. Negative value.\n"
  221. "In FlatCAM units.")
  222. )
  223. self.cutz_entry = FloatEntry()
  224. self.cutz_entry.setToolTip(
  225. _("Depth of cut into material. Negative value.\n"
  226. "In FlatCAM units.")
  227. )
  228. grid3.addWidget(cutzlabel, 1, 0)
  229. grid3.addWidget(self.cutz_entry, 1, 1)
  230. # Overlap Entry
  231. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  232. nccoverlabel.setToolTip(
  233. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  234. "Example:\n"
  235. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  236. "Adjust the value starting with lower values\n"
  237. "and increasing it if areas that should be cleared are still \n"
  238. "not cleared.\n"
  239. "Lower values = faster processing, faster execution on PCB.\n"
  240. "Higher values = slow processing and slow execution on CNC\n"
  241. "due of too many paths.")
  242. )
  243. self.ncc_overlap_entry = FCEntry()
  244. grid3.addWidget(nccoverlabel, 2, 0)
  245. grid3.addWidget(self.ncc_overlap_entry, 2, 1)
  246. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  247. nccmarginlabel.setToolTip(
  248. _("Bounding box margin.")
  249. )
  250. grid3.addWidget(nccmarginlabel, 3, 0)
  251. self.ncc_margin_entry = FCEntry()
  252. grid3.addWidget(self.ncc_margin_entry, 3, 1)
  253. # Method
  254. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  255. methodlabel.setToolTip(
  256. _("Algorithm for non-copper clearing:<BR>"
  257. "<B>Standard</B>: Fixed step inwards.<BR>"
  258. "<B>Seed-based</B>: Outwards from seed.<BR>"
  259. "<B>Line-based</B>: Parallel lines.")
  260. )
  261. grid3.addWidget(methodlabel, 4, 0)
  262. self.ncc_method_radio = RadioSet([
  263. {"label": _("Standard"), "value": "standard"},
  264. {"label": _("Seed-based"), "value": "seed"},
  265. {"label": _("Straight lines"), "value": "lines"}
  266. ], orientation='vertical', stretch=False)
  267. grid3.addWidget(self.ncc_method_radio, 4, 1)
  268. # Connect lines
  269. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  270. pathconnectlabel.setToolTip(
  271. _("Draw lines between resulting\n"
  272. "segments to minimize tool lifts.")
  273. )
  274. grid3.addWidget(pathconnectlabel, 5, 0)
  275. self.ncc_connect_cb = FCCheckBox()
  276. grid3.addWidget(self.ncc_connect_cb, 5, 1)
  277. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  278. contourlabel.setToolTip(
  279. _("Cut around the perimeter of the polygon\n"
  280. "to trim rough edges.")
  281. )
  282. grid3.addWidget(contourlabel, 6, 0)
  283. self.ncc_contour_cb = FCCheckBox()
  284. grid3.addWidget(self.ncc_contour_cb, 6, 1)
  285. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  286. restlabel.setToolTip(
  287. _("If checked, use 'rest machining'.\n"
  288. "Basically it will clear copper outside PCB features,\n"
  289. "using the biggest tool and continue with the next tools,\n"
  290. "from bigger to smaller, to clear areas of copper that\n"
  291. "could not be cleared by previous tool, until there is\n"
  292. "no more copper to clear or there are no more tools.\n"
  293. "If not checked, use the standard algorithm.")
  294. )
  295. grid3.addWidget(restlabel, 7, 0)
  296. self.ncc_rest_cb = FCCheckBox()
  297. grid3.addWidget(self.ncc_rest_cb, 7, 1)
  298. # ## NCC Offset choice
  299. self.ncc_offset_choice_label = QtWidgets.QLabel('%s:' % _("Offset"))
  300. self.ncc_offset_choice_label.setToolTip(
  301. _("If used, it will add an offset to the copper features.\n"
  302. "The copper clearing will finish to a distance\n"
  303. "from the copper features.\n"
  304. "The value can be between 0 and 10 FlatCAM units.")
  305. )
  306. grid3.addWidget(self.ncc_offset_choice_label, 8, 0)
  307. self.ncc_choice_offset_cb = FCCheckBox()
  308. grid3.addWidget(self.ncc_choice_offset_cb, 8, 1)
  309. # ## NCC Offset value
  310. self.ncc_offset_label = QtWidgets.QLabel('%s:' % _("Offset value"))
  311. self.ncc_offset_label.setToolTip(
  312. _("If used, it will add an offset to the copper features.\n"
  313. "The copper clearing will finish to a distance\n"
  314. "from the copper features.\n"
  315. "The value can be between 0 and 10 FlatCAM units.")
  316. )
  317. grid3.addWidget(self.ncc_offset_label, 9, 0)
  318. self.ncc_offset_spinner = FCDoubleSpinner()
  319. self.ncc_offset_spinner.set_range(0.00, 10.00)
  320. self.ncc_offset_spinner.set_precision(4)
  321. self.ncc_offset_spinner.setWrapping(True)
  322. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  323. if units == 'MM':
  324. self.ncc_offset_spinner.setSingleStep(0.1)
  325. else:
  326. self.ncc_offset_spinner.setSingleStep(0.01)
  327. grid3.addWidget(self.ncc_offset_spinner, 9, 1)
  328. self.ncc_offset_label.hide()
  329. self.ncc_offset_spinner.hide()
  330. # ## Reference
  331. self.reference_radio = RadioSet([
  332. {'label': _('Itself'), 'value': 'itself'},
  333. {"label": _("Area Selection"), "value": "area"},
  334. {'label': _("Reference Object"), 'value': 'box'}
  335. ], orientation='vertical', stretch=False)
  336. self.reference_label = QtWidgets.QLabel(_("Reference:"))
  337. self.reference_label.setToolTip(
  338. _("- 'Itself' - the non copper clearing extent\n"
  339. "is based on the object that is copper cleared.\n "
  340. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  341. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  342. "- 'Reference Object' - will do non copper clearing within the area\n"
  343. "specified by another object.")
  344. )
  345. grid3.addWidget(self.reference_label, 10, 0)
  346. grid3.addWidget(self.reference_radio, 10, 1)
  347. form1 = QtWidgets.QFormLayout()
  348. self.tools_box.addLayout(form1)
  349. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  350. self.box_combo_type_label.setToolTip(
  351. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  352. "It can be Gerber, Excellon or Geometry.")
  353. )
  354. self.box_combo_type = QtWidgets.QComboBox()
  355. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  356. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  357. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  358. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  359. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  360. self.box_combo_label.setToolTip(
  361. _("The FlatCAM object to be used as non copper clearing reference.")
  362. )
  363. self.box_combo = QtWidgets.QComboBox()
  364. self.box_combo.setModel(self.app.collection)
  365. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  366. self.box_combo.setCurrentIndex(1)
  367. form1.addRow(self.box_combo_label, self.box_combo)
  368. self.box_combo.hide()
  369. self.box_combo_label.hide()
  370. self.box_combo_type.hide()
  371. self.box_combo_type_label.hide()
  372. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  373. self.generate_ncc_button.setToolTip(
  374. _("Create the Geometry Object\n"
  375. "for non-copper routing.")
  376. )
  377. self.tools_box.addWidget(self.generate_ncc_button)
  378. self.tools_box.addStretch()
  379. self.tools_table.setupContextMenu()
  380. self.tools_table.addContextMenu(
  381. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  382. self.tools_table.addContextMenu(
  383. "Delete", lambda:
  384. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  385. self.units = ''
  386. self.ncc_tools = {}
  387. self.tooluid = 0
  388. # store here the default data for Geometry Data
  389. self.default_data = {}
  390. self.obj_name = ""
  391. self.ncc_obj = None
  392. self.sel_rect = []
  393. self.bound_obj_name = ""
  394. self.bound_obj = None
  395. self.first_click = False
  396. self.cursor_pos = None
  397. self.mouse_is_dragging = False
  398. # store here solid_geometry when there are tool with isolation job
  399. self.solid_geometry = []
  400. self.tool_type_item_options = []
  401. self.addtool_btn.clicked.connect(self.on_tool_add)
  402. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  403. self.deltool_btn.clicked.connect(self.on_tool_delete)
  404. self.generate_ncc_button.clicked.connect(self.on_ncc_click)
  405. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  406. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  407. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  408. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  409. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  410. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  411. def on_type_obj_index_changed(self, index):
  412. obj_type = self.type_obj_combo.currentIndex()
  413. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  414. self.object_combo.setCurrentIndex(0)
  415. def install(self, icon=None, separator=None, **kwargs):
  416. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  417. def run(self, toggle=True):
  418. self.app.report_usage("ToolNonCopperClear()")
  419. if toggle:
  420. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  421. if self.app.ui.splitter.sizes()[0] == 0:
  422. self.app.ui.splitter.setSizes([1, 1])
  423. else:
  424. try:
  425. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  426. # if tab is populated with the tool but it does not have the focus, focus on it
  427. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  428. # focus on Tool Tab
  429. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  430. else:
  431. self.app.ui.splitter.setSizes([0, 1])
  432. except AttributeError:
  433. pass
  434. else:
  435. if self.app.ui.splitter.sizes()[0] == 0:
  436. self.app.ui.splitter.setSizes([1, 1])
  437. FlatCAMTool.run(self)
  438. self.set_tool_ui()
  439. # reset those objects on a new run
  440. self.ncc_obj = None
  441. self.bound_obj = None
  442. self.obj_name = ''
  443. self.bound_obj_name = ''
  444. self.build_ui()
  445. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  446. def set_tool_ui(self):
  447. self.tools_frame.show()
  448. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  449. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  450. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  451. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  452. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  453. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  454. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  455. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  456. self.milling_type_radio.set_value(self.app.defaults["tools_nccmilling_type"])
  457. self.cutz_entry.set_value(self.app.defaults["tools_ncccutz"])
  458. self.tool_type_radio.set_value(self.app.defaults["tools_ncctool_type"])
  459. self.tipdia_entry.set_value(self.app.defaults["tools_ncctipdia"])
  460. self.tipangle_entry.set_value(self.app.defaults["tools_ncctipangle"])
  461. self.on_tool_type(val=self.tool_type_radio.get_value())
  462. # init the working variables
  463. self.default_data.clear()
  464. self.default_data.update({
  465. "name": '_ncc',
  466. "plot": self.app.defaults["geometry_plot"],
  467. "cutz": float(self.cutz_entry.get_value()),
  468. "vtipdia": float(self.tipdia_entry.get_value()),
  469. "vtipangle": float(self.tipangle_entry.get_value()),
  470. "travelz": self.app.defaults["geometry_travelz"],
  471. "feedrate": self.app.defaults["geometry_feedrate"],
  472. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  473. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  474. "dwell": self.app.defaults["geometry_dwell"],
  475. "dwelltime": self.app.defaults["geometry_dwelltime"],
  476. "multidepth": self.app.defaults["geometry_multidepth"],
  477. "ppname_g": self.app.defaults["geometry_ppname_g"],
  478. "depthperpass": self.app.defaults["geometry_depthperpass"],
  479. "extracut": self.app.defaults["geometry_extracut"],
  480. "toolchange": self.app.defaults["geometry_toolchange"],
  481. "toolchangez": self.app.defaults["geometry_toolchangez"],
  482. "endz": self.app.defaults["geometry_endz"],
  483. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  484. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  485. "startz": self.app.defaults["geometry_startz"],
  486. "tooldia": self.app.defaults["tools_painttooldia"],
  487. "paintmargin": self.app.defaults["tools_paintmargin"],
  488. "paintmethod": self.app.defaults["tools_paintmethod"],
  489. "selectmethod": self.app.defaults["tools_selectmethod"],
  490. "pathconnect": self.app.defaults["tools_pathconnect"],
  491. "paintcontour": self.app.defaults["tools_paintcontour"],
  492. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  493. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  494. "nccmargin": self.app.defaults["tools_nccmargin"],
  495. "nccmethod": self.app.defaults["tools_nccmethod"],
  496. "nccconnect": self.app.defaults["tools_nccconnect"],
  497. "ncccontour": self.app.defaults["tools_ncccontour"],
  498. "nccrest": self.app.defaults["tools_nccrest"]
  499. })
  500. try:
  501. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  502. except Exception as e:
  503. log.error("At least one tool diameter needed. "
  504. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  505. return
  506. self.tooluid = 0
  507. self.ncc_tools.clear()
  508. for tool_dia in dias:
  509. self.tooluid += 1
  510. self.ncc_tools.update({
  511. int(self.tooluid): {
  512. 'tooldia': float('%.4f' % tool_dia),
  513. 'offset': 'Path',
  514. 'offset_value': 0.0,
  515. 'type': 'Iso',
  516. 'tool_type': self.tool_type_radio.get_value(),
  517. 'operation': 'clear_op',
  518. 'data': deepcopy(self.default_data),
  519. 'solid_geometry': []
  520. }
  521. })
  522. self.obj_name = ""
  523. self.ncc_obj = None
  524. self.bound_obj_name = ""
  525. self.bound_obj = None
  526. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  527. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  528. def build_ui(self):
  529. self.ui_disconnect()
  530. # updated units
  531. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  532. if self.units == "IN":
  533. self.addtool_entry.set_value(0.039)
  534. else:
  535. self.addtool_entry.set_value(1)
  536. sorted_tools = []
  537. for k, v in self.ncc_tools.items():
  538. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  539. order = self.ncc_order_radio.get_value()
  540. if order == 'fwd':
  541. sorted_tools.sort(reverse=False)
  542. elif order == 'rev':
  543. sorted_tools.sort(reverse=True)
  544. else:
  545. pass
  546. n = len(sorted_tools)
  547. self.tools_table.setRowCount(n)
  548. tool_id = 0
  549. for tool_sorted in sorted_tools:
  550. for tooluid_key, tooluid_value in self.ncc_tools.items():
  551. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  552. tool_id += 1
  553. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  554. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  555. row_no = tool_id - 1
  556. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  557. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  558. # There are no drill bits in MM with more than 3 decimals diameter
  559. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  560. if self.units == 'MM':
  561. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  562. else:
  563. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  564. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  565. tool_type_item = QtWidgets.QComboBox()
  566. for item in self.tool_type_item_options:
  567. tool_type_item.addItem(item)
  568. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  569. idx = tool_type_item.findText(tooluid_value['tool_type'])
  570. tool_type_item.setCurrentIndex(idx)
  571. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  572. operation_type = QtWidgets.QComboBox()
  573. operation_type.addItem('iso_op')
  574. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  575. operation_type.addItem('clear_op')
  576. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  577. op_idx = operation_type.findText(tooluid_value['operation'])
  578. operation_type.setCurrentIndex(op_idx)
  579. self.tools_table.setItem(row_no, 1, dia) # Diameter
  580. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  581. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  582. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  583. self.tools_table.setCellWidget(row_no, 4, operation_type)
  584. # make the diameter column editable
  585. for row in range(tool_id):
  586. self.tools_table.item(row, 1).setFlags(
  587. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  588. # all the tools are selected by default
  589. self.tools_table.selectColumn(0)
  590. #
  591. self.tools_table.resizeColumnsToContents()
  592. self.tools_table.resizeRowsToContents()
  593. vertical_header = self.tools_table.verticalHeader()
  594. vertical_header.hide()
  595. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  596. horizontal_header = self.tools_table.horizontalHeader()
  597. horizontal_header.setMinimumSectionSize(10)
  598. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  599. horizontal_header.resizeSection(0, 20)
  600. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  601. # self.tools_table.setSortingEnabled(True)
  602. # sort by tool diameter
  603. # self.tools_table.sortItems(1)
  604. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  605. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  606. self.ui_connect()
  607. def ui_connect(self):
  608. self.tools_table.itemChanged.connect(self.on_tool_edit)
  609. for row in range(self.tools_table.rowCount()):
  610. for col in [2, 4]:
  611. self.tools_table.cellWidget(row, col).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  612. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  613. def ui_disconnect(self):
  614. try:
  615. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  616. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  617. except (TypeError, AttributeError):
  618. pass
  619. try:
  620. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  621. self.tool_type_radio.activated_custom.disconnect(self.on_tool_type)
  622. except (TypeError, AttributeError):
  623. pass
  624. for row in range(self.tools_table.rowCount()):
  625. for col in [2, 4]:
  626. try:
  627. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  628. except (TypeError, AttributeError):
  629. pass
  630. def on_combo_box_type(self):
  631. obj_type = self.box_combo_type.currentIndex()
  632. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  633. self.box_combo.setCurrentIndex(0)
  634. def on_toggle_reference(self):
  635. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  636. self.box_combo.hide()
  637. self.box_combo_label.hide()
  638. self.box_combo_type.hide()
  639. self.box_combo_type_label.hide()
  640. else:
  641. self.box_combo.show()
  642. self.box_combo_label.show()
  643. self.box_combo_type.show()
  644. self.box_combo_type_label.show()
  645. def on_offset_choice(self, state):
  646. if state:
  647. self.ncc_offset_label.show()
  648. self.ncc_offset_spinner.show()
  649. else:
  650. self.ncc_offset_label.hide()
  651. self.ncc_offset_spinner.hide()
  652. def on_order_changed(self, order):
  653. if order != 'no':
  654. self.build_ui()
  655. def on_rest_machining_check(self, state):
  656. if state:
  657. self.ncc_order_radio.set_value('rev')
  658. self.ncc_order_label.setDisabled(True)
  659. self.ncc_order_radio.setDisabled(True)
  660. else:
  661. self.ncc_order_label.setDisabled(False)
  662. self.ncc_order_radio.setDisabled(False)
  663. def on_tooltable_cellwidget_change(self):
  664. cw = self.sender()
  665. cw_index = self.tools_table.indexAt(cw.pos())
  666. cw_row = cw_index.row()
  667. cw_col = cw_index.column()
  668. current_uid = int(self.tools_table.item(cw_row, 3).text())
  669. hide_iso_type = True
  670. for row in range(self.tools_table.rowCount()):
  671. if self.tools_table.cellWidget(row, 4).currentText() == 'iso_op':
  672. hide_iso_type = False
  673. break
  674. if hide_iso_type is False:
  675. self.milling_type_label.show()
  676. self.milling_type_radio.show()
  677. else:
  678. self.milling_type_label.hide()
  679. self.milling_type_radio.hide()
  680. # if the sender is in the column with index 2 then we update the tool_type key
  681. if cw_col == 2:
  682. tt = cw.currentText()
  683. if tt == 'V':
  684. typ = 'Iso'
  685. else:
  686. typ = "Rough"
  687. self.ncc_tools[current_uid].update({
  688. 'type': typ,
  689. 'tool_type': tt,
  690. })
  691. def on_tool_type(self, val):
  692. if val == 'V':
  693. self.addtool_entry_lbl.hide()
  694. self.addtool_entry.hide()
  695. self.tipdialabel.show()
  696. self.tipdia_entry.show()
  697. self.tipanglelabel.show()
  698. self.tipangle_entry.show()
  699. else:
  700. self.addtool_entry_lbl.show()
  701. self.addtool_entry.show()
  702. self.tipdialabel.hide()
  703. self.tipdia_entry.hide()
  704. self.tipanglelabel.hide()
  705. self.tipangle_entry.hide()
  706. def on_tool_add(self, dia=None, muted=None):
  707. self.ui_disconnect()
  708. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  709. if dia:
  710. tool_dia = dia
  711. else:
  712. if self.tool_type_radio.get_value() == 'V':
  713. try:
  714. tip_dia = float(self.tipdia_entry.get_value())
  715. except ValueError:
  716. # try to convert comma to decimal point. if it's still not working error message and return
  717. try:
  718. tip_dia = float(self.tipdia_entry.get_value().replace(',', '.'))
  719. except ValueError:
  720. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  721. "use a number."))
  722. return
  723. try:
  724. tip_angle = float(self.tipangle_entry.get_value()) / 2
  725. except ValueError:
  726. # try to convert comma to decimal point. if it's still not working error message and return
  727. try:
  728. tip_angle = float(self.tipangle_entry.get_value().replace(',', '.')) / 2
  729. except ValueError:
  730. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  731. "use a number."))
  732. return
  733. try:
  734. cut_z = float(self.cutz_entry.get_value())
  735. except ValueError:
  736. # try to convert comma to decimal point. if it's still not working error message and return
  737. try:
  738. cut_z = float(self.cutz_entry.get_value().replace(',', '.'))
  739. except ValueError:
  740. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  741. "use a number."))
  742. return
  743. # calculated tool diameter so the cut_z parameter is obeyed
  744. tool_dia = tip_dia + 2 * cut_z * math.tan(math.radians(tip_angle))
  745. # update the default_data so it is used in the ncc_tools dict
  746. self.default_data.update({
  747. "vtipdia": tip_dia,
  748. "vtipangle": (tip_angle * 2),
  749. })
  750. else:
  751. try:
  752. tool_dia = float(self.addtool_entry.get_value())
  753. except ValueError:
  754. # try to convert comma to decimal point. if it's still not working error message and return
  755. try:
  756. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  757. except ValueError:
  758. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  759. "use a number."))
  760. return
  761. if tool_dia is None:
  762. self.build_ui()
  763. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  764. return
  765. if self.units == 'MM':
  766. tool_dia = float('%.2f' % tool_dia)
  767. else:
  768. tool_dia = float('%.4f' % tool_dia)
  769. if tool_dia == 0:
  770. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, "
  771. "in Float format."))
  772. return
  773. # construct a list of all 'tooluid' in the self.tools
  774. tool_uid_list = []
  775. for tooluid_key in self.ncc_tools:
  776. tool_uid_item = int(tooluid_key)
  777. tool_uid_list.append(tool_uid_item)
  778. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  779. if not tool_uid_list:
  780. max_uid = 0
  781. else:
  782. max_uid = max(tool_uid_list)
  783. self.tooluid = int(max_uid + 1)
  784. tool_dias = []
  785. for k, v in self.ncc_tools.items():
  786. for tool_v in v.keys():
  787. if tool_v == 'tooldia':
  788. tool_dias.append(float('%.4f' % v[tool_v]))
  789. if float('%.4f' % tool_dia) in tool_dias:
  790. if muted is None:
  791. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  792. self.tools_table.itemChanged.connect(self.on_tool_edit)
  793. return
  794. else:
  795. if muted is None:
  796. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  797. self.ncc_tools.update({
  798. int(self.tooluid): {
  799. 'tooldia': float('%.4f' % tool_dia),
  800. 'offset': 'Path',
  801. 'offset_value': 0.0,
  802. 'type': 'Iso',
  803. 'tool_type': self.tool_type_radio.get_value(),
  804. 'operation': 'clear_op',
  805. 'data': deepcopy(self.default_data),
  806. 'solid_geometry': []
  807. }
  808. })
  809. self.build_ui()
  810. def on_tool_edit(self):
  811. self.ui_disconnect()
  812. old_tool_dia = ''
  813. tool_dias = []
  814. for k, v in self.ncc_tools.items():
  815. for tool_v in v.keys():
  816. if tool_v == 'tooldia':
  817. tool_dias.append(float('%.4f' % v[tool_v]))
  818. for row in range(self.tools_table.rowCount()):
  819. try:
  820. new_tool_dia = float(self.tools_table.item(row, 1).text())
  821. except ValueError:
  822. # try to convert comma to decimal point. if it's still not working error message and return
  823. try:
  824. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  825. except ValueError:
  826. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  827. "use a number."))
  828. return
  829. tooluid = int(self.tools_table.item(row, 3).text())
  830. # identify the tool that was edited and get it's tooluid
  831. if new_tool_dia not in tool_dias:
  832. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  833. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  834. self.build_ui()
  835. return
  836. else:
  837. # identify the old tool_dia and restore the text in tool table
  838. for k, v in self.ncc_tools.items():
  839. if k == tooluid:
  840. old_tool_dia = v['tooldia']
  841. break
  842. restore_dia_item = self.tools_table.item(row, 1)
  843. restore_dia_item.setText(str(old_tool_dia))
  844. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  845. "New diameter value is already in the Tool Table."))
  846. self.build_ui()
  847. def on_tool_delete(self, rows_to_delete=None, all=None):
  848. self.ui_disconnect()
  849. deleted_tools_list = []
  850. if all:
  851. self.paint_tools.clear()
  852. self.build_ui()
  853. return
  854. if rows_to_delete:
  855. try:
  856. for row in rows_to_delete:
  857. tooluid_del = int(self.tools_table.item(row, 3).text())
  858. deleted_tools_list.append(tooluid_del)
  859. except TypeError:
  860. deleted_tools_list.append(rows_to_delete)
  861. for t in deleted_tools_list:
  862. self.ncc_tools.pop(t, None)
  863. self.build_ui()
  864. return
  865. try:
  866. if self.tools_table.selectedItems():
  867. for row_sel in self.tools_table.selectedItems():
  868. row = row_sel.row()
  869. if row < 0:
  870. continue
  871. tooluid_del = int(self.tools_table.item(row, 3).text())
  872. deleted_tools_list.append(tooluid_del)
  873. for t in deleted_tools_list:
  874. self.ncc_tools.pop(t, None)
  875. except AttributeError:
  876. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  877. return
  878. except Exception as e:
  879. log.debug(str(e))
  880. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  881. self.build_ui()
  882. def on_ncc_click(self):
  883. # init values for the next usage
  884. self.reset_usage()
  885. self.app.report_usage(_("on_paint_button_click"))
  886. try:
  887. overlap = float(self.ncc_overlap_entry.get_value())
  888. except ValueError:
  889. # try to convert comma to decimal point. if it's still not working error message and return
  890. try:
  891. overlap = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  892. except ValueError:
  893. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  894. "use a number."))
  895. return
  896. if overlap >= 1 or overlap < 0:
  897. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  898. "0 (inclusive) and 1 (exclusive), "))
  899. return
  900. connect = self.ncc_connect_cb.get_value()
  901. contour = self.ncc_contour_cb.get_value()
  902. has_offset = self.ncc_choice_offset_cb.isChecked()
  903. rest = self.ncc_rest_cb.get_value()
  904. self.obj_name = self.object_combo.currentText()
  905. # Get source object.
  906. try:
  907. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  908. except Exception as e:
  909. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  910. return "Could not retrieve object: %s" % self.obj_name
  911. if self.ncc_obj is None:
  912. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.ncc_obj)
  913. return
  914. # use the selected tools in the tool table; get diameters for non-copper clear
  915. iso_dia_list = list()
  916. # use the selected tools in the tool table; get diameters for non-copper clear
  917. ncc_dia_list = list()
  918. if self.tools_table.selectedItems():
  919. for x in self.tools_table.selectedItems():
  920. try:
  921. tooldia = float(self.tools_table.item(x.row(), 1).text())
  922. except ValueError:
  923. # try to convert comma to decimal point. if it's still not working error message and return
  924. try:
  925. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  926. except ValueError:
  927. self.app.inform.emit(_("[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  928. "use a number."))
  929. continue
  930. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  931. iso_dia_list.append(tooldia)
  932. else:
  933. ncc_dia_list.append(tooldia)
  934. else:
  935. self.app.inform.emit(_("[ERROR_NOTCL] No selected tools in Tool Table."))
  936. return
  937. o_name = '%s_ncc' % self.obj_name
  938. select_method = self.reference_radio.get_value()
  939. if select_method == 'itself':
  940. self.bound_obj_name = self.object_combo.currentText()
  941. # Get source object.
  942. try:
  943. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  944. except Exception as e:
  945. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  946. return "Could not retrieve object: %s" % self.obj_name
  947. self.clear_copper(ncc_obj=self.ncc_obj,
  948. ncctooldia=ncc_dia_list,
  949. isotooldia=iso_dia_list,
  950. has_offset=has_offset,
  951. outname=o_name,
  952. overlap=overlap,
  953. connect=connect,
  954. contour=contour,
  955. rest=rest)
  956. elif select_method == 'area':
  957. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the area."))
  958. # use the first tool in the tool table; get the diameter
  959. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  960. # To be called after clicking on the plot.
  961. def on_mouse_release(event):
  962. # do clear area only for left mouse clicks
  963. if event.button == 1:
  964. if self.first_click is False:
  965. self.first_click = True
  966. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  967. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  968. if self.app.grid_status() == True:
  969. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  970. else:
  971. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  972. self.app.delete_selection_shape()
  973. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  974. if self.app.grid_status() == True:
  975. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  976. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  977. x1, y1 = curr_pos[0], curr_pos[1]
  978. pt1 = (x0, y0)
  979. pt2 = (x1, y0)
  980. pt3 = (x1, y1)
  981. pt4 = (x0, y1)
  982. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  983. self.first_click = False
  984. return
  985. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  986. #
  987. # if modifiers == QtCore.Qt.ShiftModifier:
  988. # mod_key = 'Shift'
  989. # elif modifiers == QtCore.Qt.ControlModifier:
  990. # mod_key = 'Control'
  991. # else:
  992. # mod_key = None
  993. #
  994. # if mod_key == self.app.defaults["global_mselect_key"]:
  995. # self.first_click = False
  996. # return
  997. #
  998. # self.sel_rect = cascaded_union(self.sel_rect)
  999. # self.clear_copper(ncc_obj=self.ncc_obj,
  1000. # sel_obj=self.bound_obj,
  1001. # ncctooldia=ncc_dia_list,
  1002. # isotooldia=iso_dia_list,
  1003. # has_offset=has_offset,
  1004. # outname=o_name,
  1005. # overlap=overlap,
  1006. # connect=connect,
  1007. # contour=contour,
  1008. # rest=rest)
  1009. #
  1010. # self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1011. # self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  1012. #
  1013. # self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1014. # self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1015. # self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1016. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  1017. self.first_click = False
  1018. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1019. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  1020. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1021. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1022. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1023. self.sel_rect = cascaded_union(self.sel_rect)
  1024. self.clear_copper(ncc_obj=self.ncc_obj,
  1025. sel_obj=self.bound_obj,
  1026. ncctooldia=ncc_dia_list,
  1027. isotooldia=iso_dia_list,
  1028. has_offset=has_offset,
  1029. outname=o_name,
  1030. overlap=overlap,
  1031. connect=connect,
  1032. contour=contour,
  1033. rest=rest)
  1034. # called on mouse move
  1035. def on_mouse_move(event):
  1036. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  1037. self.app.app_cursor.enabled = False
  1038. if event.button == 2:
  1039. if event.is_dragging is True:
  1040. self.mouse_is_dragging = True
  1041. else:
  1042. self.mouse_is_dragging = False
  1043. if self.app.grid_status() == True:
  1044. self.app.app_cursor.enabled = True
  1045. # Update cursor
  1046. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1047. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1048. symbol='++', edge_color='black', size=20)
  1049. if self.first_click:
  1050. self.app.delete_selection_shape()
  1051. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1052. coords=(curr_pos[0], curr_pos[1]),
  1053. face_alpha=0.0)
  1054. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1055. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1056. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1057. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  1058. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  1059. elif select_method == 'box':
  1060. self.bound_obj_name = self.box_combo.currentText()
  1061. # Get source object.
  1062. try:
  1063. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1064. except Exception as e:
  1065. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.bound_obj_name)
  1066. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1067. self.clear_copper(ncc_obj=self.ncc_obj,
  1068. sel_obj=self.bound_obj,
  1069. ncctooldia=ncc_dia_list,
  1070. isotooldia=iso_dia_list,
  1071. has_offset=has_offset,
  1072. outname=o_name,
  1073. overlap=overlap,
  1074. connect=connect,
  1075. contour=contour,
  1076. rest=rest)
  1077. def clear_copper(self, ncc_obj,
  1078. sel_obj=None,
  1079. ncctooldia=None,
  1080. isotooldia=None,
  1081. margin=None,
  1082. has_offset=None,
  1083. offset=None,
  1084. select_method=None,
  1085. outname=None,
  1086. overlap=None,
  1087. connect=None,
  1088. contour=None,
  1089. order=None,
  1090. method=None,
  1091. rest=None,
  1092. tools_storage=None):
  1093. """
  1094. Clear the excess copper from the entire object.
  1095. :param ncc_obj: ncc cleared object
  1096. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1097. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1098. :param overlap: value by which the paths will overlap
  1099. :param order: if the tools are ordered and how
  1100. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1101. another object
  1102. :param has_offset: True if an offset is needed
  1103. :param offset: distance from the copper features where the copper clearing is stopping
  1104. :param margin: a border around cleared area
  1105. :param outname: name of the resulting object
  1106. :param connect: Connect lines to avoid tool lifts.
  1107. :param contour: Paint around the edges.
  1108. :param method: choice out of 'seed', 'normal', 'lines'
  1109. :param rest: True if to use rest-machining
  1110. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1111. Usage of the different one is related to when this function is called from a TcL command.
  1112. :return:
  1113. """
  1114. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1115. # #####################################################################
  1116. # ####### Read the parameters #########################################
  1117. # #####################################################################
  1118. ncc_method = method if method else self.ncc_method_radio.get_value()
  1119. if margin is not None:
  1120. ncc_margin = margin
  1121. else:
  1122. try:
  1123. ncc_margin = float(self.ncc_margin_entry.get_value())
  1124. except ValueError:
  1125. # try to convert comma to decimal point. if it's still not working error message and return
  1126. try:
  1127. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  1128. except ValueError:
  1129. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1130. "use a number."))
  1131. return
  1132. if select_method is not None:
  1133. ncc_select = select_method
  1134. else:
  1135. ncc_select = self.reference_radio.get_value()
  1136. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  1137. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1138. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1139. order = order if order else self.ncc_order_radio.get_value()
  1140. if tools_storage is not None:
  1141. tools_storage = tools_storage
  1142. else:
  1143. tools_storage = self.ncc_tools
  1144. ncc_offset = 0.0
  1145. if has_offset is True:
  1146. if offset is not None:
  1147. ncc_offset = offset
  1148. else:
  1149. try:
  1150. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1151. except ValueError:
  1152. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1153. "use a number."))
  1154. return
  1155. # ######################################################################################################
  1156. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1157. # ######################################################################################################
  1158. sorted_tools = []
  1159. if ncctooldia is not None:
  1160. try:
  1161. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1162. except AttributeError:
  1163. if not isinstance(ncctooldia, list):
  1164. sorted_tools = [float(ncctooldia)]
  1165. else:
  1166. sorted_tools = ncctooldia
  1167. else:
  1168. for row in range(self.tools_table.rowCount()):
  1169. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1170. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1171. # ##############################################################################################################
  1172. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1173. # ##############################################################################################################
  1174. try:
  1175. if sel_obj is None or sel_obj == 'itself':
  1176. ncc_sel_obj = ncc_obj
  1177. else:
  1178. ncc_sel_obj = sel_obj
  1179. except Exception as e:
  1180. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1181. return 'fail'
  1182. bounding_box = None
  1183. if ncc_select == 'itself':
  1184. geo_n = ncc_sel_obj.solid_geometry
  1185. try:
  1186. if isinstance(geo_n, MultiPolygon):
  1187. env_obj = geo_n.convex_hull
  1188. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1189. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1190. env_obj = cascaded_union(geo_n)
  1191. else:
  1192. env_obj = cascaded_union(geo_n)
  1193. env_obj = env_obj.convex_hull
  1194. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1195. except Exception as e:
  1196. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1197. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1198. return 'fail'
  1199. elif ncc_select == 'area':
  1200. geo_n = cascaded_union(self.sel_rect)
  1201. try:
  1202. __ = iter(geo_n)
  1203. except Exception as e:
  1204. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1205. geo_n = [geo_n]
  1206. geo_buff_list = []
  1207. for poly in geo_n:
  1208. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1209. bounding_box = cascaded_union(geo_buff_list)
  1210. elif ncc_select == 'box':
  1211. geo_n = ncc_sel_obj.solid_geometry
  1212. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1213. try:
  1214. __ = iter(geo_n)
  1215. except Exception as e:
  1216. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1217. geo_n = [geo_n]
  1218. geo_buff_list = []
  1219. for poly in geo_n:
  1220. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1221. bounding_box = cascaded_union(geo_buff_list)
  1222. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1223. geo_n = cascaded_union(geo_n).convex_hull
  1224. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1225. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1226. else:
  1227. self.app.inform.emit(_("[ERROR_NOTCL] The reference object type is not supported."))
  1228. return 'fail'
  1229. # ########################################################################################################
  1230. # set the name for the future Geometry object
  1231. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1232. # ########################################################################################################
  1233. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1234. if rest_machining_choice is True:
  1235. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1236. else:
  1237. name = outname if outname is not None else self.obj_name + "_ncc"
  1238. # ##########################################################################################
  1239. # Initializes the new geometry object ######################################################
  1240. # ##########################################################################################
  1241. def gen_clear_area(geo_obj, app_obj):
  1242. assert isinstance(geo_obj, FlatCAMGeometry), \
  1243. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1244. if order == 'fwd':
  1245. sorted_tools.sort(reverse=False)
  1246. elif order == 'rev':
  1247. sorted_tools.sort(reverse=True)
  1248. else:
  1249. pass
  1250. cleared_geo = []
  1251. # Already cleared area
  1252. cleared = MultiPolygon()
  1253. # flag for polygons not cleared
  1254. app_obj.poly_not_cleared = False
  1255. # Generate area for each tool
  1256. offset = sum(sorted_tools)
  1257. current_uid = int(1)
  1258. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1259. # ###################################################################################################
  1260. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1261. # ###################################################################################################
  1262. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1263. sol_geo = ncc_obj.solid_geometry
  1264. if has_offset is True:
  1265. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1266. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1267. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1268. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1269. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1270. isolated_geo = []
  1271. self.solid_geometry = ncc_obj.solid_geometry
  1272. # if milling type is climb then the move is counter-clockwise around features
  1273. milling_type = self.milling_type_radio.get_value()
  1274. for tool_iso in isotooldia:
  1275. new_geometry = []
  1276. if milling_type == 'cl':
  1277. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1278. else:
  1279. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1280. if isolated_geo == 'fail':
  1281. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1282. else:
  1283. try:
  1284. for geo_elem in isolated_geo:
  1285. if isinstance(geo_elem, Polygon):
  1286. for ring in self.poly2rings(geo_elem):
  1287. new_geo = ring.intersection(bounding_box)
  1288. if new_geo and not new_geo.is_empty:
  1289. new_geometry.append(new_geo)
  1290. elif isinstance(geo_elem, MultiPolygon):
  1291. for poly in geo_elem:
  1292. for ring in self.poly2rings(poly):
  1293. new_geo = ring.intersection(bounding_box)
  1294. if new_geo and not new_geo.is_empty:
  1295. new_geometry.append(new_geo)
  1296. elif isinstance(geo_elem, LineString):
  1297. new_geo = geo_elem.intersection(bounding_box)
  1298. if new_geo:
  1299. if not new_geo.is_empty:
  1300. new_geometry.append(new_geo)
  1301. elif isinstance(geo_elem, MultiLineString):
  1302. for line_elem in geo_elem:
  1303. new_geo = line_elem.intersection(bounding_box)
  1304. if new_geo and not new_geo.is_empty:
  1305. new_geometry.append(new_geo)
  1306. except TypeError:
  1307. if isinstance(isolated_geo, Polygon):
  1308. for ring in self.poly2rings(isolated_geo):
  1309. new_geo = ring.intersection(bounding_box)
  1310. if new_geo:
  1311. if not new_geo.is_empty:
  1312. new_geometry.append(new_geo)
  1313. elif isinstance(isolated_geo, LineString):
  1314. new_geo = isolated_geo.intersection(bounding_box)
  1315. if new_geo and not new_geo.is_empty:
  1316. new_geometry.append(new_geo)
  1317. elif isinstance(isolated_geo, MultiLineString):
  1318. for line_elem in isolated_geo:
  1319. new_geo = line_elem.intersection(bounding_box)
  1320. if new_geo and not new_geo.is_empty:
  1321. new_geometry.append(new_geo)
  1322. for k, v in tools_storage.items():
  1323. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1324. current_uid = int(k)
  1325. # add the solid_geometry to the current too in self.paint_tools dictionary
  1326. # and then reset the temporary list that stored that solid_geometry
  1327. v['solid_geometry'] = deepcopy(new_geometry)
  1328. v['data']['name'] = name
  1329. break
  1330. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1331. sol_geo = cascaded_union(isolated_geo)
  1332. if has_offset is True:
  1333. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1334. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1335. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1336. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1337. elif isinstance(ncc_obj, FlatCAMGeometry):
  1338. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1339. if has_offset is True:
  1340. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1341. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1342. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1343. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1344. else:
  1345. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1346. return
  1347. if empty.is_empty:
  1348. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1349. return 'fail'
  1350. if type(empty) is Polygon:
  1351. empty = MultiPolygon([empty])
  1352. for tool in sorted_tools:
  1353. app_obj.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1354. cleared_geo[:] = []
  1355. # Get remaining tools offset
  1356. offset -= (tool - 1e-12)
  1357. # Area to clear
  1358. area = empty.buffer(-offset)
  1359. try:
  1360. area = area.difference(cleared)
  1361. except Exception as e:
  1362. continue
  1363. # Transform area to MultiPolygon
  1364. if type(area) is Polygon:
  1365. area = MultiPolygon([area])
  1366. if area.geoms:
  1367. if len(area.geoms) > 0:
  1368. for p in area.geoms:
  1369. try:
  1370. if ncc_method == 'standard':
  1371. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1372. overlap=overlap, contour=contour, connect=connect)
  1373. elif ncc_method == 'seed':
  1374. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1375. overlap=overlap, contour=contour, connect=connect)
  1376. else:
  1377. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1378. overlap=overlap, contour=contour, connect=connect)
  1379. if cp:
  1380. cleared_geo += list(cp.get_objects())
  1381. except Exception as e:
  1382. log.warning("Polygon can not be cleared. %s" % str(e))
  1383. app_obj.poly_not_cleared = True
  1384. continue
  1385. # check if there is a geometry at all in the cleared geometry
  1386. if cleared_geo:
  1387. # Overall cleared area
  1388. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1389. tool / 1.999999)
  1390. # clean-up cleared geo
  1391. cleared = cleared.buffer(0)
  1392. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1393. # solid_geometry
  1394. for k, v in tools_storage.items():
  1395. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1396. current_uid = int(k)
  1397. # add the solid_geometry to the current too in self.paint_tools dictionary
  1398. # and then reset the temporary list that stored that solid_geometry
  1399. v['solid_geometry'] = deepcopy(cleared_geo)
  1400. v['data']['name'] = name
  1401. break
  1402. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1403. else:
  1404. log.debug("There are no geometries in the cleared polygon.")
  1405. # delete tools with empty geometry
  1406. keys_to_delete = []
  1407. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1408. for uid in tools_storage:
  1409. # if the solid_geometry (type=list) is empty
  1410. if not tools_storage[uid]['solid_geometry']:
  1411. keys_to_delete.append(uid)
  1412. # actual delete of keys from the tools_storage dict
  1413. for k in keys_to_delete:
  1414. tools_storage.pop(k, None)
  1415. geo_obj.options["cnctooldia"] = str(tool)
  1416. geo_obj.multigeo = True
  1417. geo_obj.tools.clear()
  1418. geo_obj.tools = dict(tools_storage)
  1419. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1420. has_solid_geo = 0
  1421. for tooluid in geo_obj.tools:
  1422. if geo_obj.tools[tooluid]['solid_geometry']:
  1423. has_solid_geo += 1
  1424. if has_solid_geo == 0:
  1425. app_obj.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1426. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1427. "Change the painting parameters and try again."))
  1428. return
  1429. # Experimental...
  1430. # print("Indexing...", end=' ')
  1431. # geo_obj.make_index()
  1432. self.app.inform.emit(_("[success] Non-Copper clear all done."))
  1433. # ###########################################################################################
  1434. # Initializes the new geometry object for the case of the rest-machining ####################
  1435. # ###########################################################################################
  1436. def gen_clear_area_rest(geo_obj, app_obj):
  1437. assert isinstance(geo_obj, FlatCAMGeometry), \
  1438. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1439. sorted_tools.sort(reverse=True)
  1440. cleared_geo = []
  1441. cleared_by_last_tool = []
  1442. rest_geo = []
  1443. current_uid = 1
  1444. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1445. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1446. app_obj.poly_not_cleared = True
  1447. # ###################################################################################################
  1448. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1449. # ###################################################################################################
  1450. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1451. sol_geo = ncc_obj.solid_geometry
  1452. if has_offset is True:
  1453. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1454. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1455. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1456. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1457. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1458. isolated_geo = []
  1459. self.solid_geometry = ncc_obj.solid_geometry
  1460. # if milling type is climb then the move is counter-clockwise around features
  1461. milling_type = self.milling_type_radio.get_value()
  1462. for tool_iso in isotooldia:
  1463. new_geometry = []
  1464. if milling_type == 'cl':
  1465. isolated_geo = self.generate_envelope(tool_iso, 1)
  1466. else:
  1467. isolated_geo = self.generate_envelope(tool_iso, 0)
  1468. if isolated_geo == 'fail':
  1469. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1470. else:
  1471. try:
  1472. for geo_elem in isolated_geo:
  1473. if isinstance(geo_elem, Polygon):
  1474. for ring in self.poly2rings(geo_elem):
  1475. new_geo = ring.intersection(bounding_box)
  1476. if new_geo and not new_geo.is_empty:
  1477. new_geometry.append(new_geo)
  1478. elif isinstance(geo_elem, MultiPolygon):
  1479. for poly in geo_elem:
  1480. for ring in self.poly2rings(poly):
  1481. new_geo = ring.intersection(bounding_box)
  1482. if new_geo and not new_geo.is_empty:
  1483. new_geometry.append(new_geo)
  1484. elif isinstance(geo_elem, LineString):
  1485. new_geo = geo_elem.intersection(bounding_box)
  1486. if new_geo:
  1487. if not new_geo.is_empty:
  1488. new_geometry.append(new_geo)
  1489. elif isinstance(geo_elem, MultiLineString):
  1490. for line_elem in geo_elem:
  1491. new_geo = line_elem.intersection(bounding_box)
  1492. if new_geo and not new_geo.is_empty:
  1493. new_geometry.append(new_geo)
  1494. except TypeError:
  1495. if isinstance(isolated_geo, Polygon):
  1496. for ring in self.poly2rings(isolated_geo):
  1497. new_geo = ring.intersection(bounding_box)
  1498. if new_geo:
  1499. if not new_geo.is_empty:
  1500. new_geometry.append(new_geo)
  1501. elif isinstance(isolated_geo, LineString):
  1502. new_geo = isolated_geo.intersection(bounding_box)
  1503. if new_geo and not new_geo.is_empty:
  1504. new_geometry.append(new_geo)
  1505. elif isinstance(isolated_geo, MultiLineString):
  1506. for line_elem in isolated_geo:
  1507. new_geo = line_elem.intersection(bounding_box)
  1508. if new_geo and not new_geo.is_empty:
  1509. new_geometry.append(new_geo)
  1510. for k, v in tools_storage.items():
  1511. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1512. current_uid = int(k)
  1513. # add the solid_geometry to the current too in self.paint_tools dictionary
  1514. # and then reset the temporary list that stored that solid_geometry
  1515. v['solid_geometry'] = deepcopy(new_geometry)
  1516. v['data']['name'] = name
  1517. break
  1518. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1519. sol_geo = cascaded_union(isolated_geo)
  1520. if has_offset is True:
  1521. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1522. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1523. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1524. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1525. elif isinstance(ncc_obj, FlatCAMGeometry):
  1526. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1527. if has_offset is True:
  1528. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1529. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1530. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1531. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1532. else:
  1533. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1534. return
  1535. if empty.is_empty:
  1536. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1537. return 'fail'
  1538. if type(empty) is Polygon:
  1539. empty = MultiPolygon([empty])
  1540. area = empty.buffer(0)
  1541. # Generate area for each tool
  1542. while sorted_tools:
  1543. tool = sorted_tools.pop(0)
  1544. app_obj.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1545. tool_used = tool - 1e-12
  1546. cleared_geo[:] = []
  1547. # Area to clear
  1548. for poly in cleared_by_last_tool:
  1549. try:
  1550. area = area.difference(poly)
  1551. except Exception as e:
  1552. pass
  1553. cleared_by_last_tool[:] = []
  1554. # Transform area to MultiPolygon
  1555. if type(area) is Polygon:
  1556. area = MultiPolygon([area])
  1557. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1558. # and rest_geo it's a list
  1559. allparts = [p.buffer(0) for p in area.geoms]
  1560. allparts += deepcopy(rest_geo)
  1561. rest_geo[:] = []
  1562. area = MultiPolygon(deepcopy(allparts))
  1563. allparts[:] = []
  1564. if area.geoms:
  1565. if len(area.geoms) > 0:
  1566. for p in area.geoms:
  1567. try:
  1568. if ncc_method == 'standard':
  1569. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1570. overlap=overlap, contour=contour, connect=connect)
  1571. elif ncc_method == 'seed':
  1572. cp = self.clear_polygon2(p, tool_used,
  1573. self.app.defaults["gerber_circle_steps"],
  1574. overlap=overlap, contour=contour, connect=connect)
  1575. else:
  1576. cp = self.clear_polygon3(p, tool_used,
  1577. self.app.defaults["gerber_circle_steps"],
  1578. overlap=overlap, contour=contour, connect=connect)
  1579. cleared_geo.append(list(cp.get_objects()))
  1580. except:
  1581. log.warning("Polygon can't be cleared.")
  1582. # this polygon should be added to a list and then try clear it with a smaller tool
  1583. rest_geo.append(p)
  1584. # check if there is a geometry at all in the cleared geometry
  1585. if cleared_geo:
  1586. # Overall cleared area
  1587. cleared_area = list(self.flatten_list(cleared_geo))
  1588. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1589. # for p in cleared_area])
  1590. # here we store the poly's already processed in the original geometry by the current tool
  1591. # into cleared_by_last_tool list
  1592. # this will be sustracted from the original geometry_to_be_cleared and make data for
  1593. # the next tool
  1594. buffer_value = tool_used / 2
  1595. for p in cleared_area:
  1596. poly = p.buffer(buffer_value)
  1597. cleared_by_last_tool.append(poly)
  1598. # find the tooluid associated with the current tool_dia so we know
  1599. # where to add the tool solid_geometry
  1600. for k, v in tools_storage.items():
  1601. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1602. current_uid = int(k)
  1603. # add the solid_geometry to the current too in self.paint_tools dictionary
  1604. # and then reset the temporary list that stored that solid_geometry
  1605. v['solid_geometry'] = deepcopy(cleared_area)
  1606. v['data']['name'] = name
  1607. cleared_area[:] = []
  1608. break
  1609. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1610. else:
  1611. log.debug("There are no geometries in the cleared polygon.")
  1612. geo_obj.multigeo = True
  1613. geo_obj.options["cnctooldia"] = str(tool)
  1614. # check to see if geo_obj.tools is empty
  1615. # it will be updated only if there is a solid_geometry for tools
  1616. if geo_obj.tools:
  1617. return
  1618. else:
  1619. # I will use this variable for this purpose although it was meant for something else
  1620. # signal that we have no geo in the object therefore don't create it
  1621. app_obj.poly_not_cleared = False
  1622. return "fail"
  1623. # ###########################################################################################
  1624. # Create the Job function and send it to the worker to be processed in another thread #######
  1625. # ###########################################################################################
  1626. def job_thread(app_obj):
  1627. try:
  1628. if rest_machining_choice is True:
  1629. app_obj.new_object("geometry", name, gen_clear_area_rest)
  1630. else:
  1631. app_obj.new_object("geometry", name, gen_clear_area)
  1632. except Exception as e:
  1633. proc.done()
  1634. traceback.print_stack()
  1635. return
  1636. proc.done()
  1637. # focus on Selected Tab
  1638. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1639. # Promise object with the new name
  1640. self.app.collection.promise(name)
  1641. # Background
  1642. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1643. # def on_ncc(self):
  1644. #
  1645. # # Prepare non-copper polygons
  1646. # if self.reference_radio.get_value() == 'area':
  1647. # geo_n = self.sel_rect
  1648. #
  1649. # geo_buff_list = []
  1650. # for poly in geo_n:
  1651. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1652. # bounding_box = cascaded_union(geo_buff_list)
  1653. # else:
  1654. # geo_n = self.bound_obj.solid_geometry
  1655. #
  1656. # try:
  1657. # if isinstance(geo_n, MultiPolygon):
  1658. # env_obj = geo_n.convex_hull
  1659. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1660. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1661. # env_obj = cascaded_union(geo_n)
  1662. # else:
  1663. # env_obj = cascaded_union(geo_n)
  1664. # env_obj = env_obj.convex_hull
  1665. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1666. # except Exception as e:
  1667. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1668. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1669. # return
  1670. #
  1671. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1672. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1673. # if self.ncc_choice_offset_cb.isChecked():
  1674. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1675. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1676. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1677. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1678. # else:
  1679. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1680. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1681. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1682. # if self.ncc_choice_offset_cb.isChecked():
  1683. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1684. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1685. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1686. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1687. # else:
  1688. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1689. # else:
  1690. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1691. # return
  1692. #
  1693. # if type(empty) is Polygon:
  1694. # empty = MultiPolygon([empty])
  1695. #
  1696. # if empty.is_empty:
  1697. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1698. # return
  1699. #
  1700. # # clear non copper using standard algorithm
  1701. # if clearing_method is False:
  1702. # self.clear_non_copper(
  1703. # empty=empty,
  1704. # over=over,
  1705. # pol_method=pol_method,
  1706. # connect=connect,
  1707. # contour=contour
  1708. # )
  1709. # # clear non copper using rest machining algorithm
  1710. # else:
  1711. # self.clear_non_copper_rest(
  1712. # empty=empty,
  1713. # over=over,
  1714. # pol_method=pol_method,
  1715. # connect=connect,
  1716. # contour=contour
  1717. # )
  1718. #
  1719. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1720. #
  1721. # name = outname if outname else self.obj_name + "_ncc"
  1722. #
  1723. # # Sort tools in descending order
  1724. # sorted_tools = []
  1725. # for k, v in self.ncc_tools.items():
  1726. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1727. #
  1728. # order = self.ncc_order_radio.get_value()
  1729. # if order == 'fwd':
  1730. # sorted_tools.sort(reverse=False)
  1731. # elif order == 'rev':
  1732. # sorted_tools.sort(reverse=True)
  1733. # else:
  1734. # pass
  1735. #
  1736. # # Do job in background
  1737. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1738. #
  1739. # def initialize(geo_obj, app_obj):
  1740. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1741. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1742. #
  1743. # cleared_geo = []
  1744. # # Already cleared area
  1745. # cleared = MultiPolygon()
  1746. #
  1747. # # flag for polygons not cleared
  1748. # app_obj.poly_not_cleared = False
  1749. #
  1750. # # Generate area for each tool
  1751. # offset = sum(sorted_tools)
  1752. # current_uid = int(1)
  1753. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1754. #
  1755. # for tool in sorted_tools:
  1756. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1757. # cleared_geo[:] = []
  1758. #
  1759. # # Get remaining tools offset
  1760. # offset -= (tool - 1e-12)
  1761. #
  1762. # # Area to clear
  1763. # area = empty.buffer(-offset)
  1764. # try:
  1765. # area = area.difference(cleared)
  1766. # except Exception as e:
  1767. # continue
  1768. #
  1769. # # Transform area to MultiPolygon
  1770. # if type(area) is Polygon:
  1771. # area = MultiPolygon([area])
  1772. #
  1773. # if area.geoms:
  1774. # if len(area.geoms) > 0:
  1775. # for p in area.geoms:
  1776. # try:
  1777. # if pol_method == 'standard':
  1778. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1779. # overlap=over, contour=contour, connect=connect)
  1780. # elif pol_method == 'seed':
  1781. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1782. # overlap=over, contour=contour, connect=connect)
  1783. # else:
  1784. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1785. # overlap=over, contour=contour, connect=connect)
  1786. # if cp:
  1787. # cleared_geo += list(cp.get_objects())
  1788. # except Exception as e:
  1789. # log.warning("Polygon can not be cleared. %s" % str(e))
  1790. # app_obj.poly_not_cleared = True
  1791. # continue
  1792. #
  1793. # # check if there is a geometry at all in the cleared geometry
  1794. # if cleared_geo:
  1795. # # Overall cleared area
  1796. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  1797. # tool / 1.999999)
  1798. #
  1799. # # clean-up cleared geo
  1800. # cleared = cleared.buffer(0)
  1801. #
  1802. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  1803. # # solid_geometry
  1804. # for k, v in self.ncc_tools.items():
  1805. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1806. # current_uid = int(k)
  1807. #
  1808. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1809. # # and then reset the temporary list that stored that solid_geometry
  1810. # v['solid_geometry'] = deepcopy(cleared_geo)
  1811. # v['data']['name'] = name
  1812. # break
  1813. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1814. # else:
  1815. # log.debug("There are no geometries in the cleared polygon.")
  1816. #
  1817. # geo_obj.options["cnctooldia"] = str(tool)
  1818. # geo_obj.multigeo = True
  1819. #
  1820. # def job_thread(app_obj):
  1821. # try:
  1822. # app_obj.new_object("geometry", name, initialize)
  1823. # except Exception as e:
  1824. # proc.done()
  1825. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  1826. # return
  1827. # proc.done()
  1828. #
  1829. # if app_obj.poly_not_cleared is False:
  1830. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  1831. # else:
  1832. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  1833. # 'Check the result.'))
  1834. # # reset the variable for next use
  1835. # app_obj.poly_not_cleared = False
  1836. #
  1837. # # focus on Selected Tab
  1838. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1839. #
  1840. # # Promise object with the new name
  1841. # self.app.collection.promise(name)
  1842. #
  1843. # # Background
  1844. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1845. #
  1846. # # clear copper with 'rest-machining' algorithm
  1847. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1848. #
  1849. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1850. #
  1851. # # Sort tools in descending order
  1852. # sorted_tools = []
  1853. # for k, v in self.ncc_tools.items():
  1854. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1855. # sorted_tools.sort(reverse=True)
  1856. #
  1857. # # Do job in background
  1858. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1859. #
  1860. # def initialize_rm(geo_obj, app_obj):
  1861. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1862. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1863. #
  1864. # cleared_geo = []
  1865. # cleared_by_last_tool = []
  1866. # rest_geo = []
  1867. # current_uid = 1
  1868. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1869. #
  1870. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1871. # app_obj.poly_not_cleared = True
  1872. #
  1873. # area = empty.buffer(0)
  1874. # # Generate area for each tool
  1875. # while sorted_tools:
  1876. # tool = sorted_tools.pop(0)
  1877. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1878. #
  1879. # tool_used = tool - 1e-12
  1880. # cleared_geo[:] = []
  1881. #
  1882. # # Area to clear
  1883. # for poly in cleared_by_last_tool:
  1884. # try:
  1885. # area = area.difference(poly)
  1886. # except Exception as e:
  1887. # pass
  1888. # cleared_by_last_tool[:] = []
  1889. #
  1890. # # Transform area to MultiPolygon
  1891. # if type(area) is Polygon:
  1892. # area = MultiPolygon([area])
  1893. #
  1894. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1895. # # and rest_geo it's a list
  1896. # allparts = [p.buffer(0) for p in area.geoms]
  1897. # allparts += deepcopy(rest_geo)
  1898. # rest_geo[:] = []
  1899. # area = MultiPolygon(deepcopy(allparts))
  1900. # allparts[:] = []
  1901. #
  1902. # if area.geoms:
  1903. # if len(area.geoms) > 0:
  1904. # for p in area.geoms:
  1905. # try:
  1906. # if pol_method == 'standard':
  1907. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1908. # overlap=over, contour=contour, connect=connect)
  1909. # elif pol_method == 'seed':
  1910. # cp = self.clear_polygon2(p, tool_used,
  1911. # self.app.defaults["gerber_circle_steps"],
  1912. # overlap=over, contour=contour, connect=connect)
  1913. # else:
  1914. # cp = self.clear_polygon3(p, tool_used,
  1915. # self.app.defaults["gerber_circle_steps"],
  1916. # overlap=over, contour=contour, connect=connect)
  1917. # cleared_geo.append(list(cp.get_objects()))
  1918. # except:
  1919. # log.warning("Polygon can't be cleared.")
  1920. # # this polygon should be added to a list and then try clear it with a smaller tool
  1921. # rest_geo.append(p)
  1922. #
  1923. # # check if there is a geometry at all in the cleared geometry
  1924. # if cleared_geo:
  1925. # # Overall cleared area
  1926. # cleared_area = list(self.flatten_list(cleared_geo))
  1927. #
  1928. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1929. # # for p in cleared_area])
  1930. #
  1931. # # here we store the poly's already processed in the original geometry by the current tool
  1932. # # into cleared_by_last_tool list
  1933. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  1934. # # the next tool
  1935. # buffer_value = tool_used / 2
  1936. # for p in cleared_area:
  1937. # poly = p.buffer(buffer_value)
  1938. # cleared_by_last_tool.append(poly)
  1939. #
  1940. # # find the tooluid associated with the current tool_dia so we know
  1941. # # where to add the tool solid_geometry
  1942. # for k, v in self.ncc_tools.items():
  1943. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1944. # current_uid = int(k)
  1945. #
  1946. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1947. # # and then reset the temporary list that stored that solid_geometry
  1948. # v['solid_geometry'] = deepcopy(cleared_area)
  1949. # v['data']['name'] = name
  1950. # cleared_area[:] = []
  1951. # break
  1952. #
  1953. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1954. # else:
  1955. # log.debug("There are no geometries in the cleared polygon.")
  1956. #
  1957. # geo_obj.multigeo = True
  1958. # geo_obj.options["cnctooldia"] = str(tool)
  1959. #
  1960. # # check to see if geo_obj.tools is empty
  1961. # # it will be updated only if there is a solid_geometry for tools
  1962. # if geo_obj.tools:
  1963. # return
  1964. # else:
  1965. # # I will use this variable for this purpose although it was meant for something else
  1966. # # signal that we have no geo in the object therefore don't create it
  1967. # app_obj.poly_not_cleared = False
  1968. # return "fail"
  1969. #
  1970. # def job_thread(app_obj):
  1971. # try:
  1972. # app_obj.new_object("geometry", name, initialize_rm)
  1973. # except Exception as e:
  1974. # proc.done()
  1975. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  1976. # return
  1977. #
  1978. # if app_obj.poly_not_cleared is True:
  1979. # app_obj.inform.emit('[success] NCC Tool finished.')
  1980. # # focus on Selected Tab
  1981. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1982. # else:
  1983. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  1984. # 'with current settings.'))
  1985. # # focus on Project Tab
  1986. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1987. # proc.done()
  1988. # # reset the variable for next use
  1989. # app_obj.poly_not_cleared = False
  1990. #
  1991. # # Promise object with the new name
  1992. # self.app.collection.promise(name)
  1993. #
  1994. # # Background
  1995. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1996. @staticmethod
  1997. def get_ncc_empty_area(target, boundary=None):
  1998. """
  1999. Returns the complement of target geometry within
  2000. the given boundary polygon. If not specified, it defaults to
  2001. the rectangular bounding box of target geometry.
  2002. """
  2003. if boundary is None:
  2004. boundary = target.envelope
  2005. return boundary.difference(target)
  2006. def reset_fields(self):
  2007. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2008. def reset_usage(self):
  2009. self.obj_name = ""
  2010. self.ncc_obj = None
  2011. self.bound_obj = None
  2012. self.first_click = False
  2013. self.cursor_pos = None
  2014. self.mouse_is_dragging = False
  2015. self.sel_rect = []
  2016. @staticmethod
  2017. def poly2rings(poly):
  2018. return [poly.exterior] + [interior for interior in poly.interiors]
  2019. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2020. # isolation_geometry produces an envelope that is going on the left of the geometry
  2021. # (the copper features). To leave the least amount of burrs on the features
  2022. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2023. # the first pass is the one cutting all of the features, so it needs to be reversed
  2024. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2025. # to cut on the right side of the left over copper i.e on the left side of the features.
  2026. try:
  2027. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2028. except Exception as e:
  2029. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2030. return 'fail'
  2031. if invert:
  2032. try:
  2033. try:
  2034. pl = []
  2035. for p in geom:
  2036. if p is not None:
  2037. if isinstance(p, Polygon):
  2038. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2039. elif isinstance(p, LinearRing):
  2040. pl.append(Polygon(p.coords[::-1]))
  2041. geom = MultiPolygon(pl)
  2042. except TypeError:
  2043. if isinstance(geom, Polygon) and geom is not None:
  2044. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2045. elif isinstance(geom, LinearRing) and geom is not None:
  2046. geom = Polygon(geom.coords[::-1])
  2047. else:
  2048. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2049. type(geom))
  2050. except Exception as e:
  2051. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2052. return 'fail'
  2053. return geom