ToolNonCopperClear.py 134 KB

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