ToolNonCopperClear.py 131 KB

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