ToolNonCopperClear.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330
  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. 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. modifiers = QtWidgets.QApplication.keyboardModifiers()
  984. if modifiers == QtCore.Qt.ShiftModifier:
  985. mod_key = 'Shift'
  986. elif modifiers == QtCore.Qt.ControlModifier:
  987. mod_key = 'Control'
  988. else:
  989. mod_key = None
  990. if mod_key == self.app.defaults["global_mselect_key"]:
  991. self.first_click = False
  992. return
  993. self.sel_rect = cascaded_union(self.sel_rect)
  994. self.clear_copper(ncc_obj=self.ncc_obj,
  995. sel_obj=self.bound_obj,
  996. ncctooldia=ncc_dia_list,
  997. isotooldia=iso_dia_list,
  998. has_offset=has_offset,
  999. outname=o_name,
  1000. overlap=overlap,
  1001. connect=connect,
  1002. contour=contour,
  1003. rest=rest)
  1004. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1005. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  1006. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1007. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1008. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1009. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  1010. self.first_click = False
  1011. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1012. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  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. self.sel_rect = cascaded_union(self.sel_rect)
  1017. self.clear_copper(ncc_obj=self.ncc_obj,
  1018. sel_obj=self.bound_obj,
  1019. ncctooldia=ncc_dia_list,
  1020. isotooldia=iso_dia_list,
  1021. has_offset=has_offset,
  1022. outname=o_name,
  1023. overlap=overlap,
  1024. connect=connect,
  1025. contour=contour,
  1026. rest=rest)
  1027. # called on mouse move
  1028. def on_mouse_move(event):
  1029. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  1030. self.app.app_cursor.enabled = False
  1031. if event.button == 2:
  1032. if event.is_dragging is True:
  1033. self.mouse_is_dragging = True
  1034. else:
  1035. self.mouse_is_dragging = False
  1036. if self.app.grid_status() == True:
  1037. self.app.app_cursor.enabled = True
  1038. # Update cursor
  1039. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1040. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1041. symbol='++', edge_color='black', size=20)
  1042. if self.first_click:
  1043. self.app.delete_selection_shape()
  1044. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1045. coords=(curr_pos[0], curr_pos[1]),
  1046. face_alpha=0.0)
  1047. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1048. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1049. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1050. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  1051. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  1052. elif select_method == 'box':
  1053. self.bound_obj_name = self.box_combo.currentText()
  1054. # Get source object.
  1055. try:
  1056. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1057. except Exception as e:
  1058. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.bound_obj_name)
  1059. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1060. self.clear_copper(ncc_obj=self.ncc_obj,
  1061. sel_obj=self.bound_obj,
  1062. ncctooldia=ncc_dia_list,
  1063. isotooldia=iso_dia_list,
  1064. has_offset=has_offset,
  1065. outname=o_name,
  1066. overlap=overlap,
  1067. connect=connect,
  1068. contour=contour,
  1069. rest=rest)
  1070. def clear_copper(self, ncc_obj,
  1071. sel_obj=None,
  1072. ncctooldia=None,
  1073. isotooldia=None,
  1074. margin=None,
  1075. has_offset=None,
  1076. offset=None,
  1077. select_method=None,
  1078. outname=None,
  1079. overlap=None,
  1080. connect=None,
  1081. contour=None,
  1082. order=None,
  1083. method=None,
  1084. rest=None,
  1085. tools_storage=None):
  1086. """
  1087. Clear the excess copper from the entire object.
  1088. :param ncc_obj: ncc cleared object
  1089. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1090. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1091. :param overlap: value by which the paths will overlap
  1092. :param order: if the tools are ordered and how
  1093. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1094. another object
  1095. :param has_offset: True if an offset is needed
  1096. :param offset: distance from the copper features where the copper clearing is stopping
  1097. :param margin: a border around cleared area
  1098. :param outname: name of the resulting object
  1099. :param connect: Connect lines to avoid tool lifts.
  1100. :param contour: Paint around the edges.
  1101. :param method: choice out of 'seed', 'normal', 'lines'
  1102. :param rest: True if to use rest-machining
  1103. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1104. Usage of the different one is related to when this function is called from a TcL command.
  1105. :return:
  1106. """
  1107. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1108. # #####################################################################
  1109. # ####### Read the parameters #########################################
  1110. # #####################################################################
  1111. ncc_method = method if method else self.ncc_method_radio.get_value()
  1112. if margin is not None:
  1113. ncc_margin = margin
  1114. else:
  1115. try:
  1116. ncc_margin = float(self.ncc_margin_entry.get_value())
  1117. except ValueError:
  1118. # try to convert comma to decimal point. if it's still not working error message and return
  1119. try:
  1120. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  1121. except ValueError:
  1122. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1123. "use a number."))
  1124. return
  1125. if select_method is not None:
  1126. ncc_select = select_method
  1127. else:
  1128. ncc_select = self.reference_radio.get_value()
  1129. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  1130. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1131. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1132. order = order if order else self.ncc_order_radio.get_value()
  1133. if tools_storage is not None:
  1134. tools_storage = tools_storage
  1135. else:
  1136. tools_storage = self.ncc_tools
  1137. ncc_offset = 0.0
  1138. if has_offset is True:
  1139. if offset is not None:
  1140. ncc_offset = offset
  1141. else:
  1142. try:
  1143. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1144. except ValueError:
  1145. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1146. "use a number."))
  1147. return
  1148. # ######################################################################################################
  1149. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1150. # ######################################################################################################
  1151. sorted_tools = []
  1152. if ncctooldia is not None:
  1153. try:
  1154. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1155. except AttributeError:
  1156. if not isinstance(ncctooldia, list):
  1157. sorted_tools = [float(ncctooldia)]
  1158. else:
  1159. sorted_tools = ncctooldia
  1160. else:
  1161. for row in range(self.tools_table.rowCount()):
  1162. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1163. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1164. # ##############################################################################################################
  1165. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1166. # ##############################################################################################################
  1167. try:
  1168. if sel_obj is None or sel_obj == 'itself':
  1169. ncc_sel_obj = ncc_obj
  1170. else:
  1171. ncc_sel_obj = sel_obj
  1172. except Exception as e:
  1173. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1174. return 'fail'
  1175. bounding_box = None
  1176. if ncc_select == 'itself':
  1177. geo_n = ncc_sel_obj.solid_geometry
  1178. try:
  1179. if isinstance(geo_n, MultiPolygon):
  1180. env_obj = geo_n.convex_hull
  1181. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1182. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1183. env_obj = cascaded_union(geo_n)
  1184. else:
  1185. env_obj = cascaded_union(geo_n)
  1186. env_obj = env_obj.convex_hull
  1187. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1188. except Exception as e:
  1189. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1190. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1191. return 'fail'
  1192. elif ncc_select == 'area':
  1193. geo_n = cascaded_union(self.sel_rect)
  1194. try:
  1195. __ = iter(geo_n)
  1196. except Exception as e:
  1197. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1198. geo_n = [geo_n]
  1199. geo_buff_list = []
  1200. for poly in geo_n:
  1201. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1202. bounding_box = cascaded_union(geo_buff_list)
  1203. elif ncc_select == 'box':
  1204. geo_n = ncc_sel_obj.solid_geometry
  1205. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1206. try:
  1207. __ = iter(geo_n)
  1208. except Exception as e:
  1209. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1210. geo_n = [geo_n]
  1211. geo_buff_list = []
  1212. for poly in geo_n:
  1213. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1214. bounding_box = cascaded_union(geo_buff_list)
  1215. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1216. geo_n = cascaded_union(geo_n).convex_hull
  1217. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1218. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1219. else:
  1220. self.app.inform.emit(_("[ERROR_NOTCL] The reference object type is not supported."))
  1221. return 'fail'
  1222. # ########################################################################################################
  1223. # set the name for the future Geometry object
  1224. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1225. # ########################################################################################################
  1226. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1227. if rest_machining_choice is True:
  1228. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1229. else:
  1230. name = outname if outname is not None else self.obj_name + "_ncc"
  1231. # ##########################################################################################
  1232. # Initializes the new geometry object ######################################################
  1233. # ##########################################################################################
  1234. def gen_clear_area(geo_obj, app_obj):
  1235. assert isinstance(geo_obj, FlatCAMGeometry), \
  1236. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1237. if order == 'fwd':
  1238. sorted_tools.sort(reverse=False)
  1239. elif order == 'rev':
  1240. sorted_tools.sort(reverse=True)
  1241. else:
  1242. pass
  1243. cleared_geo = []
  1244. # Already cleared area
  1245. cleared = MultiPolygon()
  1246. # flag for polygons not cleared
  1247. app_obj.poly_not_cleared = False
  1248. # Generate area for each tool
  1249. offset = sum(sorted_tools)
  1250. current_uid = int(1)
  1251. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1252. # ###################################################################################################
  1253. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1254. # ###################################################################################################
  1255. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1256. sol_geo = ncc_obj.solid_geometry
  1257. if has_offset is True:
  1258. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1259. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1260. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1261. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1262. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1263. isolated_geo = []
  1264. self.solid_geometry = ncc_obj.solid_geometry
  1265. # if milling type is climb then the move is counter-clockwise around features
  1266. milling_type = self.milling_type_radio.get_value()
  1267. for tool_iso in isotooldia:
  1268. new_geometry = []
  1269. if milling_type == 'cl':
  1270. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1271. else:
  1272. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1273. if isolated_geo == 'fail':
  1274. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1275. else:
  1276. try:
  1277. for geo_elem in isolated_geo:
  1278. if isinstance(geo_elem, Polygon):
  1279. for ring in self.poly2rings(geo_elem):
  1280. new_geo = ring.intersection(bounding_box)
  1281. if new_geo and not new_geo.is_empty:
  1282. new_geometry.append(new_geo)
  1283. elif isinstance(geo_elem, MultiPolygon):
  1284. for poly in geo_elem:
  1285. for ring in self.poly2rings(poly):
  1286. new_geo = ring.intersection(bounding_box)
  1287. if new_geo and not new_geo.is_empty:
  1288. new_geometry.append(new_geo)
  1289. elif isinstance(geo_elem, LineString):
  1290. new_geo = geo_elem.intersection(bounding_box)
  1291. if new_geo:
  1292. if not new_geo.is_empty:
  1293. new_geometry.append(new_geo)
  1294. elif isinstance(geo_elem, MultiLineString):
  1295. for line_elem in geo_elem:
  1296. new_geo = line_elem.intersection(bounding_box)
  1297. if new_geo and not new_geo.is_empty:
  1298. new_geometry.append(new_geo)
  1299. except TypeError:
  1300. if isinstance(isolated_geo, Polygon):
  1301. for ring in self.poly2rings(isolated_geo):
  1302. new_geo = ring.intersection(bounding_box)
  1303. if new_geo:
  1304. if not new_geo.is_empty:
  1305. new_geometry.append(new_geo)
  1306. elif isinstance(isolated_geo, LineString):
  1307. new_geo = isolated_geo.intersection(bounding_box)
  1308. if new_geo and not new_geo.is_empty:
  1309. new_geometry.append(new_geo)
  1310. elif isinstance(isolated_geo, MultiLineString):
  1311. for line_elem in isolated_geo:
  1312. new_geo = line_elem.intersection(bounding_box)
  1313. if new_geo and not new_geo.is_empty:
  1314. new_geometry.append(new_geo)
  1315. for k, v in tools_storage.items():
  1316. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1317. current_uid = int(k)
  1318. # add the solid_geometry to the current too in self.paint_tools dictionary
  1319. # and then reset the temporary list that stored that solid_geometry
  1320. v['solid_geometry'] = deepcopy(new_geometry)
  1321. v['data']['name'] = name
  1322. break
  1323. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1324. sol_geo = cascaded_union(isolated_geo)
  1325. if has_offset is True:
  1326. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1327. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1328. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1329. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1330. elif isinstance(ncc_obj, FlatCAMGeometry):
  1331. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  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. else:
  1338. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1339. return
  1340. if empty.is_empty:
  1341. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1342. return 'fail'
  1343. if type(empty) is Polygon:
  1344. empty = MultiPolygon([empty])
  1345. for tool in sorted_tools:
  1346. app_obj.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1347. cleared_geo[:] = []
  1348. # Get remaining tools offset
  1349. offset -= (tool - 1e-12)
  1350. # Area to clear
  1351. area = empty.buffer(-offset)
  1352. try:
  1353. area = area.difference(cleared)
  1354. except Exception as e:
  1355. continue
  1356. # Transform area to MultiPolygon
  1357. if type(area) is Polygon:
  1358. area = MultiPolygon([area])
  1359. if area.geoms:
  1360. if len(area.geoms) > 0:
  1361. for p in area.geoms:
  1362. try:
  1363. if ncc_method == 'standard':
  1364. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1365. overlap=overlap, contour=contour, connect=connect)
  1366. elif ncc_method == 'seed':
  1367. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1368. overlap=overlap, contour=contour, connect=connect)
  1369. else:
  1370. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1371. overlap=overlap, contour=contour, connect=connect)
  1372. if cp:
  1373. cleared_geo += list(cp.get_objects())
  1374. except Exception as e:
  1375. log.warning("Polygon can not be cleared. %s" % str(e))
  1376. app_obj.poly_not_cleared = True
  1377. continue
  1378. # check if there is a geometry at all in the cleared geometry
  1379. if cleared_geo:
  1380. # Overall cleared area
  1381. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1382. tool / 1.999999)
  1383. # clean-up cleared geo
  1384. cleared = cleared.buffer(0)
  1385. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1386. # solid_geometry
  1387. for k, v in tools_storage.items():
  1388. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1389. current_uid = int(k)
  1390. # add the solid_geometry to the current too in self.paint_tools dictionary
  1391. # and then reset the temporary list that stored that solid_geometry
  1392. v['solid_geometry'] = deepcopy(cleared_geo)
  1393. v['data']['name'] = name
  1394. break
  1395. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1396. else:
  1397. log.debug("There are no geometries in the cleared polygon.")
  1398. # delete tools with empty geometry
  1399. keys_to_delete = []
  1400. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1401. for uid in tools_storage:
  1402. # if the solid_geometry (type=list) is empty
  1403. if not tools_storage[uid]['solid_geometry']:
  1404. keys_to_delete.append(uid)
  1405. # actual delete of keys from the tools_storage dict
  1406. for k in keys_to_delete:
  1407. tools_storage.pop(k, None)
  1408. geo_obj.options["cnctooldia"] = str(tool)
  1409. geo_obj.multigeo = True
  1410. geo_obj.tools.clear()
  1411. geo_obj.tools = dict(tools_storage)
  1412. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1413. has_solid_geo = 0
  1414. for tooluid in geo_obj.tools:
  1415. if geo_obj.tools[tooluid]['solid_geometry']:
  1416. has_solid_geo += 1
  1417. if has_solid_geo == 0:
  1418. app_obj.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1419. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1420. "Change the painting parameters and try again."))
  1421. return
  1422. # Experimental...
  1423. # print("Indexing...", end=' ')
  1424. # geo_obj.make_index()
  1425. self.app.inform.emit(_("[success] Non-Copper clear all done."))
  1426. # ###########################################################################################
  1427. # Initializes the new geometry object for the case of the rest-machining ####################
  1428. # ###########################################################################################
  1429. def gen_clear_area_rest(geo_obj, app_obj):
  1430. assert isinstance(geo_obj, FlatCAMGeometry), \
  1431. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1432. sorted_tools.sort(reverse=True)
  1433. cleared_geo = []
  1434. cleared_by_last_tool = []
  1435. rest_geo = []
  1436. current_uid = 1
  1437. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1438. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1439. app_obj.poly_not_cleared = True
  1440. # ###################################################################################################
  1441. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1442. # ###################################################################################################
  1443. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1444. sol_geo = ncc_obj.solid_geometry
  1445. if has_offset is True:
  1446. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1447. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1448. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1449. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1450. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1451. isolated_geo = []
  1452. self.solid_geometry = ncc_obj.solid_geometry
  1453. # if milling type is climb then the move is counter-clockwise around features
  1454. milling_type = self.milling_type_radio.get_value()
  1455. for tool_iso in isotooldia:
  1456. new_geometry = []
  1457. if milling_type == 'cl':
  1458. isolated_geo = self.generate_envelope(tool_iso, 1)
  1459. else:
  1460. isolated_geo = self.generate_envelope(tool_iso, 0)
  1461. if isolated_geo == 'fail':
  1462. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1463. else:
  1464. try:
  1465. for geo_elem in isolated_geo:
  1466. if isinstance(geo_elem, Polygon):
  1467. for ring in self.poly2rings(geo_elem):
  1468. new_geo = ring.intersection(bounding_box)
  1469. if new_geo and not new_geo.is_empty:
  1470. new_geometry.append(new_geo)
  1471. elif isinstance(geo_elem, MultiPolygon):
  1472. for poly in geo_elem:
  1473. for ring in self.poly2rings(poly):
  1474. new_geo = ring.intersection(bounding_box)
  1475. if new_geo and not new_geo.is_empty:
  1476. new_geometry.append(new_geo)
  1477. elif isinstance(geo_elem, LineString):
  1478. new_geo = geo_elem.intersection(bounding_box)
  1479. if new_geo:
  1480. if not new_geo.is_empty:
  1481. new_geometry.append(new_geo)
  1482. elif isinstance(geo_elem, MultiLineString):
  1483. for line_elem in geo_elem:
  1484. new_geo = line_elem.intersection(bounding_box)
  1485. if new_geo and not new_geo.is_empty:
  1486. new_geometry.append(new_geo)
  1487. except TypeError:
  1488. if isinstance(isolated_geo, Polygon):
  1489. for ring in self.poly2rings(isolated_geo):
  1490. new_geo = ring.intersection(bounding_box)
  1491. if new_geo:
  1492. if not new_geo.is_empty:
  1493. new_geometry.append(new_geo)
  1494. elif isinstance(isolated_geo, LineString):
  1495. new_geo = isolated_geo.intersection(bounding_box)
  1496. if new_geo and not new_geo.is_empty:
  1497. new_geometry.append(new_geo)
  1498. elif isinstance(isolated_geo, MultiLineString):
  1499. for line_elem in isolated_geo:
  1500. new_geo = line_elem.intersection(bounding_box)
  1501. if new_geo and not new_geo.is_empty:
  1502. new_geometry.append(new_geo)
  1503. for k, v in tools_storage.items():
  1504. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1505. current_uid = int(k)
  1506. # add the solid_geometry to the current too in self.paint_tools dictionary
  1507. # and then reset the temporary list that stored that solid_geometry
  1508. v['solid_geometry'] = deepcopy(new_geometry)
  1509. v['data']['name'] = name
  1510. break
  1511. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1512. sol_geo = cascaded_union(isolated_geo)
  1513. if has_offset is True:
  1514. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1515. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1516. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1517. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1518. elif isinstance(ncc_obj, FlatCAMGeometry):
  1519. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  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. else:
  1526. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1527. return
  1528. if empty.is_empty:
  1529. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1530. return 'fail'
  1531. if type(empty) is Polygon:
  1532. empty = MultiPolygon([empty])
  1533. area = empty.buffer(0)
  1534. # Generate area for each tool
  1535. while sorted_tools:
  1536. tool = sorted_tools.pop(0)
  1537. app_obj.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1538. tool_used = tool - 1e-12
  1539. cleared_geo[:] = []
  1540. # Area to clear
  1541. for poly in cleared_by_last_tool:
  1542. try:
  1543. area = area.difference(poly)
  1544. except Exception as e:
  1545. pass
  1546. cleared_by_last_tool[:] = []
  1547. # Transform area to MultiPolygon
  1548. if type(area) is Polygon:
  1549. area = MultiPolygon([area])
  1550. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1551. # and rest_geo it's a list
  1552. allparts = [p.buffer(0) for p in area.geoms]
  1553. allparts += deepcopy(rest_geo)
  1554. rest_geo[:] = []
  1555. area = MultiPolygon(deepcopy(allparts))
  1556. allparts[:] = []
  1557. if area.geoms:
  1558. if len(area.geoms) > 0:
  1559. for p in area.geoms:
  1560. try:
  1561. if ncc_method == 'standard':
  1562. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1563. overlap=overlap, contour=contour, connect=connect)
  1564. elif ncc_method == 'seed':
  1565. cp = self.clear_polygon2(p, tool_used,
  1566. self.app.defaults["gerber_circle_steps"],
  1567. overlap=overlap, contour=contour, connect=connect)
  1568. else:
  1569. cp = self.clear_polygon3(p, tool_used,
  1570. self.app.defaults["gerber_circle_steps"],
  1571. overlap=overlap, contour=contour, connect=connect)
  1572. cleared_geo.append(list(cp.get_objects()))
  1573. except:
  1574. log.warning("Polygon can't be cleared.")
  1575. # this polygon should be added to a list and then try clear it with a smaller tool
  1576. rest_geo.append(p)
  1577. # check if there is a geometry at all in the cleared geometry
  1578. if cleared_geo:
  1579. # Overall cleared area
  1580. cleared_area = list(self.flatten_list(cleared_geo))
  1581. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1582. # for p in cleared_area])
  1583. # here we store the poly's already processed in the original geometry by the current tool
  1584. # into cleared_by_last_tool list
  1585. # this will be sustracted from the original geometry_to_be_cleared and make data for
  1586. # the next tool
  1587. buffer_value = tool_used / 2
  1588. for p in cleared_area:
  1589. poly = p.buffer(buffer_value)
  1590. cleared_by_last_tool.append(poly)
  1591. # find the tooluid associated with the current tool_dia so we know
  1592. # where to add the tool solid_geometry
  1593. for k, v in tools_storage.items():
  1594. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1595. current_uid = int(k)
  1596. # add the solid_geometry to the current too in self.paint_tools dictionary
  1597. # and then reset the temporary list that stored that solid_geometry
  1598. v['solid_geometry'] = deepcopy(cleared_area)
  1599. v['data']['name'] = name
  1600. cleared_area[:] = []
  1601. break
  1602. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1603. else:
  1604. log.debug("There are no geometries in the cleared polygon.")
  1605. geo_obj.multigeo = True
  1606. geo_obj.options["cnctooldia"] = str(tool)
  1607. # check to see if geo_obj.tools is empty
  1608. # it will be updated only if there is a solid_geometry for tools
  1609. if geo_obj.tools:
  1610. return
  1611. else:
  1612. # I will use this variable for this purpose although it was meant for something else
  1613. # signal that we have no geo in the object therefore don't create it
  1614. app_obj.poly_not_cleared = False
  1615. return "fail"
  1616. # ###########################################################################################
  1617. # Create the Job function and send it to the worker to be processed in another thread #######
  1618. # ###########################################################################################
  1619. def job_thread(app_obj):
  1620. try:
  1621. if rest_machining_choice is True:
  1622. app_obj.new_object("geometry", name, gen_clear_area_rest)
  1623. else:
  1624. app_obj.new_object("geometry", name, gen_clear_area)
  1625. except Exception as e:
  1626. proc.done()
  1627. traceback.print_stack()
  1628. return
  1629. proc.done()
  1630. # focus on Selected Tab
  1631. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1632. # Promise object with the new name
  1633. self.app.collection.promise(name)
  1634. # Background
  1635. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1636. # def on_ncc(self):
  1637. #
  1638. # # Prepare non-copper polygons
  1639. # if self.reference_radio.get_value() == 'area':
  1640. # geo_n = self.sel_rect
  1641. #
  1642. # geo_buff_list = []
  1643. # for poly in geo_n:
  1644. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1645. # bounding_box = cascaded_union(geo_buff_list)
  1646. # else:
  1647. # geo_n = self.bound_obj.solid_geometry
  1648. #
  1649. # try:
  1650. # if isinstance(geo_n, MultiPolygon):
  1651. # env_obj = geo_n.convex_hull
  1652. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1653. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1654. # env_obj = cascaded_union(geo_n)
  1655. # else:
  1656. # env_obj = cascaded_union(geo_n)
  1657. # env_obj = env_obj.convex_hull
  1658. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1659. # except Exception as e:
  1660. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1661. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1662. # return
  1663. #
  1664. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1665. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1666. # if self.ncc_choice_offset_cb.isChecked():
  1667. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1668. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1669. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1670. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1671. # else:
  1672. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1673. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1674. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1675. # if self.ncc_choice_offset_cb.isChecked():
  1676. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1677. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1678. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1679. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1680. # else:
  1681. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1682. # else:
  1683. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1684. # return
  1685. #
  1686. # if type(empty) is Polygon:
  1687. # empty = MultiPolygon([empty])
  1688. #
  1689. # if empty.is_empty:
  1690. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1691. # return
  1692. #
  1693. # # clear non copper using standard algorithm
  1694. # if clearing_method is False:
  1695. # self.clear_non_copper(
  1696. # empty=empty,
  1697. # over=over,
  1698. # pol_method=pol_method,
  1699. # connect=connect,
  1700. # contour=contour
  1701. # )
  1702. # # clear non copper using rest machining algorithm
  1703. # else:
  1704. # self.clear_non_copper_rest(
  1705. # empty=empty,
  1706. # over=over,
  1707. # pol_method=pol_method,
  1708. # connect=connect,
  1709. # contour=contour
  1710. # )
  1711. #
  1712. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1713. #
  1714. # name = outname if outname else self.obj_name + "_ncc"
  1715. #
  1716. # # Sort tools in descending order
  1717. # sorted_tools = []
  1718. # for k, v in self.ncc_tools.items():
  1719. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1720. #
  1721. # order = self.ncc_order_radio.get_value()
  1722. # if order == 'fwd':
  1723. # sorted_tools.sort(reverse=False)
  1724. # elif order == 'rev':
  1725. # sorted_tools.sort(reverse=True)
  1726. # else:
  1727. # pass
  1728. #
  1729. # # Do job in background
  1730. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1731. #
  1732. # def initialize(geo_obj, app_obj):
  1733. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1734. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1735. #
  1736. # cleared_geo = []
  1737. # # Already cleared area
  1738. # cleared = MultiPolygon()
  1739. #
  1740. # # flag for polygons not cleared
  1741. # app_obj.poly_not_cleared = False
  1742. #
  1743. # # Generate area for each tool
  1744. # offset = sum(sorted_tools)
  1745. # current_uid = int(1)
  1746. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1747. #
  1748. # for tool in sorted_tools:
  1749. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1750. # cleared_geo[:] = []
  1751. #
  1752. # # Get remaining tools offset
  1753. # offset -= (tool - 1e-12)
  1754. #
  1755. # # Area to clear
  1756. # area = empty.buffer(-offset)
  1757. # try:
  1758. # area = area.difference(cleared)
  1759. # except Exception as e:
  1760. # continue
  1761. #
  1762. # # Transform area to MultiPolygon
  1763. # if type(area) is Polygon:
  1764. # area = MultiPolygon([area])
  1765. #
  1766. # if area.geoms:
  1767. # if len(area.geoms) > 0:
  1768. # for p in area.geoms:
  1769. # try:
  1770. # if pol_method == 'standard':
  1771. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1772. # overlap=over, contour=contour, connect=connect)
  1773. # elif pol_method == 'seed':
  1774. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1775. # overlap=over, contour=contour, connect=connect)
  1776. # else:
  1777. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1778. # overlap=over, contour=contour, connect=connect)
  1779. # if cp:
  1780. # cleared_geo += list(cp.get_objects())
  1781. # except Exception as e:
  1782. # log.warning("Polygon can not be cleared. %s" % str(e))
  1783. # app_obj.poly_not_cleared = True
  1784. # continue
  1785. #
  1786. # # check if there is a geometry at all in the cleared geometry
  1787. # if cleared_geo:
  1788. # # Overall cleared area
  1789. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  1790. # tool / 1.999999)
  1791. #
  1792. # # clean-up cleared geo
  1793. # cleared = cleared.buffer(0)
  1794. #
  1795. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  1796. # # solid_geometry
  1797. # for k, v in self.ncc_tools.items():
  1798. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1799. # current_uid = int(k)
  1800. #
  1801. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1802. # # and then reset the temporary list that stored that solid_geometry
  1803. # v['solid_geometry'] = deepcopy(cleared_geo)
  1804. # v['data']['name'] = name
  1805. # break
  1806. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1807. # else:
  1808. # log.debug("There are no geometries in the cleared polygon.")
  1809. #
  1810. # geo_obj.options["cnctooldia"] = str(tool)
  1811. # geo_obj.multigeo = True
  1812. #
  1813. # def job_thread(app_obj):
  1814. # try:
  1815. # app_obj.new_object("geometry", name, initialize)
  1816. # except Exception as e:
  1817. # proc.done()
  1818. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  1819. # return
  1820. # proc.done()
  1821. #
  1822. # if app_obj.poly_not_cleared is False:
  1823. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  1824. # else:
  1825. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  1826. # 'Check the result.'))
  1827. # # reset the variable for next use
  1828. # app_obj.poly_not_cleared = False
  1829. #
  1830. # # focus on Selected Tab
  1831. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1832. #
  1833. # # Promise object with the new name
  1834. # self.app.collection.promise(name)
  1835. #
  1836. # # Background
  1837. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1838. #
  1839. # # clear copper with 'rest-machining' algorithm
  1840. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1841. #
  1842. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1843. #
  1844. # # Sort tools in descending order
  1845. # sorted_tools = []
  1846. # for k, v in self.ncc_tools.items():
  1847. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1848. # sorted_tools.sort(reverse=True)
  1849. #
  1850. # # Do job in background
  1851. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1852. #
  1853. # def initialize_rm(geo_obj, app_obj):
  1854. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1855. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1856. #
  1857. # cleared_geo = []
  1858. # cleared_by_last_tool = []
  1859. # rest_geo = []
  1860. # current_uid = 1
  1861. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1862. #
  1863. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1864. # app_obj.poly_not_cleared = True
  1865. #
  1866. # area = empty.buffer(0)
  1867. # # Generate area for each tool
  1868. # while sorted_tools:
  1869. # tool = sorted_tools.pop(0)
  1870. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1871. #
  1872. # tool_used = tool - 1e-12
  1873. # cleared_geo[:] = []
  1874. #
  1875. # # Area to clear
  1876. # for poly in cleared_by_last_tool:
  1877. # try:
  1878. # area = area.difference(poly)
  1879. # except Exception as e:
  1880. # pass
  1881. # cleared_by_last_tool[:] = []
  1882. #
  1883. # # Transform area to MultiPolygon
  1884. # if type(area) is Polygon:
  1885. # area = MultiPolygon([area])
  1886. #
  1887. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1888. # # and rest_geo it's a list
  1889. # allparts = [p.buffer(0) for p in area.geoms]
  1890. # allparts += deepcopy(rest_geo)
  1891. # rest_geo[:] = []
  1892. # area = MultiPolygon(deepcopy(allparts))
  1893. # allparts[:] = []
  1894. #
  1895. # if area.geoms:
  1896. # if len(area.geoms) > 0:
  1897. # for p in area.geoms:
  1898. # try:
  1899. # if pol_method == 'standard':
  1900. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1901. # overlap=over, contour=contour, connect=connect)
  1902. # elif pol_method == 'seed':
  1903. # cp = self.clear_polygon2(p, tool_used,
  1904. # self.app.defaults["gerber_circle_steps"],
  1905. # overlap=over, contour=contour, connect=connect)
  1906. # else:
  1907. # cp = self.clear_polygon3(p, tool_used,
  1908. # self.app.defaults["gerber_circle_steps"],
  1909. # overlap=over, contour=contour, connect=connect)
  1910. # cleared_geo.append(list(cp.get_objects()))
  1911. # except:
  1912. # log.warning("Polygon can't be cleared.")
  1913. # # this polygon should be added to a list and then try clear it with a smaller tool
  1914. # rest_geo.append(p)
  1915. #
  1916. # # check if there is a geometry at all in the cleared geometry
  1917. # if cleared_geo:
  1918. # # Overall cleared area
  1919. # cleared_area = list(self.flatten_list(cleared_geo))
  1920. #
  1921. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1922. # # for p in cleared_area])
  1923. #
  1924. # # here we store the poly's already processed in the original geometry by the current tool
  1925. # # into cleared_by_last_tool list
  1926. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  1927. # # the next tool
  1928. # buffer_value = tool_used / 2
  1929. # for p in cleared_area:
  1930. # poly = p.buffer(buffer_value)
  1931. # cleared_by_last_tool.append(poly)
  1932. #
  1933. # # find the tooluid associated with the current tool_dia so we know
  1934. # # where to add the tool solid_geometry
  1935. # for k, v in self.ncc_tools.items():
  1936. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1937. # current_uid = int(k)
  1938. #
  1939. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1940. # # and then reset the temporary list that stored that solid_geometry
  1941. # v['solid_geometry'] = deepcopy(cleared_area)
  1942. # v['data']['name'] = name
  1943. # cleared_area[:] = []
  1944. # break
  1945. #
  1946. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1947. # else:
  1948. # log.debug("There are no geometries in the cleared polygon.")
  1949. #
  1950. # geo_obj.multigeo = True
  1951. # geo_obj.options["cnctooldia"] = str(tool)
  1952. #
  1953. # # check to see if geo_obj.tools is empty
  1954. # # it will be updated only if there is a solid_geometry for tools
  1955. # if geo_obj.tools:
  1956. # return
  1957. # else:
  1958. # # I will use this variable for this purpose although it was meant for something else
  1959. # # signal that we have no geo in the object therefore don't create it
  1960. # app_obj.poly_not_cleared = False
  1961. # return "fail"
  1962. #
  1963. # def job_thread(app_obj):
  1964. # try:
  1965. # app_obj.new_object("geometry", name, initialize_rm)
  1966. # except Exception as e:
  1967. # proc.done()
  1968. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  1969. # return
  1970. #
  1971. # if app_obj.poly_not_cleared is True:
  1972. # app_obj.inform.emit('[success] NCC Tool finished.')
  1973. # # focus on Selected Tab
  1974. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1975. # else:
  1976. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  1977. # 'with current settings.'))
  1978. # # focus on Project Tab
  1979. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1980. # proc.done()
  1981. # # reset the variable for next use
  1982. # app_obj.poly_not_cleared = False
  1983. #
  1984. # # Promise object with the new name
  1985. # self.app.collection.promise(name)
  1986. #
  1987. # # Background
  1988. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1989. @staticmethod
  1990. def get_ncc_empty_area(target, boundary=None):
  1991. """
  1992. Returns the complement of target geometry within
  1993. the given boundary polygon. If not specified, it defaults to
  1994. the rectangular bounding box of target geometry.
  1995. """
  1996. if boundary is None:
  1997. boundary = target.envelope
  1998. return boundary.difference(target)
  1999. def reset_fields(self):
  2000. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2001. def reset_usage(self):
  2002. self.obj_name = ""
  2003. self.ncc_obj = None
  2004. self.bound_obj = None
  2005. self.first_click = False
  2006. self.cursor_pos = None
  2007. self.mouse_is_dragging = False
  2008. self.sel_rect = []
  2009. @staticmethod
  2010. def poly2rings(poly):
  2011. return [poly.exterior] + [interior for interior in poly.interiors]
  2012. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2013. # isolation_geometry produces an envelope that is going on the left of the geometry
  2014. # (the copper features). To leave the least amount of burrs on the features
  2015. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2016. # the first pass is the one cutting all of the features, so it needs to be reversed
  2017. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2018. # to cut on the right side of the left over copper i.e on the left side of the features.
  2019. try:
  2020. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2021. except Exception as e:
  2022. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2023. return 'fail'
  2024. if invert:
  2025. try:
  2026. try:
  2027. pl = []
  2028. for p in geom:
  2029. if p is not None:
  2030. if isinstance(p, Polygon):
  2031. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2032. elif isinstance(p, LinearRing):
  2033. pl.append(Polygon(p.coords[::-1]))
  2034. geom = MultiPolygon(pl)
  2035. except TypeError:
  2036. if isinstance(geom, Polygon) and geom is not None:
  2037. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2038. elif isinstance(geom, LinearRing) and geom is not None:
  2039. geom = Polygon(geom.coords[::-1])
  2040. else:
  2041. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2042. type(geom))
  2043. except Exception as e:
  2044. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2045. return 'fail'
  2046. return geom