ToolNonCopperClear.py 111 KB

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