ToolNonCopperClear.py 133 KB

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