ToolNonCopperClear.py 183 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782
  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, FCButton
  10. from flatcamParsers.ParseGerber import Gerber
  11. import FlatCAMApp
  12. from copy import deepcopy
  13. import numpy as np
  14. import math
  15. from shapely.geometry import base
  16. from shapely.ops import cascaded_union
  17. from shapely.geometry import MultiPolygon, Polygon, MultiLineString, LineString, LinearRing
  18. import logging
  19. import traceback
  20. import gettext
  21. import FlatCAMTranslation as fcTranslate
  22. import builtins
  23. fcTranslate.apply_language('strings')
  24. if '_' not in builtins.__dict__:
  25. _ = gettext.gettext
  26. log = logging.getLogger('base')
  27. class NonCopperClear(FlatCAMTool, Gerber):
  28. toolName = _("Non-Copper Clearing")
  29. def __init__(self, app):
  30. self.app = app
  31. self.decimals = self.app.decimals
  32. FlatCAMTool.__init__(self, app)
  33. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  34. self.tools_frame = QtWidgets.QFrame()
  35. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  36. self.layout.addWidget(self.tools_frame)
  37. self.tools_box = QtWidgets.QVBoxLayout()
  38. self.tools_box.setContentsMargins(0, 0, 0, 0)
  39. self.tools_frame.setLayout(self.tools_box)
  40. # ## Title
  41. title_label = QtWidgets.QLabel("%s" % self.toolName)
  42. title_label.setStyleSheet("""
  43. QLabel
  44. {
  45. font-size: 16px;
  46. font-weight: bold;
  47. }
  48. """)
  49. self.tools_box.addWidget(title_label)
  50. # ## Form Layout
  51. form_layout = QtWidgets.QFormLayout()
  52. self.tools_box.addLayout(form_layout)
  53. # ################################################
  54. # ##### Type of object to be copper cleaned ######
  55. # ################################################
  56. self.type_obj_combo = QtWidgets.QComboBox()
  57. self.type_obj_combo.addItem("Gerber")
  58. self.type_obj_combo.addItem("Excellon")
  59. self.type_obj_combo.addItem("Geometry")
  60. # we get rid of item1 ("Excellon") as it is not suitable
  61. self.type_obj_combo.view().setRowHidden(1, True)
  62. self.type_obj_combo.setItemIcon(0, QtGui.QIcon(self.app.resource_location + "/flatcam_icon16.png"))
  63. self.type_obj_combo.setItemIcon(2, QtGui.QIcon(self.app.resource_location + "/geometry16.png"))
  64. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  65. self.type_obj_combo_label.setToolTip(
  66. _("Specify the type of object to be cleared of excess copper.\n"
  67. "It can be of type: Gerber or Geometry.\n"
  68. "What is selected here will dictate the kind\n"
  69. "of objects that will populate the 'Object' combobox.")
  70. )
  71. self.type_obj_combo_label.setMinimumWidth(60)
  72. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  73. # ################################################
  74. # ##### The object to be copper cleaned ##########
  75. # ################################################
  76. self.object_combo = QtWidgets.QComboBox()
  77. self.object_combo.setModel(self.app.collection)
  78. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  79. self.object_combo.setCurrentIndex(1)
  80. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  81. self.object_label.setToolTip(_("Object to be cleared of excess copper."))
  82. form_layout.addRow(self.object_label, self.object_combo)
  83. separator_line = QtWidgets.QFrame()
  84. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  85. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  86. self.tools_box.addWidget(separator_line)
  87. # ### Tools ## ##
  88. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  89. self.tools_table_label.setToolTip(
  90. _("Tools pool from which the algorithm\n"
  91. "will pick the ones used for copper clearing.")
  92. )
  93. self.tools_box.addWidget(self.tools_table_label)
  94. self.tools_table = FCTable()
  95. self.tools_box.addWidget(self.tools_table)
  96. self.tools_table.setColumnCount(5)
  97. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), '', _("Operation")])
  98. self.tools_table.setColumnHidden(3, True)
  99. self.tools_table.setSortingEnabled(False)
  100. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  101. self.tools_table.horizontalHeaderItem(0).setToolTip(
  102. _("This is the Tool Number.\n"
  103. "Non copper clearing will start with the tool with the biggest \n"
  104. "diameter, continuing until there are no more tools.\n"
  105. "Only tools that create NCC clearing geometry will still be present\n"
  106. "in the resulting geometry. This is because with some tools\n"
  107. "this function will not be able to create painting geometry.")
  108. )
  109. self.tools_table.horizontalHeaderItem(1).setToolTip(
  110. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  111. "is the cut width into the material."))
  112. self.tools_table.horizontalHeaderItem(2).setToolTip(
  113. _("The Tool Type (TT) can be:\n"
  114. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  115. "the cut width in material is exactly the tool diameter.\n"
  116. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  117. "- V-Shape -> it will disable de Z-Cut parameter in the resulting geometry UI form\n"
  118. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  119. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  120. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  121. "column of this table.\n"
  122. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  123. "in the resulting geometry as Isolation."))
  124. self.tools_table.horizontalHeaderItem(4).setToolTip(
  125. _("The 'Operation' can be:\n"
  126. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  127. "If it's not successful then the non-copper clearing will fail, too.\n"
  128. "- Clear -> the regular non-copper clearing."))
  129. grid1 = QtWidgets.QGridLayout()
  130. self.tools_box.addLayout(grid1)
  131. grid1.setColumnStretch(0, 0)
  132. grid1.setColumnStretch(1, 1)
  133. # Milling Type Radio Button
  134. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  135. self.milling_type_label.setToolTip(
  136. _("Milling type when the selected tool is of type: 'iso_op':\n"
  137. "- climb / best for precision milling and to reduce tool usage\n"
  138. "- conventional / useful when there is no backlash compensation")
  139. )
  140. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  141. {'label': _('Conventional'), 'value': 'cv'}])
  142. self.milling_type_radio.setToolTip(
  143. _("Milling type when the selected tool is of type: 'iso_op':\n"
  144. "- climb / best for precision milling and to reduce tool usage\n"
  145. "- conventional / useful when there is no backlash compensation")
  146. )
  147. self.milling_type_radio.setObjectName(_("Milling Type"))
  148. grid1.addWidget(self.milling_type_label, 0, 0)
  149. grid1.addWidget(self.milling_type_radio, 0, 1)
  150. # Tool order
  151. self.ncc_order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  152. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  153. "'No' --> means that the used order is the one in the tool table\n"
  154. "'Forward' --> means that the tools will be ordered from small to big\n"
  155. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  156. "WARNING: using rest machining will automatically set the order\n"
  157. "in reverse and disable this control."))
  158. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  159. {'label': _('Forward'), 'value': 'fwd'},
  160. {'label': _('Reverse'), 'value': 'rev'}])
  161. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  162. "'No' --> means that the used order is the one in the tool table\n"
  163. "'Forward' --> means that the tools will be ordered from small to big\n"
  164. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  165. "WARNING: using rest machining will automatically set the order\n"
  166. "in reverse and disable this control."))
  167. grid1.addWidget(self.ncc_order_label, 1, 0)
  168. grid1.addWidget(self.ncc_order_radio, 1, 1)
  169. separator_line = QtWidgets.QFrame()
  170. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  171. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  172. grid1.addWidget(separator_line, 2, 0, 1, 2)
  173. self.milling_type_label.hide()
  174. self.milling_type_radio.hide()
  175. # #############################################################
  176. # ############### Tool selection ##############################
  177. # #############################################################
  178. self.grid3 = QtWidgets.QGridLayout()
  179. self.tools_box.addLayout(self.grid3)
  180. self.grid3.setColumnStretch(0, 0)
  181. self.grid3.setColumnStretch(1, 1)
  182. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  183. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  184. # Tool Type Radio Button
  185. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  186. self.tool_type_label.setToolTip(
  187. _("Default tool type:\n"
  188. "- 'V-shape'\n"
  189. "- Circular")
  190. )
  191. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  192. {'label': _('Circular'), 'value': 'C1'}])
  193. self.tool_type_radio.setToolTip(
  194. _("Default tool type:\n"
  195. "- 'V-shape'\n"
  196. "- Circular")
  197. )
  198. self.tool_type_radio.setObjectName(_("Tool Type"))
  199. self.grid3.addWidget(self.tool_type_label, 2, 0)
  200. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  201. # Tip Dia
  202. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  203. self.tipdialabel.setToolTip(
  204. _("The tip diameter for V-Shape Tool"))
  205. self.tipdia_entry = FCDoubleSpinner()
  206. self.tipdia_entry.set_precision(self.decimals)
  207. self.tipdia_entry.set_range(0.0000, 9999.9999)
  208. self.tipdia_entry.setSingleStep(0.1)
  209. self.tipdia_entry.setObjectName(_("V-Tip Dia"))
  210. self.grid3.addWidget(self.tipdialabel, 3, 0)
  211. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  212. # Tip Angle
  213. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  214. self.tipanglelabel.setToolTip(
  215. _("The tip angle for V-Shape Tool.\n"
  216. "In degree."))
  217. self.tipangle_entry = FCDoubleSpinner()
  218. self.tipangle_entry.set_precision(self.decimals)
  219. self.tipangle_entry.set_range(0.0000, 180.0000)
  220. self.tipangle_entry.setSingleStep(5)
  221. self.tipangle_entry.setObjectName(_("V-Tip Angle"))
  222. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  223. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  224. # Cut Z entry
  225. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  226. cutzlabel.setToolTip(
  227. _("Depth of cut into material. Negative value.\n"
  228. "In FlatCAM units.")
  229. )
  230. self.cutz_entry = FCDoubleSpinner()
  231. self.cutz_entry.set_precision(self.decimals)
  232. self.cutz_entry.set_range(-99999.9999, 0.0000)
  233. self.cutz_entry.setObjectName(_("Cut Z"))
  234. self.cutz_entry.setToolTip(
  235. _("Depth of cut into material. Negative value.\n"
  236. "In FlatCAM units.")
  237. )
  238. self.grid3.addWidget(cutzlabel, 5, 0)
  239. self.grid3.addWidget(self.cutz_entry, 5, 1)
  240. # ### Tool Diameter ####
  241. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  242. self.addtool_entry_lbl.setToolTip(
  243. _("Diameter for the new tool to add in the Tool Table.\n"
  244. "If the tool is V-shape type then this value is automatically\n"
  245. "calculated from the other parameters.")
  246. )
  247. self.addtool_entry = FCDoubleSpinner()
  248. self.addtool_entry.set_precision(self.decimals)
  249. self.addtool_entry.set_range(0.000, 9999.9999)
  250. self.addtool_entry.setObjectName(_("Tool Dia"))
  251. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  252. self.grid3.addWidget(self.addtool_entry, 6, 1)
  253. hlay = QtWidgets.QHBoxLayout()
  254. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  255. self.addtool_btn.setToolTip(
  256. _("Add a new tool to the Tool Table\n"
  257. "with the diameter specified above.")
  258. )
  259. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  260. self.addtool_from_db_btn.setToolTip(
  261. _("Add a new tool to the Tool Table\n"
  262. "from the Tool DataBase.")
  263. )
  264. hlay.addWidget(self.addtool_btn)
  265. hlay.addWidget(self.addtool_from_db_btn)
  266. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  267. separator_line = QtWidgets.QFrame()
  268. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  269. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  270. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  271. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  272. self.deltool_btn.setToolTip(
  273. _("Delete a selection of tools in the Tool Table\n"
  274. "by first selecting a row(s) in the Tool Table.")
  275. )
  276. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  277. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  278. separator_line = QtWidgets.QFrame()
  279. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  280. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  281. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  282. self.tool_data_label = QtWidgets.QLabel(
  283. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  284. self.tool_data_label.setToolTip(
  285. _(
  286. "The data used for creating GCode.\n"
  287. "Each tool store it's own set of such data."
  288. )
  289. )
  290. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  291. # Overlap Entry
  292. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  293. nccoverlabel.setToolTip(
  294. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  295. "Adjust the value starting with lower values\n"
  296. "and increasing it if areas that should be cleared are still \n"
  297. "not cleared.\n"
  298. "Lower values = faster processing, faster execution on CNC.\n"
  299. "Higher values = slow processing and slow execution on CNC\n"
  300. "due of too many paths.")
  301. )
  302. self.ncc_overlap_entry = FCDoubleSpinner(suffix='%')
  303. self.ncc_overlap_entry.set_precision(self.decimals)
  304. self.ncc_overlap_entry.setWrapping(True)
  305. self.ncc_overlap_entry.setRange(0.000, 99.9999)
  306. self.ncc_overlap_entry.setSingleStep(0.1)
  307. self.ncc_overlap_entry.setObjectName(_("Overlap Rate"))
  308. self.grid3.addWidget(nccoverlabel, 13, 0)
  309. self.grid3.addWidget(self.ncc_overlap_entry, 13, 1)
  310. # Margin
  311. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  312. nccmarginlabel.setToolTip(
  313. _("Bounding box margin.")
  314. )
  315. self.ncc_margin_entry = FCDoubleSpinner()
  316. self.ncc_margin_entry.set_precision(self.decimals)
  317. self.ncc_margin_entry.set_range(-9999.9999, 9999.9999)
  318. self.ncc_margin_entry.setObjectName(_("Margin"))
  319. self.grid3.addWidget(nccmarginlabel, 14, 0)
  320. self.grid3.addWidget(self.ncc_margin_entry, 14, 1)
  321. # Method
  322. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  323. methodlabel.setToolTip(
  324. _("Algorithm for non-copper clearing:<BR>"
  325. "<B>Standard</B>: Fixed step inwards.<BR>"
  326. "<B>Seed-based</B>: Outwards from seed.<BR>"
  327. "<B>Line-based</B>: Parallel lines.")
  328. )
  329. self.ncc_method_radio = RadioSet([
  330. {"label": _("Standard"), "value": "standard"},
  331. {"label": _("Seed-based"), "value": "seed"},
  332. {"label": _("Straight lines"), "value": "lines"}
  333. ], orientation='vertical', stretch=False)
  334. self.ncc_method_radio.setObjectName(_("Method"))
  335. self.grid3.addWidget(methodlabel, 15, 0)
  336. self.grid3.addWidget(self.ncc_method_radio, 15, 1)
  337. # Connect lines
  338. self.ncc_connect_cb = FCCheckBox('%s' % _("Connect"))
  339. self.ncc_connect_cb.setObjectName(_("Connect"))
  340. self.ncc_connect_cb.setToolTip(
  341. _("Draw lines between resulting\n"
  342. "segments to minimize tool lifts.")
  343. )
  344. self.grid3.addWidget(self.ncc_connect_cb, 16, 0)
  345. # Contour
  346. self.ncc_contour_cb = FCCheckBox('%s' % _("Contour"))
  347. self.ncc_contour_cb.setObjectName(_("Contour"))
  348. self.ncc_contour_cb.setToolTip(
  349. _("Cut around the perimeter of the polygon\n"
  350. "to trim rough edges.")
  351. )
  352. self.grid3.addWidget(self.ncc_contour_cb, 16, 1)
  353. # ## NCC Offset choice
  354. self.ncc_choice_offset_cb = FCCheckBox('%s' % _("Offset"))
  355. self.ncc_choice_offset_cb.setObjectName(_("Offset"))
  356. self.ncc_choice_offset_cb.setToolTip(
  357. _("If used, it will add an offset to the copper features.\n"
  358. "The copper clearing will finish to a distance\n"
  359. "from the copper features.\n"
  360. "The value can be between 0 and 10 FlatCAM units.")
  361. )
  362. self.grid3.addWidget(self.ncc_choice_offset_cb, 19, 0)
  363. # ## NCC Offset value
  364. # self.ncc_offset_label = QtWidgets.QLabel('%s:' % _("Offset value"))
  365. # self.ncc_offset_label.setToolTip(
  366. # _("If used, it will add an offset to the copper features.\n"
  367. # "The copper clearing will finish to a distance\n"
  368. # "from the copper features.\n"
  369. # "The value can be between 0 and 10 FlatCAM units.")
  370. # )
  371. self.ncc_offset_spinner = FCDoubleSpinner()
  372. self.ncc_offset_spinner.set_range(0.00, 10.00)
  373. self.ncc_offset_spinner.set_precision(4)
  374. self.ncc_offset_spinner.setWrapping(True)
  375. self.ncc_offset_spinner.setObjectName(_("Offset value"))
  376. units = self.app.defaults['units'].upper()
  377. if units == 'MM':
  378. self.ncc_offset_spinner.setSingleStep(0.1)
  379. else:
  380. self.ncc_offset_spinner.setSingleStep(0.01)
  381. # self.grid3.addWidget(self.ncc_offset_label, 20, 0)
  382. self.grid3.addWidget(self.ncc_offset_spinner, 19, 1)
  383. # self.ncc_offset_label.hide()
  384. self.ncc_offset_spinner.setEnabled(False)
  385. separator_line = QtWidgets.QFrame()
  386. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  387. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  388. self.grid3.addWidget(separator_line, 21, 0, 1, 2)
  389. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  390. self.apply_param_to_all.setToolTip(
  391. _("The parameters in the current form will be applied\n"
  392. "on all the tools from the Tool Table.")
  393. )
  394. self.grid3.addWidget(self.apply_param_to_all, 22, 0, 1, 2)
  395. separator_line = QtWidgets.QFrame()
  396. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  397. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  398. self.grid3.addWidget(separator_line, 23, 0, 1, 2)
  399. # General Parameters
  400. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  401. self.gen_param_label.setToolTip(
  402. _("Parameters that are common for all tools.")
  403. )
  404. self.grid3.addWidget(self.gen_param_label, 24, 0, 1, 2)
  405. # Rest Machining
  406. self.ncc_rest_cb = FCCheckBox('%s' % _("Rest Machining"))
  407. self.ncc_rest_cb.setObjectName(_("Rest Machining"))
  408. self.ncc_rest_cb.setToolTip(
  409. _("If checked, use 'rest machining'.\n"
  410. "Basically it will clear copper outside PCB features,\n"
  411. "using the biggest tool and continue with the next tools,\n"
  412. "from bigger to smaller, to clear areas of copper that\n"
  413. "could not be cleared by previous tool, until there is\n"
  414. "no more copper to clear or there are no more tools.\n"
  415. "If not checked, use the standard algorithm.")
  416. )
  417. self.grid3.addWidget(self.ncc_rest_cb, 25, 0, 1, 2)
  418. # ## Reference
  419. self.reference_radio = RadioSet([
  420. {'label': _('Itself'), 'value': 'itself'},
  421. {"label": _("Area Selection"), "value": "area"},
  422. {'label': _("Reference Object"), 'value': 'box'}
  423. ], orientation='vertical', stretch=False)
  424. self.reference_radio.setObjectName(_("Reference"))
  425. self.reference_label = QtWidgets.QLabel('%s:' % _("Reference"))
  426. self.reference_label.setToolTip(
  427. _("- 'Itself' - the non copper clearing extent is based on the object that is copper cleared.\n "
  428. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  429. "- 'Reference Object' - will do non copper clearing within the area specified by another object.")
  430. )
  431. self.grid3.addWidget(self.reference_label, 26, 0, 1, 2)
  432. self.grid3.addWidget(self.reference_radio, 27, 0, 1, 2)
  433. form1 = QtWidgets.QFormLayout()
  434. self.grid3.addLayout(form1, 28, 0, 1, 2)
  435. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  436. self.box_combo_type_label.setToolTip(
  437. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  438. "It can be Gerber, Excellon or Geometry.")
  439. )
  440. self.box_combo_type = QtWidgets.QComboBox()
  441. self.box_combo_type.addItem(_("Reference Gerber"))
  442. self.box_combo_type.addItem(_("Reference Excellon"))
  443. self.box_combo_type.addItem(_("Reference Geometry"))
  444. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  445. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  446. self.box_combo_label.setToolTip(
  447. _("The FlatCAM object to be used as non copper clearing reference.")
  448. )
  449. self.box_combo = QtWidgets.QComboBox()
  450. self.box_combo.setModel(self.app.collection)
  451. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  452. self.box_combo.setCurrentIndex(1)
  453. form1.addRow(self.box_combo_label, self.box_combo)
  454. self.box_combo.hide()
  455. self.box_combo_label.hide()
  456. self.box_combo_type.hide()
  457. self.box_combo_type_label.hide()
  458. separator_line = QtWidgets.QFrame()
  459. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  460. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  461. self.grid3.addWidget(separator_line, 29, 0, 1, 2)
  462. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  463. self.generate_ncc_button.setToolTip(
  464. _("Create the Geometry Object\n"
  465. "for non-copper routing.")
  466. )
  467. self.generate_ncc_button.setStyleSheet("""
  468. QPushButton
  469. {
  470. font-weight: bold;
  471. }
  472. """)
  473. self.tools_box.addWidget(self.generate_ncc_button)
  474. self.tools_box.addStretch()
  475. # ## Reset Tool
  476. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  477. self.reset_button.setToolTip(
  478. _("Will reset the tool parameters.")
  479. )
  480. self.reset_button.setStyleSheet("""
  481. QPushButton
  482. {
  483. font-weight: bold;
  484. }
  485. """)
  486. self.tools_box.addWidget(self.reset_button)
  487. # ############################ FINSIHED GUI ###################################
  488. # #############################################################################
  489. # #############################################################################
  490. # ###################### Setup CONTEXT MENU ###################################
  491. # #############################################################################
  492. self.tools_table.setupContextMenu()
  493. self.tools_table.addContextMenu(
  494. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  495. )
  496. self.tools_table.addContextMenu(
  497. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  498. )
  499. self.tools_table.addContextMenu(
  500. _("Delete"), lambda:
  501. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  502. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  503. )
  504. # #############################################################################
  505. # ########################## VARIABLES ########################################
  506. # #############################################################################
  507. self.units = ''
  508. self.ncc_tools = dict()
  509. self.tooluid = 0
  510. # store here the default data for Geometry Data
  511. self.default_data = dict()
  512. self.obj_name = ""
  513. self.ncc_obj = None
  514. self.sel_rect = list()
  515. self.bound_obj_name = ""
  516. self.bound_obj = None
  517. self.ncc_dia_list = list()
  518. self.iso_dia_list = list()
  519. self.has_offset = None
  520. self.o_name = None
  521. self.overlap = None
  522. self.connect = None
  523. self.contour = None
  524. self.rest = None
  525. self.first_click = False
  526. self.cursor_pos = None
  527. self.mouse_is_dragging = False
  528. self.mm = None
  529. self.mr = None
  530. # store here solid_geometry when there are tool with isolation job
  531. self.solid_geometry = list()
  532. self.select_method = None
  533. self.tool_type_item_options = list()
  534. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  535. self.tooldia = None
  536. self.form_fields = {
  537. "nccoverlap": self.ncc_overlap_entry,
  538. "nccmargin": self.ncc_margin_entry,
  539. "nccmethod": self.ncc_method_radio,
  540. "nccconnect": self.ncc_connect_cb,
  541. "ncccontour": self.ncc_contour_cb,
  542. "nccoffset": self.ncc_choice_offset_cb,
  543. "nccoffset_value": self.ncc_offset_spinner,
  544. "milling_type": self.milling_type_radio
  545. }
  546. self.name2option = {
  547. _('Overlap Rate'): "nccoverlap",
  548. _('Margin'): "nccmargin",
  549. _('Method'): "nccmethod",
  550. _("Connect"): "nccconnect",
  551. _("Contour"): "ncccontour",
  552. _("Offset"): "nccoffset",
  553. _("Offset value"): "nccoffset_value",
  554. _('Milling Type'): "milling_type",
  555. }
  556. # #############################################################################
  557. # ############################ SIGNALS ########################################
  558. # #############################################################################
  559. self.addtool_btn.clicked.connect(self.on_tool_add)
  560. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  561. self.deltool_btn.clicked.connect(self.on_tool_delete)
  562. self.generate_ncc_button.clicked.connect(self.on_ncc_click)
  563. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  564. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  565. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  566. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  567. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  568. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  569. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  570. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  571. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  572. self.reset_button.clicked.connect(self.set_tool_ui)
  573. self.tools_table.currentItemChanged.connect(self.on_row_selection_change)
  574. def on_type_obj_index_changed(self, index):
  575. obj_type = self.type_obj_combo.currentIndex()
  576. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  577. self.object_combo.setCurrentIndex(0)
  578. def on_row_selection_change(self):
  579. self.update_ui()
  580. def update_ui(self, row=None):
  581. self.blockSignals(True)
  582. if row is None:
  583. try:
  584. current_row = self.tools_table.currentRow()
  585. except Exception:
  586. current_row = 0
  587. else:
  588. current_row = row
  589. if current_row < 0:
  590. current_row = 0
  591. # populate the form with the data from the tool associated with the row parameter
  592. try:
  593. item = self.tools_table.item(current_row, 3)
  594. if item is not None:
  595. tooluid = int(item.text())
  596. else:
  597. return
  598. except Exception as e:
  599. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  600. return
  601. # update the QLabel that shows for which Tool we have the parameters in the UI form
  602. self.tool_data_label.setText(
  603. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), (current_row + 1))
  604. )
  605. try:
  606. # set the form with data from the newly selected tool
  607. for tooluid_key, tooluid_value in list(self.ncc_tools.items()):
  608. if int(tooluid_key) == tooluid:
  609. for key, value in tooluid_value.items():
  610. if key == 'data':
  611. form_value_storage = tooluid_value[key]
  612. self.storage_to_form(form_value_storage)
  613. except Exception as e:
  614. log.debug("NonCopperClear ---> update_ui() " + str(e))
  615. self.blockSignals(False)
  616. def storage_to_form(self, dict_storage):
  617. for form_key in self.form_fields:
  618. for storage_key in dict_storage:
  619. if form_key == storage_key:
  620. try:
  621. self.form_fields[form_key].set_value(dict_storage[form_key])
  622. except Exception:
  623. pass
  624. def form_to_storage(self):
  625. if self.tools_table.rowCount() == 0:
  626. # there is no tool in tool table so we can't save the GUI elements values to storage
  627. return
  628. self.blockSignals(True)
  629. widget_changed = self.sender()
  630. wdg_objname = widget_changed.objectName()
  631. option_changed = self.name2option[wdg_objname]
  632. row = self.tools_table.currentRow()
  633. if row < 0:
  634. row = 0
  635. tooluid_item = int(self.tools_table.item(row, 3).text())
  636. for tooluid_key, tooluid_val in self.ncc_tools.items():
  637. if int(tooluid_key) == tooluid_item:
  638. new_option_value = self.form_fields[option_changed].get_value()
  639. if option_changed in tooluid_val:
  640. tooluid_val[option_changed] = new_option_value
  641. if option_changed in tooluid_val['data']:
  642. tooluid_val['data'][option_changed] = new_option_value
  643. self.blockSignals(False)
  644. def on_apply_param_to_all_clicked(self):
  645. if self.tools_table.rowCount() == 0:
  646. # there is no tool in tool table so we can't save the GUI elements values to storage
  647. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  648. return
  649. self.blockSignals(True)
  650. row = self.tools_table.currentRow()
  651. if row < 0:
  652. row = 0
  653. # store all the data associated with the row parameter to the self.tools storage
  654. tooldia_item = float(self.tools_table.item(row, 1).text())
  655. type_item = self.tools_table.cellWidget(row, 2).currentText()
  656. operation_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  657. nccoffset_item = self.ncc_choice_offset_cb.get_value()
  658. nccoffset_value_item = float(self.ncc_offset_spinner.get_value())
  659. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  660. temp_tools = {}
  661. temp_dia = {}
  662. temp_data = {}
  663. for tooluid_key, tooluid_value in self.ncc_tools.items():
  664. for key, value in tooluid_value.items():
  665. if key == 'data':
  666. # update the 'data' section
  667. for data_key in tooluid_value[key].keys():
  668. for form_key, form_value in self.form_fields.items():
  669. if form_key == data_key:
  670. temp_data[data_key] = form_value.get_value()
  671. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  672. # updated from self.app.defaults
  673. if data_key not in self.form_fields:
  674. temp_data[data_key] = value[data_key]
  675. temp_dia[key] = deepcopy(temp_data)
  676. temp_data.clear()
  677. elif key == 'solid_geometry':
  678. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  679. else:
  680. temp_dia[key] = deepcopy(value)
  681. temp_tools[tooluid_key] = deepcopy(temp_dia)
  682. self.ncc_tools.clear()
  683. self.ncc_tools = deepcopy(temp_tools)
  684. temp_tools.clear()
  685. self.blockSignals(False)
  686. def on_add_tool_by_key(self):
  687. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  688. text='%s:' % _('Enter a Tool Diameter'),
  689. min=0.0001, max=9999.9999, decimals=self.decimals)
  690. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  691. val, ok = tool_add_popup.get_value()
  692. if ok:
  693. if float(val) == 0:
  694. self.app.inform.emit('[WARNING_NOTCL] %s' %
  695. _("Please enter a tool diameter with non-zero value, in Float format."))
  696. return
  697. self.on_tool_add(dia=float(val))
  698. else:
  699. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  700. def install(self, icon=None, separator=None, **kwargs):
  701. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  702. def run(self, toggle=True):
  703. self.app.report_usage("ToolNonCopperClear()")
  704. if toggle:
  705. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  706. if self.app.ui.splitter.sizes()[0] == 0:
  707. self.app.ui.splitter.setSizes([1, 1])
  708. else:
  709. try:
  710. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  711. # if tab is populated with the tool but it does not have the focus, focus on it
  712. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  713. # focus on Tool Tab
  714. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  715. else:
  716. self.app.ui.splitter.setSizes([0, 1])
  717. except AttributeError:
  718. pass
  719. else:
  720. if self.app.ui.splitter.sizes()[0] == 0:
  721. self.app.ui.splitter.setSizes([1, 1])
  722. FlatCAMTool.run(self)
  723. self.set_tool_ui()
  724. # reset those objects on a new run
  725. self.ncc_obj = None
  726. self.bound_obj = None
  727. self.obj_name = ''
  728. self.bound_obj_name = ''
  729. self.build_ui()
  730. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  731. def set_tool_ui(self):
  732. self.units = self.app.defaults['units'].upper()
  733. self.tools_frame.show()
  734. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  735. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  736. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  737. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  738. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  739. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  740. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  741. self.ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  742. self.ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  743. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  744. self.milling_type_radio.set_value(self.app.defaults["tools_nccmilling_type"])
  745. self.cutz_entry.set_value(self.app.defaults["tools_ncccutz"])
  746. self.tool_type_radio.set_value(self.app.defaults["tools_ncctool_type"])
  747. self.tipdia_entry.set_value(self.app.defaults["tools_ncctipdia"])
  748. self.tipangle_entry.set_value(self.app.defaults["tools_ncctipangle"])
  749. self.addtool_entry.set_value(self.app.defaults["tools_nccnewdia"])
  750. self.on_tool_type(val=self.tool_type_radio.get_value())
  751. # init the working variables
  752. self.default_data.clear()
  753. self.default_data = {
  754. "name": '_ncc',
  755. "plot": self.app.defaults["geometry_plot"],
  756. "cutz": float(self.cutz_entry.get_value()),
  757. "vtipdia": float(self.tipdia_entry.get_value()),
  758. "vtipangle": float(self.tipangle_entry.get_value()),
  759. "travelz": self.app.defaults["geometry_travelz"],
  760. "feedrate": self.app.defaults["geometry_feedrate"],
  761. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  762. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  763. "dwell": self.app.defaults["geometry_dwell"],
  764. "dwelltime": self.app.defaults["geometry_dwelltime"],
  765. "multidepth": self.app.defaults["geometry_multidepth"],
  766. "ppname_g": self.app.defaults["geometry_ppname_g"],
  767. "depthperpass": self.app.defaults["geometry_depthperpass"],
  768. "extracut": self.app.defaults["geometry_extracut"],
  769. "extracut_length": self.app.defaults["geometry_extracut_length"],
  770. "toolchange": self.app.defaults["geometry_toolchange"],
  771. "toolchangez": self.app.defaults["geometry_toolchangez"],
  772. "endz": self.app.defaults["geometry_endz"],
  773. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  774. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  775. "startz": self.app.defaults["geometry_startz"],
  776. "nccmargin": self.app.defaults["tools_nccmargin"],
  777. "nccmethod": self.app.defaults["tools_nccmethod"],
  778. "nccconnect": self.app.defaults["tools_nccconnect"],
  779. "ncccontour": self.app.defaults["tools_ncccontour"],
  780. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  781. "nccrest": self.app.defaults["tools_nccrest"],
  782. "nccref": self.app.defaults["tools_nccref"],
  783. "nccoffset": self.app.defaults["tools_ncc_offset_choice"],
  784. "nccoffset_value": self.app.defaults["tools_ncc_offset_value"],
  785. }
  786. try:
  787. dias = [float(self.app.defaults["tools_ncctools"])]
  788. except (ValueError, TypeError):
  789. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  790. if not dias:
  791. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  792. return
  793. self.tooluid = 0
  794. self.ncc_tools.clear()
  795. for tool_dia in dias:
  796. self.tooluid += 1
  797. self.ncc_tools.update({
  798. int(self.tooluid): {
  799. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  800. 'offset': 'Path',
  801. 'offset_value': 0.0,
  802. 'type': 'Iso',
  803. 'tool_type': self.tool_type_radio.get_value(),
  804. 'operation': 'clear_op',
  805. 'data': deepcopy(self.default_data),
  806. 'solid_geometry': []
  807. }
  808. })
  809. self.obj_name = ""
  810. self.ncc_obj = None
  811. self.bound_obj_name = ""
  812. self.bound_obj = None
  813. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  814. self.units = self.app.defaults['units'].upper()
  815. def build_ui(self):
  816. self.ui_disconnect()
  817. # updated units
  818. self.units = self.app.defaults['units'].upper()
  819. sorted_tools = []
  820. for k, v in self.ncc_tools.items():
  821. if self.units == "IN":
  822. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  823. else:
  824. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  825. order = self.ncc_order_radio.get_value()
  826. if order == 'fwd':
  827. sorted_tools.sort(reverse=False)
  828. elif order == 'rev':
  829. sorted_tools.sort(reverse=True)
  830. else:
  831. pass
  832. n = len(sorted_tools)
  833. self.tools_table.setRowCount(n)
  834. tool_id = 0
  835. for tool_sorted in sorted_tools:
  836. for tooluid_key, tooluid_value in self.ncc_tools.items():
  837. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  838. tool_id += 1
  839. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  840. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  841. row_no = tool_id - 1
  842. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  843. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  844. # There are no drill bits in MM with more than 2 decimals diameter
  845. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  846. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  847. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  848. tool_type_item = QtWidgets.QComboBox()
  849. for item in self.tool_type_item_options:
  850. tool_type_item.addItem(item)
  851. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  852. idx = tool_type_item.findText(tooluid_value['tool_type'])
  853. tool_type_item.setCurrentIndex(idx)
  854. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  855. operation_type = QtWidgets.QComboBox()
  856. operation_type.addItem('iso_op')
  857. # operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  858. operation_type.addItem('clear_op')
  859. # operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  860. op_idx = operation_type.findText(tooluid_value['operation'])
  861. operation_type.setCurrentIndex(op_idx)
  862. self.tools_table.setItem(row_no, 1, dia) # Diameter
  863. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  864. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  865. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  866. self.tools_table.setCellWidget(row_no, 4, operation_type)
  867. # make the diameter column editable
  868. for row in range(tool_id):
  869. self.tools_table.item(row, 1).setFlags(
  870. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  871. # all the tools are selected by default
  872. self.tools_table.selectColumn(0)
  873. #
  874. self.tools_table.resizeColumnsToContents()
  875. self.tools_table.resizeRowsToContents()
  876. vertical_header = self.tools_table.verticalHeader()
  877. vertical_header.hide()
  878. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  879. horizontal_header = self.tools_table.horizontalHeader()
  880. horizontal_header.setMinimumSectionSize(10)
  881. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  882. horizontal_header.resizeSection(0, 20)
  883. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  884. # self.tools_table.setSortingEnabled(True)
  885. # sort by tool diameter
  886. # self.tools_table.sortItems(1)
  887. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  888. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  889. self.ui_connect()
  890. def ui_connect(self):
  891. self.tools_table.itemChanged.connect(self.on_tool_edit)
  892. for row in range(self.tools_table.rowCount()):
  893. try:
  894. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  895. except AttributeError:
  896. pass
  897. try:
  898. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  899. except AttributeError:
  900. pass
  901. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  902. # first disconnect
  903. for opt in self.form_fields:
  904. current_widget = self.form_fields[opt]
  905. if isinstance(current_widget, FCCheckBox):
  906. try:
  907. current_widget.stateChanged.disconnect()
  908. except (TypeError, ValueError):
  909. pass
  910. if isinstance(current_widget, RadioSet):
  911. try:
  912. current_widget.activated_custom.disconnect()
  913. except (TypeError, ValueError):
  914. pass
  915. elif isinstance(current_widget, FCDoubleSpinner):
  916. try:
  917. current_widget.returnPressed.disconnect()
  918. except (TypeError, ValueError):
  919. pass
  920. # then reconnect
  921. for opt in self.form_fields:
  922. current_widget = self.form_fields[opt]
  923. if isinstance(current_widget, FCCheckBox):
  924. current_widget.stateChanged.connect(self.form_to_storage)
  925. if isinstance(current_widget, RadioSet):
  926. current_widget.activated_custom.connect(self.form_to_storage)
  927. elif isinstance(current_widget, FCDoubleSpinner):
  928. current_widget.returnPressed.connect(self.form_to_storage)
  929. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  930. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  931. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  932. def ui_disconnect(self):
  933. try:
  934. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  935. self.tools_table.itemChanged.disconnect()
  936. except (TypeError, AttributeError):
  937. pass
  938. try:
  939. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  940. self.tool_type_radio.activated_custom.disconnect()
  941. except (TypeError, AttributeError):
  942. pass
  943. for row in range(self.tools_table.rowCount()):
  944. for col in [2, 4]:
  945. try:
  946. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  947. except (TypeError, AttributeError):
  948. pass
  949. for opt in self.form_fields:
  950. current_widget = self.form_fields[opt]
  951. if isinstance(current_widget, FCCheckBox):
  952. try:
  953. current_widget.stateChanged.disconnect()
  954. except (TypeError, ValueError):
  955. pass
  956. if isinstance(current_widget, RadioSet):
  957. try:
  958. current_widget.activated_custom.disconnect()
  959. except (TypeError, ValueError):
  960. pass
  961. elif isinstance(current_widget, FCDoubleSpinner):
  962. try:
  963. current_widget.returnPressed.disconnect()
  964. except (TypeError, ValueError):
  965. pass
  966. def on_combo_box_type(self):
  967. obj_type = self.box_combo_type.currentIndex()
  968. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  969. self.box_combo.setCurrentIndex(0)
  970. def on_toggle_reference(self):
  971. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  972. self.box_combo.hide()
  973. self.box_combo_label.hide()
  974. self.box_combo_type.hide()
  975. self.box_combo_type_label.hide()
  976. else:
  977. self.box_combo.show()
  978. self.box_combo_label.show()
  979. self.box_combo_type.show()
  980. self.box_combo_type_label.show()
  981. def on_offset_choice(self, state):
  982. # if state:
  983. # self.ncc_offset_label.show()
  984. # self.ncc_offset_spinner.show()
  985. # else:
  986. # self.ncc_offset_label.hide()
  987. # self.ncc_offset_spinner.hide()
  988. self.ncc_offset_spinner.setEnabled(state)
  989. def on_order_changed(self, order):
  990. if order != 'no':
  991. self.build_ui()
  992. def on_rest_machining_check(self, state):
  993. if state:
  994. self.ncc_order_radio.set_value('rev')
  995. self.ncc_order_label.setDisabled(True)
  996. self.ncc_order_radio.setDisabled(True)
  997. else:
  998. self.ncc_order_label.setDisabled(False)
  999. self.ncc_order_radio.setDisabled(False)
  1000. def on_tooltable_cellwidget_change(self):
  1001. cw = self.sender()
  1002. cw_index = self.tools_table.indexAt(cw.pos())
  1003. cw_row = cw_index.row()
  1004. cw_col = cw_index.column()
  1005. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1006. # if the sender is in the column with index 2 then we update the tool_type key
  1007. if cw_col == 2:
  1008. tt = cw.currentText()
  1009. typ = 'Iso' if tt == 'V' else "Rough"
  1010. self.ncc_tools[current_uid].update({
  1011. 'type': typ,
  1012. 'tool_type': tt,
  1013. })
  1014. if cw_col == 4:
  1015. op = cw.currentText()
  1016. if op == 'iso_op':
  1017. self.milling_type_label.show()
  1018. self.milling_type_radio.show()
  1019. else:
  1020. self.milling_type_label.hide()
  1021. self.milling_type_radio.hide()
  1022. self.ncc_tools[current_uid].update({
  1023. 'operation': op
  1024. })
  1025. def on_tool_type(self, val):
  1026. if val == 'V':
  1027. self.addtool_entry_lbl.setDisabled(True)
  1028. self.addtool_entry.setDisabled(True)
  1029. self.tipdialabel.show()
  1030. self.tipdia_entry.show()
  1031. self.tipanglelabel.show()
  1032. self.tipangle_entry.show()
  1033. else:
  1034. self.addtool_entry_lbl.setDisabled(False)
  1035. self.addtool_entry.setDisabled(False)
  1036. self.tipdialabel.hide()
  1037. self.tipdia_entry.hide()
  1038. self.tipanglelabel.hide()
  1039. self.tipangle_entry.hide()
  1040. def on_calculate_tooldia(self):
  1041. if self.tool_type_radio.get_value() == 'V':
  1042. tip_dia = float(self.tipdia_entry.get_value())
  1043. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1044. cut_z = float(self.cutz_entry.get_value())
  1045. cut_z = -cut_z if cut_z < 0 else cut_z
  1046. # calculated tool diameter so the cut_z parameter is obeyed
  1047. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1048. # update the default_data so it is used in the ncc_tools dict
  1049. self.default_data.update({
  1050. "vtipdia": tip_dia,
  1051. "vtipangle": (tip_angle * 2),
  1052. })
  1053. self.addtool_entry.set_value(tool_dia)
  1054. return tool_dia
  1055. else:
  1056. return float(self.addtool_entry.get_value())
  1057. def on_tool_add(self, dia=None, muted=None):
  1058. self.blockSignals(True)
  1059. self.units = self.app.defaults['units'].upper()
  1060. if dia:
  1061. tool_dia = dia
  1062. else:
  1063. tool_dia = self.on_calculate_tooldia()
  1064. if tool_dia is None:
  1065. self.build_ui()
  1066. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1067. return
  1068. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1069. if tool_dia == 0:
  1070. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1071. "in Float format."))
  1072. return
  1073. # construct a list of all 'tooluid' in the self.tools
  1074. tool_uid_list = []
  1075. for tooluid_key in self.ncc_tools:
  1076. tool_uid_item = int(tooluid_key)
  1077. tool_uid_list.append(tool_uid_item)
  1078. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1079. if not tool_uid_list:
  1080. max_uid = 0
  1081. else:
  1082. max_uid = max(tool_uid_list)
  1083. self.tooluid = int(max_uid + 1)
  1084. tool_dias = []
  1085. for k, v in self.ncc_tools.items():
  1086. for tool_v in v.keys():
  1087. if tool_v == 'tooldia':
  1088. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1089. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1090. if muted is None:
  1091. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  1092. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1093. self.blockSignals(False)
  1094. return
  1095. else:
  1096. if muted is None:
  1097. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1098. self.ncc_tools.update({
  1099. int(self.tooluid): {
  1100. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1101. 'offset': 'Path',
  1102. 'offset_value': 0.0,
  1103. 'type': 'Iso',
  1104. 'tool_type': self.tool_type_radio.get_value(),
  1105. 'operation': 'clear_op',
  1106. 'data': deepcopy(self.default_data),
  1107. 'solid_geometry': []
  1108. }
  1109. })
  1110. self.blockSignals(False)
  1111. self.build_ui()
  1112. def on_tool_edit(self):
  1113. self.blockSignals(True)
  1114. old_tool_dia = ''
  1115. tool_dias = []
  1116. for k, v in self.ncc_tools.items():
  1117. for tool_v in v.keys():
  1118. if tool_v == 'tooldia':
  1119. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1120. for row in range(self.tools_table.rowCount()):
  1121. try:
  1122. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1123. except ValueError:
  1124. # try to convert comma to decimal point. if it's still not working error message and return
  1125. try:
  1126. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1127. except ValueError:
  1128. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1129. self.blockSignals(False)
  1130. return
  1131. tooluid = int(self.tools_table.item(row, 3).text())
  1132. # identify the tool that was edited and get it's tooluid
  1133. if new_tool_dia not in tool_dias:
  1134. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  1135. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1136. self.blockSignals(False)
  1137. self.build_ui()
  1138. return
  1139. else:
  1140. # identify the old tool_dia and restore the text in tool table
  1141. for k, v in self.ncc_tools.items():
  1142. if k == tooluid:
  1143. old_tool_dia = v['tooldia']
  1144. break
  1145. restore_dia_item = self.tools_table.item(row, 1)
  1146. restore_dia_item.setText(str(old_tool_dia))
  1147. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Edit cancelled. "
  1148. "New diameter value is already in the Tool Table."))
  1149. self.blockSignals(False)
  1150. self.build_ui()
  1151. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1152. """
  1153. Will delete a tool in the tool table
  1154. :param rows_to_delete: which rows to delete; can be a list
  1155. :param all_tools: delete all tools in the tool table
  1156. :return:
  1157. """
  1158. self.blockSignals(True)
  1159. deleted_tools_list = []
  1160. if all_tools:
  1161. self.paint_tools.clear()
  1162. self.blockSignals(False)
  1163. self.build_ui()
  1164. return
  1165. if rows_to_delete:
  1166. try:
  1167. for row in rows_to_delete:
  1168. tooluid_del = int(self.tools_table.item(row, 3).text())
  1169. deleted_tools_list.append(tooluid_del)
  1170. except TypeError:
  1171. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1172. deleted_tools_list.append(tooluid_del)
  1173. for t in deleted_tools_list:
  1174. self.ncc_tools.pop(t, None)
  1175. self.blockSignals(False)
  1176. self.build_ui()
  1177. return
  1178. try:
  1179. if self.tools_table.selectedItems():
  1180. for row_sel in self.tools_table.selectedItems():
  1181. row = row_sel.row()
  1182. if row < 0:
  1183. continue
  1184. tooluid_del = int(self.tools_table.item(row, 3).text())
  1185. deleted_tools_list.append(tooluid_del)
  1186. for t in deleted_tools_list:
  1187. self.ncc_tools.pop(t, None)
  1188. except AttributeError:
  1189. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1190. self.blockSignals(False)
  1191. return
  1192. except Exception as e:
  1193. log.debug(str(e))
  1194. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1195. self.blockSignals(False)
  1196. self.build_ui()
  1197. def on_ncc_click(self):
  1198. """
  1199. Slot for clicking signal of the self.generate.ncc_button
  1200. :return: None
  1201. """
  1202. # init values for the next usage
  1203. self.reset_usage()
  1204. self.app.report_usage("on_paint_button_click")
  1205. self.overlap = float(self.ncc_overlap_entry.get_value()) / 100.0
  1206. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  1207. self.connect = self.ncc_connect_cb.get_value()
  1208. self.contour = self.ncc_contour_cb.get_value()
  1209. self.has_offset = self.ncc_choice_offset_cb.isChecked()
  1210. self.rest = self.ncc_rest_cb.get_value()
  1211. self.obj_name = self.object_combo.currentText()
  1212. # Get source object.
  1213. try:
  1214. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  1215. except Exception as e:
  1216. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1217. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1218. if self.ncc_obj is None:
  1219. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1220. return
  1221. # use the selected tools in the tool table; get diameters for non-copper clear
  1222. self.iso_dia_list = list()
  1223. # use the selected tools in the tool table; get diameters for non-copper clear
  1224. self.ncc_dia_list = list()
  1225. if self.tools_table.selectedItems():
  1226. for x in self.tools_table.selectedItems():
  1227. try:
  1228. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1229. except ValueError:
  1230. # try to convert comma to decimal point. if it's still not working error message and return
  1231. try:
  1232. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1233. except ValueError:
  1234. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  1235. "use a number."))
  1236. continue
  1237. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  1238. self.iso_dia_list.append(self.tooldia)
  1239. else:
  1240. self.ncc_dia_list.append(self.tooldia)
  1241. else:
  1242. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1243. return
  1244. self.o_name = '%s_ncc' % self.obj_name
  1245. self.select_method = self.reference_radio.get_value()
  1246. if self.select_method == 'itself':
  1247. self.bound_obj_name = self.object_combo.currentText()
  1248. # Get source object.
  1249. try:
  1250. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1251. except Exception as e:
  1252. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1253. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  1254. self.clear_copper(ncc_obj=self.ncc_obj,
  1255. ncctooldia=self.ncc_dia_list,
  1256. isotooldia=self.iso_dia_list,
  1257. has_offset=self.has_offset,
  1258. outname=self.o_name,
  1259. overlap=self.overlap,
  1260. connect=self.connect,
  1261. contour=self.contour,
  1262. rest=self.rest)
  1263. elif self.select_method == 'area':
  1264. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1265. if self.app.is_legacy is False:
  1266. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1267. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1268. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1269. else:
  1270. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1271. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1272. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1273. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1274. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1275. elif self.select_method == 'box':
  1276. self.bound_obj_name = self.box_combo.currentText()
  1277. # Get source object.
  1278. try:
  1279. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1280. except Exception as e:
  1281. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1282. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1283. self.clear_copper(ncc_obj=self.ncc_obj,
  1284. sel_obj=self.bound_obj,
  1285. ncctooldia=self.ncc_dia_list,
  1286. isotooldia=self.iso_dia_list,
  1287. has_offset=self.has_offset,
  1288. outname=self.o_name,
  1289. overlap=self.overlap,
  1290. connect=self.connect,
  1291. contour=self.contour,
  1292. rest=self.rest)
  1293. # To be called after clicking on the plot.
  1294. def on_mouse_release(self, event):
  1295. if self.app.is_legacy is False:
  1296. event_pos = event.pos
  1297. # event_is_dragging = event.is_dragging
  1298. right_button = 2
  1299. else:
  1300. event_pos = (event.xdata, event.ydata)
  1301. # event_is_dragging = self.app.plotcanvas.is_dragging
  1302. right_button = 3
  1303. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1304. # do clear area only for left mouse clicks
  1305. if event.button == 1:
  1306. if self.first_click is False:
  1307. self.first_click = True
  1308. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1309. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1310. if self.app.grid_status():
  1311. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1312. else:
  1313. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1314. self.app.delete_selection_shape()
  1315. if self.app.grid_status():
  1316. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1317. else:
  1318. curr_pos = (event_pos[0], event_pos[1])
  1319. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1320. x1, y1 = curr_pos[0], curr_pos[1]
  1321. pt1 = (x0, y0)
  1322. pt2 = (x1, y0)
  1323. pt3 = (x1, y1)
  1324. pt4 = (x0, y1)
  1325. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1326. self.sel_rect.append(new_rectangle)
  1327. # add a temporary shape on canvas
  1328. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1329. self.first_click = False
  1330. return
  1331. elif event.button == right_button and self.mouse_is_dragging is False:
  1332. self.first_click = False
  1333. self.delete_tool_selection_shape()
  1334. if self.app.is_legacy is False:
  1335. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1336. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1337. else:
  1338. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1339. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1340. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1341. self.app.on_mouse_click_over_plot)
  1342. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1343. self.app.on_mouse_move_over_plot)
  1344. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1345. self.app.on_mouse_click_release_over_plot)
  1346. if len(self.sel_rect) == 0:
  1347. return
  1348. self.sel_rect = cascaded_union(self.sel_rect)
  1349. self.clear_copper(ncc_obj=self.ncc_obj,
  1350. sel_obj=self.bound_obj,
  1351. ncctooldia=self.ncc_dia_list,
  1352. isotooldia=self.iso_dia_list,
  1353. has_offset=self.has_offset,
  1354. outname=self.o_name,
  1355. overlap=self.overlap,
  1356. connect=self.connect,
  1357. contour=self.contour,
  1358. rest=self.rest)
  1359. # called on mouse move
  1360. def on_mouse_move(self, event):
  1361. if self.app.is_legacy is False:
  1362. event_pos = event.pos
  1363. event_is_dragging = event.is_dragging
  1364. # right_button = 2
  1365. else:
  1366. event_pos = (event.xdata, event.ydata)
  1367. event_is_dragging = self.app.plotcanvas.is_dragging
  1368. # right_button = 3
  1369. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1370. # detect mouse dragging motion
  1371. if event_is_dragging is True:
  1372. self.mouse_is_dragging = True
  1373. else:
  1374. self.mouse_is_dragging = False
  1375. # update the cursor position
  1376. if self.app.grid_status():
  1377. # Update cursor
  1378. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1379. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1380. symbol='++', edge_color=self.app.cursor_color_3D,
  1381. edge_width=self.app.defaults["global_cursor_width"],
  1382. size=self.app.defaults["global_cursor_size"])
  1383. # update the positions on status bar
  1384. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1385. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1386. if self.cursor_pos is None:
  1387. self.cursor_pos = (0, 0)
  1388. dx = curr_pos[0] - float(self.cursor_pos[0])
  1389. dy = curr_pos[1] - float(self.cursor_pos[1])
  1390. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1391. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1392. # draw the utility geometry
  1393. if self.first_click:
  1394. self.app.delete_selection_shape()
  1395. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1396. coords=(curr_pos[0], curr_pos[1]))
  1397. def clear_copper(self, ncc_obj,
  1398. sel_obj=None,
  1399. ncctooldia=None,
  1400. isotooldia=None,
  1401. outname=None,
  1402. order=None,
  1403. tools_storage=None,
  1404. plot=True,
  1405. run_threaded=True):
  1406. """
  1407. Clear the excess copper from the entire object.
  1408. :param ncc_obj: ncc cleared object
  1409. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1410. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1411. :param outname: name of the resulting object
  1412. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1413. Usage of the different one is related to when this function is called from a TcL command.
  1414. :param plot: if True after the job is finished the result will be plotted, else it will not.
  1415. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1416. run non-threaded for TclShell usage
  1417. :return:
  1418. """
  1419. if run_threaded:
  1420. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1421. else:
  1422. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1423. QtWidgets.QApplication.processEvents()
  1424. # #####################################################################
  1425. # ####### Read the parameters #########################################
  1426. # #####################################################################
  1427. units = self.app.defaults['units']
  1428. order = order if order else self.ncc_order_radio.get_value()
  1429. # determine if to use the progressive plotting
  1430. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1431. prog_plot = True
  1432. else:
  1433. prog_plot = False
  1434. if tools_storage is not None:
  1435. tools_storage = tools_storage
  1436. else:
  1437. tools_storage = self.ncc_tools
  1438. # ######################################################################################################
  1439. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1440. # ######################################################################################################
  1441. sorted_tools = []
  1442. if ncctooldia is not None:
  1443. try:
  1444. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1445. except AttributeError:
  1446. if not isinstance(ncctooldia, list):
  1447. sorted_tools = [float(ncctooldia)]
  1448. else:
  1449. sorted_tools = ncctooldia
  1450. else:
  1451. for row in range(self.tools_table.rowCount()):
  1452. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1453. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1454. # ##############################################################################################################
  1455. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1456. # ##############################################################################################################
  1457. log.debug("NCC Tool. Preparing non-copper polygons.")
  1458. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1459. try:
  1460. if sel_obj is None or sel_obj == 'itself':
  1461. ncc_sel_obj = ncc_obj
  1462. else:
  1463. ncc_sel_obj = sel_obj
  1464. except Exception as e:
  1465. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1466. return 'fail'
  1467. bounding_box = None
  1468. if ncc_select == 'itself':
  1469. geo_n = ncc_sel_obj.solid_geometry
  1470. try:
  1471. if isinstance(geo_n, MultiPolygon):
  1472. env_obj = geo_n.convex_hull
  1473. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1474. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1475. env_obj = cascaded_union(geo_n)
  1476. else:
  1477. env_obj = cascaded_union(geo_n)
  1478. env_obj = env_obj.convex_hull
  1479. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1480. except Exception as e:
  1481. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1482. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1483. return 'fail'
  1484. elif ncc_select == 'area':
  1485. geo_n = cascaded_union(self.sel_rect)
  1486. try:
  1487. __ = iter(geo_n)
  1488. except Exception as e:
  1489. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1490. geo_n = [geo_n]
  1491. geo_buff_list = []
  1492. for poly in geo_n:
  1493. if self.app.abort_flag:
  1494. # graceful abort requested by the user
  1495. raise FlatCAMApp.GracefulException
  1496. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1497. bounding_box = cascaded_union(geo_buff_list)
  1498. elif ncc_select == 'box':
  1499. geo_n = ncc_sel_obj.solid_geometry
  1500. if ncc_sel_obj.kind == 'geometry':
  1501. try:
  1502. __ = iter(geo_n)
  1503. except Exception as e:
  1504. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1505. geo_n = [geo_n]
  1506. geo_buff_list = []
  1507. for poly in geo_n:
  1508. if self.app.abort_flag:
  1509. # graceful abort requested by the user
  1510. raise FlatCAMApp.GracefulException
  1511. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1512. bounding_box = cascaded_union(geo_buff_list)
  1513. elif ncc_sel_obj.kind == 'gerber':
  1514. geo_n = cascaded_union(geo_n).convex_hull
  1515. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1516. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1517. else:
  1518. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1519. return 'fail'
  1520. log.debug("NCC Tool. Finished non-copper polygons.")
  1521. # ########################################################################################################
  1522. # set the name for the future Geometry object
  1523. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1524. # ########################################################################################################
  1525. name = outname if outname is not None else self.obj_name + "_ncc"
  1526. # ##########################################################################################
  1527. # Initializes the new geometry object ######################################################
  1528. # ##########################################################################################
  1529. def gen_clear_area(geo_obj, app_obj):
  1530. assert geo_obj.kind == 'geometry', \
  1531. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1532. # provide the app with a way to process the GUI events when in a blocking loop
  1533. if not run_threaded:
  1534. QtWidgets.QApplication.processEvents()
  1535. log.debug("NCC Tool. Normal copper clearing task started.")
  1536. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1537. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1538. # will store the number of tools for which the isolation is broken
  1539. warning_flag = 0
  1540. if order == 'fwd':
  1541. sorted_tools.sort(reverse=False)
  1542. elif order == 'rev':
  1543. sorted_tools.sort(reverse=True)
  1544. else:
  1545. pass
  1546. cleared_geo = []
  1547. # Already cleared area
  1548. cleared = MultiPolygon()
  1549. # flag for polygons not cleared
  1550. app_obj.poly_not_cleared = False
  1551. # Generate area for each tool
  1552. offset = sum(sorted_tools)
  1553. current_uid = int(1)
  1554. try:
  1555. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1556. except TypeError:
  1557. tool = eval(self.app.defaults["tools_ncctools"])
  1558. # ###################################################################################################
  1559. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1560. # ###################################################################################################
  1561. log.debug("NCC Tool. Calculate 'empty' area.")
  1562. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1563. if ncc_obj.kind == 'gerber' and not isotooldia:
  1564. # unfortunately for this function to work time efficient,
  1565. # if the Gerber was loaded without buffering then it require the buffering now.
  1566. if self.app.defaults['gerber_buffering'] == 'no':
  1567. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1568. else:
  1569. sol_geo = ncc_obj.solid_geometry
  1570. if has_offset is True:
  1571. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1572. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1573. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1574. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1575. if empty == 'fail':
  1576. return 'fail'
  1577. if empty.is_empty:
  1578. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1579. _("Could not get the extent of the area to be non copper cleared."))
  1580. return 'fail'
  1581. elif ncc_obj.kind == 'gerber' and isotooldia:
  1582. isolated_geo = []
  1583. # unfortunately for this function to work time efficient,
  1584. # if the Gerber was loaded without buffering then it require the buffering now.
  1585. if self.app.defaults['gerber_buffering'] == 'no':
  1586. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1587. else:
  1588. self.solid_geometry = ncc_obj.solid_geometry
  1589. # if milling type is climb then the move is counter-clockwise around features
  1590. milling_type = self.milling_type_radio.get_value()
  1591. for tool_iso in isotooldia:
  1592. new_geometry = []
  1593. if milling_type == 'cl':
  1594. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1595. else:
  1596. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1597. if isolated_geo == 'fail':
  1598. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1599. else:
  1600. if ncc_margin < tool_iso:
  1601. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1602. "than isolation tool diameter."))
  1603. try:
  1604. for geo_elem in isolated_geo:
  1605. # provide the app with a way to process the GUI events when in a blocking loop
  1606. QtWidgets.QApplication.processEvents()
  1607. if self.app.abort_flag:
  1608. # graceful abort requested by the user
  1609. raise FlatCAMApp.GracefulException
  1610. if isinstance(geo_elem, Polygon):
  1611. for ring in self.poly2rings(geo_elem):
  1612. new_geo = ring.intersection(bounding_box)
  1613. if new_geo and not new_geo.is_empty:
  1614. new_geometry.append(new_geo)
  1615. elif isinstance(geo_elem, MultiPolygon):
  1616. for poly in geo_elem:
  1617. for ring in self.poly2rings(poly):
  1618. new_geo = ring.intersection(bounding_box)
  1619. if new_geo and not new_geo.is_empty:
  1620. new_geometry.append(new_geo)
  1621. elif isinstance(geo_elem, LineString):
  1622. new_geo = geo_elem.intersection(bounding_box)
  1623. if new_geo:
  1624. if not new_geo.is_empty:
  1625. new_geometry.append(new_geo)
  1626. elif isinstance(geo_elem, MultiLineString):
  1627. for line_elem in geo_elem:
  1628. new_geo = line_elem.intersection(bounding_box)
  1629. if new_geo and not new_geo.is_empty:
  1630. new_geometry.append(new_geo)
  1631. except TypeError:
  1632. if isinstance(isolated_geo, Polygon):
  1633. for ring in self.poly2rings(isolated_geo):
  1634. new_geo = ring.intersection(bounding_box)
  1635. if new_geo:
  1636. if not new_geo.is_empty:
  1637. new_geometry.append(new_geo)
  1638. elif isinstance(isolated_geo, LineString):
  1639. new_geo = isolated_geo.intersection(bounding_box)
  1640. if new_geo and not new_geo.is_empty:
  1641. new_geometry.append(new_geo)
  1642. elif isinstance(isolated_geo, MultiLineString):
  1643. for line_elem in isolated_geo:
  1644. new_geo = line_elem.intersection(bounding_box)
  1645. if new_geo and not new_geo.is_empty:
  1646. new_geometry.append(new_geo)
  1647. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1648. for geo_e in new_geometry:
  1649. if type(geo_e) == MultiLineString:
  1650. warning_flag += 1
  1651. break
  1652. for k, v in tools_storage.items():
  1653. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1654. tool_iso)):
  1655. current_uid = int(k)
  1656. # add the solid_geometry to the current too in self.paint_tools dictionary
  1657. # and then reset the temporary list that stored that solid_geometry
  1658. v['solid_geometry'] = deepcopy(new_geometry)
  1659. v['data']['name'] = name
  1660. break
  1661. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1662. sol_geo = cascaded_union(isolated_geo)
  1663. if has_offset is True:
  1664. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1665. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1666. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1667. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1668. if empty == 'fail':
  1669. return 'fail'
  1670. if empty.is_empty:
  1671. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1672. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  1673. return 'fail'
  1674. elif ncc_obj.kind == 'geometry':
  1675. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1676. if has_offset is True:
  1677. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1678. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1679. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1680. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1681. if empty == 'fail':
  1682. return 'fail'
  1683. if empty.is_empty:
  1684. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1685. _("Could not get the extent of the area to be non copper cleared."))
  1686. return 'fail'
  1687. else:
  1688. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1689. return 'fail'
  1690. if type(empty) is Polygon:
  1691. empty = MultiPolygon([empty])
  1692. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1693. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1694. # COPPER CLEARING #
  1695. cp = None
  1696. for tool in sorted_tools:
  1697. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1698. if self.app.abort_flag:
  1699. # graceful abort requested by the user
  1700. raise FlatCAMApp.GracefulException
  1701. # provide the app with a way to process the GUI events when in a blocking loop
  1702. QtWidgets.QApplication.processEvents()
  1703. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1704. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1705. )
  1706. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1707. cleared_geo[:] = []
  1708. # Get remaining tools offset
  1709. offset -= (tool - 1e-12)
  1710. # Area to clear
  1711. area = empty.buffer(-offset)
  1712. try:
  1713. area = area.difference(cleared)
  1714. except Exception:
  1715. continue
  1716. # Transform area to MultiPolygon
  1717. if type(area) is Polygon:
  1718. area = MultiPolygon([area])
  1719. # variables to display the percentage of work done
  1720. geo_len = len(area.geoms)
  1721. old_disp_number = 0
  1722. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1723. if area.geoms:
  1724. if len(area.geoms) > 0:
  1725. pol_nr = 0
  1726. for p in area.geoms:
  1727. # provide the app with a way to process the GUI events when in a blocking loop
  1728. QtWidgets.QApplication.processEvents()
  1729. if self.app.abort_flag:
  1730. # graceful abort requested by the user
  1731. raise FlatCAMApp.GracefulException
  1732. # clean the polygon
  1733. p = p.buffer(0)
  1734. if p is not None and p.is_valid:
  1735. poly_processed = list()
  1736. try:
  1737. for pol in p:
  1738. if pol is not None and isinstance(pol, Polygon):
  1739. if ncc_method == 'standard':
  1740. cp = self.clear_polygon(pol, tool,
  1741. self.grb_circle_steps,
  1742. overlap=overlap, contour=contour,
  1743. connect=connect,
  1744. prog_plot=prog_plot)
  1745. elif ncc_method == 'seed':
  1746. cp = self.clear_polygon2(pol, tool,
  1747. self.grb_circle_steps,
  1748. overlap=overlap, contour=contour,
  1749. connect=connect,
  1750. prog_plot=prog_plot)
  1751. else:
  1752. cp = self.clear_polygon3(pol, tool,
  1753. self.grb_circle_steps,
  1754. overlap=overlap, contour=contour,
  1755. connect=connect,
  1756. prog_plot=prog_plot)
  1757. if cp:
  1758. cleared_geo += list(cp.get_objects())
  1759. poly_processed.append(True)
  1760. else:
  1761. poly_processed.append(False)
  1762. log.warning("Polygon in MultiPolygon can not be cleared.")
  1763. else:
  1764. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  1765. "It is: %s" % str(type(pol)))
  1766. except TypeError:
  1767. if isinstance(p, Polygon):
  1768. if ncc_method == 'standard':
  1769. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  1770. overlap=overlap, contour=contour, connect=connect,
  1771. prog_plot=prog_plot)
  1772. elif ncc_method == 'seed':
  1773. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  1774. overlap=overlap, contour=contour, connect=connect,
  1775. prog_plot=prog_plot)
  1776. else:
  1777. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  1778. overlap=overlap, contour=contour, connect=connect,
  1779. prog_plot=prog_plot)
  1780. if cp:
  1781. cleared_geo += list(cp.get_objects())
  1782. poly_processed.append(True)
  1783. else:
  1784. poly_processed.append(False)
  1785. log.warning("Polygon can not be cleared.")
  1786. else:
  1787. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  1788. p_cleared = poly_processed.count(True)
  1789. p_not_cleared = poly_processed.count(False)
  1790. if p_not_cleared:
  1791. app_obj.poly_not_cleared = True
  1792. if p_cleared == 0:
  1793. continue
  1794. pol_nr += 1
  1795. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1796. # log.debug("Polygons cleared: %d" % pol_nr)
  1797. if old_disp_number < disp_number <= 100:
  1798. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1799. old_disp_number = disp_number
  1800. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1801. # check if there is a geometry at all in the cleared geometry
  1802. if cleared_geo:
  1803. # Overall cleared area
  1804. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1805. tool / 1.999999)
  1806. # clean-up cleared geo
  1807. cleared = cleared.buffer(0)
  1808. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1809. # solid_geometry
  1810. for k, v in tools_storage.items():
  1811. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1812. tool)):
  1813. current_uid = int(k)
  1814. # add the solid_geometry to the current too in self.paint_tools dictionary
  1815. # and then reset the temporary list that stored that solid_geometry
  1816. v['solid_geometry'] = deepcopy(cleared_geo)
  1817. v['data']['name'] = name
  1818. break
  1819. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1820. else:
  1821. log.debug("There are no geometries in the cleared polygon.")
  1822. # clean the progressive plotted shapes if it was used
  1823. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1824. self.temp_shapes.clear(update=True)
  1825. # # delete tools with empty geometry
  1826. # keys_to_delete = []
  1827. # # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1828. # for uid in tools_storage:
  1829. # # if the solid_geometry (type=list) is empty
  1830. # if not tools_storage[uid]['solid_geometry']:
  1831. # keys_to_delete.append(uid)
  1832. #
  1833. # # actual delete of keys from the tools_storage dict
  1834. # for k in keys_to_delete:
  1835. # tools_storage.pop(k, None)
  1836. # delete tools with empty geometry
  1837. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1838. for uid, uid_val in list(tools_storage.items()):
  1839. try:
  1840. # if the solid_geometry (type=list) is empty
  1841. if not uid_val['solid_geometry']:
  1842. tools_storage.pop(uid, None)
  1843. except KeyError:
  1844. tools_storage.pop(uid, None)
  1845. geo_obj.options["cnctooldia"] = str(tool)
  1846. geo_obj.multigeo = True
  1847. geo_obj.tools.clear()
  1848. geo_obj.tools = dict(tools_storage)
  1849. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1850. has_solid_geo = 0
  1851. for tooluid in geo_obj.tools:
  1852. if geo_obj.tools[tooluid]['solid_geometry']:
  1853. has_solid_geo += 1
  1854. if has_solid_geo == 0:
  1855. app_obj.inform.emit('[ERROR] %s' %
  1856. _("There is no NCC Geometry in the file.\n"
  1857. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1858. "Change the painting parameters and try again."))
  1859. return 'fail'
  1860. # check to see if geo_obj.tools is empty
  1861. # it will be updated only if there is a solid_geometry for tools
  1862. if geo_obj.tools:
  1863. if warning_flag == 0:
  1864. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1865. else:
  1866. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1867. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1868. str(warning_flag),
  1869. _("tools")))
  1870. return
  1871. # create the solid_geometry
  1872. geo_obj.solid_geometry = list()
  1873. for tooluid in geo_obj.tools:
  1874. if geo_obj.tools[tooluid]['solid_geometry']:
  1875. try:
  1876. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1877. geo_obj.solid_geometry.append(geo)
  1878. except TypeError:
  1879. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1880. else:
  1881. # I will use this variable for this purpose although it was meant for something else
  1882. # signal that we have no geo in the object therefore don't create it
  1883. app_obj.poly_not_cleared = False
  1884. return "fail"
  1885. # create the solid_geometry
  1886. # geo_obj.solid_geometry = list()
  1887. # for tooluid in geo_obj.tools:
  1888. # if geo_obj.tools[tooluid]['solid_geometry']:
  1889. # try:
  1890. # for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1891. # geo_obj.solid_geometry.append(geo)
  1892. # except TypeError:
  1893. # geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1894. #
  1895. # # Experimental...
  1896. # # print("Indexing...", end=' ')
  1897. # # geo_obj.make_index()
  1898. # if warning_flag == 0:
  1899. # self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1900. # else:
  1901. # self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1902. # _("NCC Tool clear all done but the copper features isolation is broken for"),
  1903. # str(warning_flag),
  1904. # _("tools")))
  1905. # ###########################################################################################
  1906. # Initializes the new geometry object for the case of the rest-machining ####################
  1907. # ###########################################################################################
  1908. def gen_clear_area_rest(geo_obj, app_obj):
  1909. assert geo_obj.kind == 'geometry', \
  1910. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1911. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1912. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1913. # provide the app with a way to process the GUI events when in a blocking loop
  1914. if not run_threaded:
  1915. QtWidgets.QApplication.processEvents()
  1916. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1917. # will store the number of tools for which the isolation is broken
  1918. warning_flag = 0
  1919. sorted_tools.sort(reverse=True)
  1920. cleared_geo = []
  1921. cleared_by_last_tool = []
  1922. rest_geo = []
  1923. current_uid = 1
  1924. try:
  1925. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1926. except TypeError:
  1927. tool = eval(self.app.defaults["tools_ncctools"])
  1928. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1929. app_obj.poly_not_cleared = True
  1930. log.debug("NCC Tool. Calculate 'empty' area.")
  1931. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1932. # ###################################################################################################
  1933. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1934. # ###################################################################################################
  1935. if ncc_obj.kind == 'gerber' and not isotooldia:
  1936. sol_geo = ncc_obj.solid_geometry
  1937. if has_offset is True:
  1938. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1939. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1940. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1941. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1942. if empty == 'fail':
  1943. return 'fail'
  1944. if empty.is_empty:
  1945. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1946. _("Could not get the extent of the area to be non copper cleared."))
  1947. return 'fail'
  1948. elif ncc_obj.kind == 'gerber' and isotooldia:
  1949. isolated_geo = []
  1950. self.solid_geometry = ncc_obj.solid_geometry
  1951. # if milling type is climb then the move is counter-clockwise around features
  1952. milling_type = self.milling_type_radio.get_value()
  1953. for tool_iso in isotooldia:
  1954. new_geometry = []
  1955. if milling_type == 'cl':
  1956. isolated_geo = self.generate_envelope(tool_iso, 1)
  1957. else:
  1958. isolated_geo = self.generate_envelope(tool_iso, 0)
  1959. if isolated_geo == 'fail':
  1960. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1961. else:
  1962. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1963. "than isolation tool diameter."))
  1964. try:
  1965. for geo_elem in isolated_geo:
  1966. # provide the app with a way to process the GUI events when in a blocking loop
  1967. QtWidgets.QApplication.processEvents()
  1968. if self.app.abort_flag:
  1969. # graceful abort requested by the user
  1970. raise FlatCAMApp.GracefulException
  1971. if isinstance(geo_elem, Polygon):
  1972. for ring in self.poly2rings(geo_elem):
  1973. new_geo = ring.intersection(bounding_box)
  1974. if new_geo and not new_geo.is_empty:
  1975. new_geometry.append(new_geo)
  1976. elif isinstance(geo_elem, MultiPolygon):
  1977. for poly in geo_elem:
  1978. for ring in self.poly2rings(poly):
  1979. new_geo = ring.intersection(bounding_box)
  1980. if new_geo and not new_geo.is_empty:
  1981. new_geometry.append(new_geo)
  1982. elif isinstance(geo_elem, LineString):
  1983. new_geo = geo_elem.intersection(bounding_box)
  1984. if new_geo:
  1985. if not new_geo.is_empty:
  1986. new_geometry.append(new_geo)
  1987. elif isinstance(geo_elem, MultiLineString):
  1988. for line_elem in geo_elem:
  1989. new_geo = line_elem.intersection(bounding_box)
  1990. if new_geo and not new_geo.is_empty:
  1991. new_geometry.append(new_geo)
  1992. except TypeError:
  1993. try:
  1994. if isinstance(isolated_geo, Polygon):
  1995. for ring in self.poly2rings(isolated_geo):
  1996. new_geo = ring.intersection(bounding_box)
  1997. if new_geo:
  1998. if not new_geo.is_empty:
  1999. new_geometry.append(new_geo)
  2000. elif isinstance(isolated_geo, LineString):
  2001. new_geo = isolated_geo.intersection(bounding_box)
  2002. if new_geo and not new_geo.is_empty:
  2003. new_geometry.append(new_geo)
  2004. elif isinstance(isolated_geo, MultiLineString):
  2005. for line_elem in isolated_geo:
  2006. new_geo = line_elem.intersection(bounding_box)
  2007. if new_geo and not new_geo.is_empty:
  2008. new_geometry.append(new_geo)
  2009. except Exception:
  2010. pass
  2011. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2012. for geo_e in new_geometry:
  2013. if type(geo_e) == MultiLineString:
  2014. warning_flag += 1
  2015. break
  2016. for k, v in tools_storage.items():
  2017. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2018. tool_iso)):
  2019. current_uid = int(k)
  2020. # add the solid_geometry to the current too in self.paint_tools dictionary
  2021. # and then reset the temporary list that stored that solid_geometry
  2022. v['solid_geometry'] = deepcopy(new_geometry)
  2023. v['data']['name'] = name
  2024. break
  2025. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2026. sol_geo = cascaded_union(isolated_geo)
  2027. if has_offset is True:
  2028. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2029. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2030. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2031. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2032. if empty == 'fail':
  2033. return 'fail'
  2034. if empty.is_empty:
  2035. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2036. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2037. return 'fail'
  2038. elif ncc_obj.kind == 'geometry':
  2039. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2040. if has_offset is True:
  2041. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2042. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2043. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2044. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2045. if empty == 'fail':
  2046. return 'fail'
  2047. if empty.is_empty:
  2048. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2049. _("Could not get the extent of the area to be non copper cleared."))
  2050. return 'fail'
  2051. else:
  2052. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2053. return
  2054. if self.app.abort_flag:
  2055. # graceful abort requested by the user
  2056. raise FlatCAMApp.GracefulException
  2057. if type(empty) is Polygon:
  2058. empty = MultiPolygon([empty])
  2059. area = empty.buffer(0)
  2060. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2061. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2062. # Generate area for each tool
  2063. while sorted_tools:
  2064. if self.app.abort_flag:
  2065. # graceful abort requested by the user
  2066. raise FlatCAMApp.GracefulException
  2067. tool = sorted_tools.pop(0)
  2068. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2069. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2070. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2071. )
  2072. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2073. tool_used = tool - 1e-12
  2074. cleared_geo[:] = []
  2075. # Area to clear
  2076. for poly in cleared_by_last_tool:
  2077. # provide the app with a way to process the GUI events when in a blocking loop
  2078. QtWidgets.QApplication.processEvents()
  2079. if self.app.abort_flag:
  2080. # graceful abort requested by the user
  2081. raise FlatCAMApp.GracefulException
  2082. try:
  2083. area = area.difference(poly)
  2084. except Exception as e:
  2085. pass
  2086. cleared_by_last_tool[:] = []
  2087. # Transform area to MultiPolygon
  2088. if type(area) is Polygon:
  2089. area = MultiPolygon([area])
  2090. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2091. # and rest_geo it's a list
  2092. allparts = [p.buffer(0) for p in area.geoms]
  2093. allparts += deepcopy(rest_geo)
  2094. rest_geo[:] = []
  2095. area = MultiPolygon(deepcopy(allparts))
  2096. allparts[:] = []
  2097. # variables to display the percentage of work done
  2098. geo_len = len(area.geoms)
  2099. old_disp_number = 0
  2100. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2101. if area.geoms:
  2102. if len(area.geoms) > 0:
  2103. pol_nr = 0
  2104. for p in area.geoms:
  2105. if self.app.abort_flag:
  2106. # graceful abort requested by the user
  2107. raise FlatCAMApp.GracefulException
  2108. # clean the polygon
  2109. p = p.buffer(0)
  2110. if p is not None and p.is_valid:
  2111. # provide the app with a way to process the GUI events when in a blocking loop
  2112. QtWidgets.QApplication.processEvents()
  2113. if isinstance(p, Polygon):
  2114. try:
  2115. if ncc_method == 'standard':
  2116. cp = self.clear_polygon(p, tool_used,
  2117. self.grb_circle_steps,
  2118. overlap=overlap, contour=contour, connect=connect,
  2119. prog_plot=prog_plot)
  2120. elif ncc_method == 'seed':
  2121. cp = self.clear_polygon2(p, tool_used,
  2122. self.grb_circle_steps,
  2123. overlap=overlap, contour=contour, connect=connect,
  2124. prog_plot=prog_plot)
  2125. else:
  2126. cp = self.clear_polygon3(p, tool_used,
  2127. self.grb_circle_steps,
  2128. overlap=overlap, contour=contour, connect=connect,
  2129. prog_plot=prog_plot)
  2130. cleared_geo.append(list(cp.get_objects()))
  2131. except Exception as e:
  2132. log.warning("Polygon can't be cleared. %s" % str(e))
  2133. # this polygon should be added to a list and then try clear it with
  2134. # a smaller tool
  2135. rest_geo.append(p)
  2136. elif isinstance(p, MultiPolygon):
  2137. for poly in p:
  2138. if poly is not None:
  2139. # provide the app with a way to process the GUI events when
  2140. # in a blocking loop
  2141. QtWidgets.QApplication.processEvents()
  2142. try:
  2143. if ncc_method == 'standard':
  2144. cp = self.clear_polygon(poly, tool_used,
  2145. self.grb_circle_steps,
  2146. overlap=overlap, contour=contour,
  2147. connect=connect,
  2148. prog_plot=prog_plot)
  2149. elif ncc_method == 'seed':
  2150. cp = self.clear_polygon2(poly, tool_used,
  2151. self.grb_circle_steps,
  2152. overlap=overlap, contour=contour,
  2153. connect=connect,
  2154. prog_plot=prog_plot)
  2155. else:
  2156. cp = self.clear_polygon3(poly, tool_used,
  2157. self.grb_circle_steps,
  2158. overlap=overlap, contour=contour,
  2159. connect=connect,
  2160. prog_plot=prog_plot)
  2161. cleared_geo.append(list(cp.get_objects()))
  2162. except Exception as e:
  2163. log.warning("Polygon can't be cleared. %s" % str(e))
  2164. # this polygon should be added to a list and then try clear it with
  2165. # a smaller tool
  2166. rest_geo.append(poly)
  2167. pol_nr += 1
  2168. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2169. # log.debug("Polygons cleared: %d" % pol_nr)
  2170. if old_disp_number < disp_number <= 100:
  2171. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2172. old_disp_number = disp_number
  2173. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2174. if self.app.abort_flag:
  2175. # graceful abort requested by the user
  2176. raise FlatCAMApp.GracefulException
  2177. # check if there is a geometry at all in the cleared geometry
  2178. if cleared_geo:
  2179. # Overall cleared area
  2180. cleared_area = list(self.flatten_list(cleared_geo))
  2181. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2182. # for p in cleared_area])
  2183. # here we store the poly's already processed in the original geometry by the current tool
  2184. # into cleared_by_last_tool list
  2185. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2186. # the next tool
  2187. buffer_value = tool_used / 2
  2188. for p in cleared_area:
  2189. if self.app.abort_flag:
  2190. # graceful abort requested by the user
  2191. raise FlatCAMApp.GracefulException
  2192. poly = p.buffer(buffer_value)
  2193. cleared_by_last_tool.append(poly)
  2194. # find the tooluid associated with the current tool_dia so we know
  2195. # where to add the tool solid_geometry
  2196. for k, v in tools_storage.items():
  2197. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2198. tool)):
  2199. current_uid = int(k)
  2200. # add the solid_geometry to the current too in self.paint_tools dictionary
  2201. # and then reset the temporary list that stored that solid_geometry
  2202. v['solid_geometry'] = deepcopy(cleared_area)
  2203. v['data']['name'] = name
  2204. cleared_area[:] = []
  2205. break
  2206. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2207. else:
  2208. log.debug("There are no geometries in the cleared polygon.")
  2209. geo_obj.multigeo = True
  2210. geo_obj.options["cnctooldia"] = str(tool)
  2211. # clean the progressive plotted shapes if it was used
  2212. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  2213. self.temp_shapes.clear(update=True)
  2214. # check to see if geo_obj.tools is empty
  2215. # it will be updated only if there is a solid_geometry for tools
  2216. if geo_obj.tools:
  2217. if warning_flag == 0:
  2218. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2219. else:
  2220. self.app.inform.emit(
  2221. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2222. "isolation is broken for"), str(warning_flag), _("tools")))
  2223. return
  2224. # create the solid_geometry
  2225. geo_obj.solid_geometry = list()
  2226. for tooluid in geo_obj.tools:
  2227. if geo_obj.tools[tooluid]['solid_geometry']:
  2228. try:
  2229. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2230. geo_obj.solid_geometry.append(geo)
  2231. except TypeError:
  2232. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2233. else:
  2234. # I will use this variable for this purpose although it was meant for something else
  2235. # signal that we have no geo in the object therefore don't create it
  2236. app_obj.poly_not_cleared = False
  2237. return "fail"
  2238. # ###########################################################################################
  2239. # Create the Job function and send it to the worker to be processed in another thread #######
  2240. # ###########################################################################################
  2241. def job_thread(app_obj):
  2242. try:
  2243. if rest_machining_choice is True:
  2244. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  2245. else:
  2246. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  2247. except FlatCAMApp.GracefulException:
  2248. if run_threaded:
  2249. proc.done()
  2250. return
  2251. except Exception:
  2252. if run_threaded:
  2253. proc.done()
  2254. traceback.print_stack()
  2255. return
  2256. if run_threaded:
  2257. proc.done()
  2258. else:
  2259. app_obj.proc_container.view.set_idle()
  2260. # focus on Selected Tab
  2261. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2262. if run_threaded:
  2263. # Promise object with the new name
  2264. self.app.collection.promise(name)
  2265. # Background
  2266. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2267. else:
  2268. job_thread(app_obj=self.app)
  2269. def clear_copper_tcl(self, ncc_obj,
  2270. sel_obj=None,
  2271. ncctooldia=None,
  2272. isotooldia=None,
  2273. margin=None,
  2274. has_offset=None,
  2275. offset=None,
  2276. select_method=None,
  2277. outname=None,
  2278. overlap=None,
  2279. connect=None,
  2280. contour=None,
  2281. order=None,
  2282. method=None,
  2283. rest=None,
  2284. tools_storage=None,
  2285. plot=True,
  2286. run_threaded=False):
  2287. """
  2288. Clear the excess copper from the entire object. To be used only in a TCL command.
  2289. :param ncc_obj: ncc cleared object
  2290. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2291. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2292. :param overlap: value by which the paths will overlap
  2293. :param order: if the tools are ordered and how
  2294. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2295. another object
  2296. :param has_offset: True if an offset is needed
  2297. :param offset: distance from the copper features where the copper clearing is stopping
  2298. :param margin: a border around cleared area
  2299. :param outname: name of the resulting object
  2300. :param connect: Connect lines to avoid tool lifts.
  2301. :param contour: Paint around the edges.
  2302. :param method: choice out of 'seed', 'normal', 'lines'
  2303. :param rest: True if to use rest-machining
  2304. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2305. Usage of the different one is related to when this function is called from a TcL command.
  2306. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2307. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  2308. run non-threaded for TclShell usage
  2309. :return:
  2310. """
  2311. if run_threaded:
  2312. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2313. else:
  2314. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2315. QtWidgets.QApplication.processEvents()
  2316. # #####################################################################
  2317. # ####### Read the parameters #########################################
  2318. # #####################################################################
  2319. units = self.app.defaults['units']
  2320. log.debug("NCC Tool started. Reading parameters.")
  2321. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2322. ncc_method = method
  2323. ncc_margin = margin
  2324. ncc_select = select_method
  2325. overlap = overlap
  2326. connect = connect
  2327. contour = contour
  2328. order = order
  2329. if tools_storage is not None:
  2330. tools_storage = tools_storage
  2331. else:
  2332. tools_storage = self.ncc_tools
  2333. ncc_offset = 0.0
  2334. if has_offset is True:
  2335. ncc_offset = offset
  2336. # ######################################################################################################
  2337. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2338. # ######################################################################################################
  2339. sorted_tools = []
  2340. try:
  2341. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2342. except AttributeError:
  2343. if not isinstance(ncctooldia, list):
  2344. sorted_tools = [float(ncctooldia)]
  2345. else:
  2346. sorted_tools = ncctooldia
  2347. # ##############################################################################################################
  2348. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2349. # ##############################################################################################################
  2350. log.debug("NCC Tool. Preparing non-copper polygons.")
  2351. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2352. try:
  2353. if sel_obj is None or sel_obj == 'itself':
  2354. ncc_sel_obj = ncc_obj
  2355. else:
  2356. ncc_sel_obj = sel_obj
  2357. except Exception as e:
  2358. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2359. return 'fail'
  2360. bounding_box = None
  2361. if ncc_select == 'itself':
  2362. geo_n = ncc_sel_obj.solid_geometry
  2363. try:
  2364. if isinstance(geo_n, MultiPolygon):
  2365. env_obj = geo_n.convex_hull
  2366. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2367. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2368. env_obj = cascaded_union(geo_n)
  2369. else:
  2370. env_obj = cascaded_union(geo_n)
  2371. env_obj = env_obj.convex_hull
  2372. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2373. except Exception as e:
  2374. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2375. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2376. return 'fail'
  2377. elif ncc_select == 'area':
  2378. geo_n = cascaded_union(self.sel_rect)
  2379. try:
  2380. __ = iter(geo_n)
  2381. except Exception as e:
  2382. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2383. geo_n = [geo_n]
  2384. geo_buff_list = []
  2385. for poly in geo_n:
  2386. if self.app.abort_flag:
  2387. # graceful abort requested by the user
  2388. raise FlatCAMApp.GracefulException
  2389. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2390. bounding_box = cascaded_union(geo_buff_list)
  2391. elif ncc_select == 'box':
  2392. geo_n = ncc_sel_obj.solid_geometry
  2393. if ncc_sel_obj.kind == 'geometry':
  2394. try:
  2395. __ = iter(geo_n)
  2396. except Exception as e:
  2397. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  2398. geo_n = [geo_n]
  2399. geo_buff_list = []
  2400. for poly in geo_n:
  2401. if self.app.abort_flag:
  2402. # graceful abort requested by the user
  2403. raise FlatCAMApp.GracefulException
  2404. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2405. bounding_box = cascaded_union(geo_buff_list)
  2406. elif ncc_sel_obj.kind == 'gerber':
  2407. geo_n = cascaded_union(geo_n).convex_hull
  2408. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2409. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2410. else:
  2411. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2412. return 'fail'
  2413. log.debug("NCC Tool. Finished non-copper polygons.")
  2414. # ########################################################################################################
  2415. # set the name for the future Geometry object
  2416. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2417. # ########################################################################################################
  2418. rest_machining_choice = rest
  2419. if rest_machining_choice is True:
  2420. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2421. else:
  2422. name = outname if outname is not None else self.obj_name + "_ncc"
  2423. # ##########################################################################################
  2424. # Initializes the new geometry object ######################################################
  2425. # ##########################################################################################
  2426. def gen_clear_area(geo_obj, app_obj):
  2427. assert geo_obj.kind == 'geometry', \
  2428. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2429. # provide the app with a way to process the GUI events when in a blocking loop
  2430. if not run_threaded:
  2431. QtWidgets.QApplication.processEvents()
  2432. log.debug("NCC Tool. Normal copper clearing task started.")
  2433. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2434. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2435. # will store the number of tools for which the isolation is broken
  2436. warning_flag = 0
  2437. if order == 'fwd':
  2438. sorted_tools.sort(reverse=False)
  2439. elif order == 'rev':
  2440. sorted_tools.sort(reverse=True)
  2441. else:
  2442. pass
  2443. cleared_geo = []
  2444. # Already cleared area
  2445. cleared = MultiPolygon()
  2446. # flag for polygons not cleared
  2447. app_obj.poly_not_cleared = False
  2448. # Generate area for each tool
  2449. offset = sum(sorted_tools)
  2450. current_uid = int(1)
  2451. try:
  2452. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2453. except TypeError:
  2454. tool = eval(self.app.defaults["tools_ncctools"])
  2455. # ###################################################################################################
  2456. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2457. # ###################################################################################################
  2458. log.debug("NCC Tool. Calculate 'empty' area.")
  2459. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2460. if ncc_obj.kind == 'gerber' and not isotooldia:
  2461. # unfortunately for this function to work time efficient,
  2462. # if the Gerber was loaded without buffering then it require the buffering now.
  2463. if self.app.defaults['gerber_buffering'] == 'no':
  2464. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2465. else:
  2466. sol_geo = ncc_obj.solid_geometry
  2467. if has_offset is True:
  2468. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2469. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2470. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2471. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2472. if empty == 'fail':
  2473. return 'fail'
  2474. if empty.is_empty:
  2475. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2476. _("Could not get the extent of the area to be non copper cleared."))
  2477. return 'fail'
  2478. elif ncc_obj.kind == 'gerber' and isotooldia:
  2479. isolated_geo = []
  2480. # unfortunately for this function to work time efficient,
  2481. # if the Gerber was loaded without buffering then it require the buffering now.
  2482. if self.app.defaults['gerber_buffering'] == 'no':
  2483. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2484. else:
  2485. self.solid_geometry = ncc_obj.solid_geometry
  2486. # if milling type is climb then the move is counter-clockwise around features
  2487. milling_type = self.app.defaults["tools_nccmilling_type"]
  2488. for tool_iso in isotooldia:
  2489. new_geometry = []
  2490. if milling_type == 'cl':
  2491. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2492. else:
  2493. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2494. if isolated_geo == 'fail':
  2495. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2496. else:
  2497. if ncc_margin < tool_iso:
  2498. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2499. "than isolation tool diameter."))
  2500. try:
  2501. for geo_elem in isolated_geo:
  2502. # provide the app with a way to process the GUI events when in a blocking loop
  2503. QtWidgets.QApplication.processEvents()
  2504. if self.app.abort_flag:
  2505. # graceful abort requested by the user
  2506. raise FlatCAMApp.GracefulException
  2507. if isinstance(geo_elem, Polygon):
  2508. for ring in self.poly2rings(geo_elem):
  2509. new_geo = ring.intersection(bounding_box)
  2510. if new_geo and not new_geo.is_empty:
  2511. new_geometry.append(new_geo)
  2512. elif isinstance(geo_elem, MultiPolygon):
  2513. for poly in geo_elem:
  2514. for ring in self.poly2rings(poly):
  2515. new_geo = ring.intersection(bounding_box)
  2516. if new_geo and not new_geo.is_empty:
  2517. new_geometry.append(new_geo)
  2518. elif isinstance(geo_elem, LineString):
  2519. new_geo = geo_elem.intersection(bounding_box)
  2520. if new_geo:
  2521. if not new_geo.is_empty:
  2522. new_geometry.append(new_geo)
  2523. elif isinstance(geo_elem, MultiLineString):
  2524. for line_elem in geo_elem:
  2525. new_geo = line_elem.intersection(bounding_box)
  2526. if new_geo and not new_geo.is_empty:
  2527. new_geometry.append(new_geo)
  2528. except TypeError:
  2529. if isinstance(isolated_geo, Polygon):
  2530. for ring in self.poly2rings(isolated_geo):
  2531. new_geo = ring.intersection(bounding_box)
  2532. if new_geo:
  2533. if not new_geo.is_empty:
  2534. new_geometry.append(new_geo)
  2535. elif isinstance(isolated_geo, LineString):
  2536. new_geo = isolated_geo.intersection(bounding_box)
  2537. if new_geo and not new_geo.is_empty:
  2538. new_geometry.append(new_geo)
  2539. elif isinstance(isolated_geo, MultiLineString):
  2540. for line_elem in isolated_geo:
  2541. new_geo = line_elem.intersection(bounding_box)
  2542. if new_geo and not new_geo.is_empty:
  2543. new_geometry.append(new_geo)
  2544. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2545. for geo_e in new_geometry:
  2546. if type(geo_e) == MultiLineString:
  2547. warning_flag += 1
  2548. break
  2549. for k, v in tools_storage.items():
  2550. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2551. tool_iso)):
  2552. current_uid = int(k)
  2553. # add the solid_geometry to the current too in self.paint_tools dictionary
  2554. # and then reset the temporary list that stored that solid_geometry
  2555. v['solid_geometry'] = deepcopy(new_geometry)
  2556. v['data']['name'] = name
  2557. break
  2558. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2559. sol_geo = cascaded_union(isolated_geo)
  2560. if has_offset is True:
  2561. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2562. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2563. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2564. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2565. if empty == 'fail':
  2566. return 'fail'
  2567. if empty.is_empty:
  2568. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2569. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2570. return 'fail'
  2571. elif ncc_obj.kind == 'geometry':
  2572. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2573. if has_offset is True:
  2574. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2575. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2576. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2577. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2578. if empty == 'fail':
  2579. return 'fail'
  2580. if empty.is_empty:
  2581. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2582. _("Could not get the extent of the area to be non copper cleared."))
  2583. return 'fail'
  2584. else:
  2585. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2586. return 'fail'
  2587. if type(empty) is Polygon:
  2588. empty = MultiPolygon([empty])
  2589. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2590. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2591. # COPPER CLEARING #
  2592. cp = None
  2593. for tool in sorted_tools:
  2594. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2595. if self.app.abort_flag:
  2596. # graceful abort requested by the user
  2597. raise FlatCAMApp.GracefulException
  2598. # provide the app with a way to process the GUI events when in a blocking loop
  2599. QtWidgets.QApplication.processEvents()
  2600. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2601. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2602. )
  2603. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2604. cleared_geo[:] = []
  2605. # Get remaining tools offset
  2606. offset -= (tool - 1e-12)
  2607. # Area to clear
  2608. area = empty.buffer(-offset)
  2609. try:
  2610. area = area.difference(cleared)
  2611. except Exception:
  2612. continue
  2613. # Transform area to MultiPolygon
  2614. if type(area) is Polygon:
  2615. area = MultiPolygon([area])
  2616. # variables to display the percentage of work done
  2617. geo_len = len(area.geoms)
  2618. old_disp_number = 0
  2619. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2620. if area.geoms:
  2621. if len(area.geoms) > 0:
  2622. pol_nr = 0
  2623. for p in area.geoms:
  2624. # provide the app with a way to process the GUI events when in a blocking loop
  2625. QtWidgets.QApplication.processEvents()
  2626. if self.app.abort_flag:
  2627. # graceful abort requested by the user
  2628. raise FlatCAMApp.GracefulException
  2629. # clean the polygon
  2630. p = p.buffer(0)
  2631. if p is not None and p.is_valid:
  2632. poly_processed = list()
  2633. try:
  2634. for pol in p:
  2635. if pol is not None and isinstance(pol, Polygon):
  2636. if ncc_method == 'standard':
  2637. cp = self.clear_polygon(pol, tool,
  2638. self.grb_circle_steps,
  2639. overlap=overlap, contour=contour,
  2640. connect=connect,
  2641. prog_plot=False)
  2642. elif ncc_method == 'seed':
  2643. cp = self.clear_polygon2(pol, tool,
  2644. self.grb_circle_steps,
  2645. overlap=overlap, contour=contour,
  2646. connect=connect,
  2647. prog_plot=False)
  2648. else:
  2649. cp = self.clear_polygon3(pol, tool,
  2650. self.grb_circle_steps,
  2651. overlap=overlap, contour=contour,
  2652. connect=connect,
  2653. prog_plot=False)
  2654. if cp:
  2655. cleared_geo += list(cp.get_objects())
  2656. poly_processed.append(True)
  2657. else:
  2658. poly_processed.append(False)
  2659. log.warning("Polygon in MultiPolygon can not be cleared.")
  2660. else:
  2661. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2662. "It is: %s" % str(type(pol)))
  2663. except TypeError:
  2664. if isinstance(p, Polygon):
  2665. if ncc_method == 'standard':
  2666. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  2667. overlap=overlap, contour=contour, connect=connect,
  2668. prog_plot=False)
  2669. elif ncc_method == 'seed':
  2670. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  2671. overlap=overlap, contour=contour, connect=connect,
  2672. prog_plot=False)
  2673. else:
  2674. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  2675. overlap=overlap, contour=contour, connect=connect,
  2676. prog_plot=False)
  2677. if cp:
  2678. cleared_geo += list(cp.get_objects())
  2679. poly_processed.append(True)
  2680. else:
  2681. poly_processed.append(False)
  2682. log.warning("Polygon can not be cleared.")
  2683. else:
  2684. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2685. p_cleared = poly_processed.count(True)
  2686. p_not_cleared = poly_processed.count(False)
  2687. if p_not_cleared:
  2688. app_obj.poly_not_cleared = True
  2689. if p_cleared == 0:
  2690. continue
  2691. pol_nr += 1
  2692. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2693. # log.debug("Polygons cleared: %d" % pol_nr)
  2694. if old_disp_number < disp_number <= 100:
  2695. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2696. old_disp_number = disp_number
  2697. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2698. # check if there is a geometry at all in the cleared geometry
  2699. if cleared_geo:
  2700. # Overall cleared area
  2701. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2702. tool / 1.999999)
  2703. # clean-up cleared geo
  2704. cleared = cleared.buffer(0)
  2705. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2706. # solid_geometry
  2707. for k, v in tools_storage.items():
  2708. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2709. tool)):
  2710. current_uid = int(k)
  2711. # add the solid_geometry to the current too in self.paint_tools dictionary
  2712. # and then reset the temporary list that stored that solid_geometry
  2713. v['solid_geometry'] = deepcopy(cleared_geo)
  2714. v['data']['name'] = name
  2715. break
  2716. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2717. else:
  2718. log.debug("There are no geometries in the cleared polygon.")
  2719. # delete tools with empty geometry
  2720. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2721. for uid, uid_val in list(tools_storage.items()):
  2722. try:
  2723. # if the solid_geometry (type=list) is empty
  2724. if not uid_val['solid_geometry']:
  2725. tools_storage.pop(uid, None)
  2726. except KeyError:
  2727. tools_storage.pop(uid, None)
  2728. geo_obj.options["cnctooldia"] = str(tool)
  2729. geo_obj.multigeo = True
  2730. geo_obj.tools.clear()
  2731. geo_obj.tools = dict(tools_storage)
  2732. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2733. has_solid_geo = 0
  2734. for tooluid in geo_obj.tools:
  2735. if geo_obj.tools[tooluid]['solid_geometry']:
  2736. has_solid_geo += 1
  2737. if has_solid_geo == 0:
  2738. app_obj.inform.emit('[ERROR] %s' %
  2739. _("There is no NCC Geometry in the file.\n"
  2740. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2741. "Change the painting parameters and try again."))
  2742. return 'fail'
  2743. # check to see if geo_obj.tools is empty
  2744. # it will be updated only if there is a solid_geometry for tools
  2745. if geo_obj.tools:
  2746. if warning_flag == 0:
  2747. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2748. else:
  2749. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2750. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2751. str(warning_flag),
  2752. _("tools")))
  2753. return
  2754. # create the solid_geometry
  2755. geo_obj.solid_geometry = list()
  2756. for tooluid in geo_obj.tools:
  2757. if geo_obj.tools[tooluid]['solid_geometry']:
  2758. try:
  2759. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2760. geo_obj.solid_geometry.append(geo)
  2761. except TypeError:
  2762. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2763. else:
  2764. # I will use this variable for this purpose although it was meant for something else
  2765. # signal that we have no geo in the object therefore don't create it
  2766. app_obj.poly_not_cleared = False
  2767. return "fail"
  2768. # ###########################################################################################
  2769. # Initializes the new geometry object for the case of the rest-machining ####################
  2770. # ###########################################################################################
  2771. def gen_clear_area_rest(geo_obj, app_obj):
  2772. assert geo_obj.kind == 'geometry', \
  2773. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2774. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2775. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2776. # provide the app with a way to process the GUI events when in a blocking loop
  2777. if not run_threaded:
  2778. QtWidgets.QApplication.processEvents()
  2779. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2780. # will store the number of tools for which the isolation is broken
  2781. warning_flag = 0
  2782. sorted_tools.sort(reverse=True)
  2783. cleared_geo = []
  2784. cleared_by_last_tool = []
  2785. rest_geo = []
  2786. current_uid = 1
  2787. try:
  2788. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2789. except TypeError:
  2790. tool = eval(self.app.defaults["tools_ncctools"])
  2791. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2792. app_obj.poly_not_cleared = True
  2793. log.debug("NCC Tool. Calculate 'empty' area.")
  2794. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2795. # ###################################################################################################
  2796. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2797. # ###################################################################################################
  2798. if ncc_obj.kind == 'gerber' and not isotooldia:
  2799. sol_geo = ncc_obj.solid_geometry
  2800. if has_offset is True:
  2801. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2802. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2803. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2804. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2805. if empty == 'fail':
  2806. return 'fail'
  2807. if empty.is_empty:
  2808. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2809. _("Could not get the extent of the area to be non copper cleared."))
  2810. return 'fail'
  2811. elif ncc_obj.kind == 'gerber' and isotooldia:
  2812. isolated_geo = []
  2813. self.solid_geometry = ncc_obj.solid_geometry
  2814. # if milling type is climb then the move is counter-clockwise around features
  2815. milling_type = self.app.defaults["tools_nccmilling_type"]
  2816. for tool_iso in isotooldia:
  2817. new_geometry = []
  2818. if milling_type == 'cl':
  2819. isolated_geo = self.generate_envelope(tool_iso, 1)
  2820. else:
  2821. isolated_geo = self.generate_envelope(tool_iso, 0)
  2822. if isolated_geo == 'fail':
  2823. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2824. else:
  2825. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2826. "than isolation tool diameter."))
  2827. try:
  2828. for geo_elem in isolated_geo:
  2829. # provide the app with a way to process the GUI events when in a blocking loop
  2830. QtWidgets.QApplication.processEvents()
  2831. if self.app.abort_flag:
  2832. # graceful abort requested by the user
  2833. raise FlatCAMApp.GracefulException
  2834. if isinstance(geo_elem, Polygon):
  2835. for ring in self.poly2rings(geo_elem):
  2836. new_geo = ring.intersection(bounding_box)
  2837. if new_geo and not new_geo.is_empty:
  2838. new_geometry.append(new_geo)
  2839. elif isinstance(geo_elem, MultiPolygon):
  2840. for poly in geo_elem:
  2841. for ring in self.poly2rings(poly):
  2842. new_geo = ring.intersection(bounding_box)
  2843. if new_geo and not new_geo.is_empty:
  2844. new_geometry.append(new_geo)
  2845. elif isinstance(geo_elem, LineString):
  2846. new_geo = geo_elem.intersection(bounding_box)
  2847. if new_geo:
  2848. if not new_geo.is_empty:
  2849. new_geometry.append(new_geo)
  2850. elif isinstance(geo_elem, MultiLineString):
  2851. for line_elem in geo_elem:
  2852. new_geo = line_elem.intersection(bounding_box)
  2853. if new_geo and not new_geo.is_empty:
  2854. new_geometry.append(new_geo)
  2855. except TypeError:
  2856. try:
  2857. if isinstance(isolated_geo, Polygon):
  2858. for ring in self.poly2rings(isolated_geo):
  2859. new_geo = ring.intersection(bounding_box)
  2860. if new_geo:
  2861. if not new_geo.is_empty:
  2862. new_geometry.append(new_geo)
  2863. elif isinstance(isolated_geo, LineString):
  2864. new_geo = isolated_geo.intersection(bounding_box)
  2865. if new_geo and not new_geo.is_empty:
  2866. new_geometry.append(new_geo)
  2867. elif isinstance(isolated_geo, MultiLineString):
  2868. for line_elem in isolated_geo:
  2869. new_geo = line_elem.intersection(bounding_box)
  2870. if new_geo and not new_geo.is_empty:
  2871. new_geometry.append(new_geo)
  2872. except Exception as e:
  2873. pass
  2874. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2875. for geo_e in new_geometry:
  2876. if type(geo_e) == MultiLineString:
  2877. warning_flag += 1
  2878. break
  2879. for k, v in tools_storage.items():
  2880. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2881. tool_iso)):
  2882. current_uid = int(k)
  2883. # add the solid_geometry to the current too in self.paint_tools dictionary
  2884. # and then reset the temporary list that stored that solid_geometry
  2885. v['solid_geometry'] = deepcopy(new_geometry)
  2886. v['data']['name'] = name
  2887. break
  2888. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2889. sol_geo = cascaded_union(isolated_geo)
  2890. if has_offset is True:
  2891. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2892. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2893. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2894. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2895. if empty == 'fail':
  2896. return 'fail'
  2897. if empty.is_empty:
  2898. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2899. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2900. return 'fail'
  2901. elif ncc_obj.kind == 'geometry':
  2902. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2903. if has_offset is True:
  2904. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2905. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2906. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2907. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2908. if empty == 'fail':
  2909. return 'fail'
  2910. if empty.is_empty:
  2911. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2912. _("Could not get the extent of the area to be non copper cleared."))
  2913. return 'fail'
  2914. else:
  2915. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2916. return
  2917. if self.app.abort_flag:
  2918. # graceful abort requested by the user
  2919. raise FlatCAMApp.GracefulException
  2920. if type(empty) is Polygon:
  2921. empty = MultiPolygon([empty])
  2922. area = empty.buffer(0)
  2923. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2924. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2925. # Generate area for each tool
  2926. while sorted_tools:
  2927. if self.app.abort_flag:
  2928. # graceful abort requested by the user
  2929. raise FlatCAMApp.GracefulException
  2930. tool = sorted_tools.pop(0)
  2931. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2932. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2933. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2934. )
  2935. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2936. tool_used = tool - 1e-12
  2937. cleared_geo[:] = []
  2938. # Area to clear
  2939. for poly in cleared_by_last_tool:
  2940. # provide the app with a way to process the GUI events when in a blocking loop
  2941. QtWidgets.QApplication.processEvents()
  2942. if self.app.abort_flag:
  2943. # graceful abort requested by the user
  2944. raise FlatCAMApp.GracefulException
  2945. try:
  2946. area = area.difference(poly)
  2947. except Exception:
  2948. pass
  2949. cleared_by_last_tool[:] = []
  2950. # Transform area to MultiPolygon
  2951. if type(area) is Polygon:
  2952. area = MultiPolygon([area])
  2953. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2954. # and rest_geo it's a list
  2955. allparts = [p.buffer(0) for p in area.geoms]
  2956. allparts += deepcopy(rest_geo)
  2957. rest_geo[:] = []
  2958. area = MultiPolygon(deepcopy(allparts))
  2959. allparts[:] = []
  2960. # variables to display the percentage of work done
  2961. geo_len = len(area.geoms)
  2962. old_disp_number = 0
  2963. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2964. if area.geoms:
  2965. if len(area.geoms) > 0:
  2966. pol_nr = 0
  2967. for p in area.geoms:
  2968. if self.app.abort_flag:
  2969. # graceful abort requested by the user
  2970. raise FlatCAMApp.GracefulException
  2971. # clean the polygon
  2972. p = p.buffer(0)
  2973. if p is not None and p.is_valid:
  2974. # provide the app with a way to process the GUI events when in a blocking loop
  2975. QtWidgets.QApplication.processEvents()
  2976. if isinstance(p, Polygon):
  2977. try:
  2978. if ncc_method == 'standard':
  2979. cp = self.clear_polygon(p, tool_used,
  2980. self.grb_circle_steps,
  2981. overlap=overlap, contour=contour, connect=connect,
  2982. prog_plot=False)
  2983. elif ncc_method == 'seed':
  2984. cp = self.clear_polygon2(p, tool_used,
  2985. self.grb_circle_steps,
  2986. overlap=overlap, contour=contour, connect=connect,
  2987. prog_plot=False)
  2988. else:
  2989. cp = self.clear_polygon3(p, tool_used,
  2990. self.grb_circle_steps,
  2991. overlap=overlap, contour=contour, connect=connect,
  2992. prog_plot=False)
  2993. cleared_geo.append(list(cp.get_objects()))
  2994. except Exception as e:
  2995. log.warning("Polygon can't be cleared. %s" % str(e))
  2996. # this polygon should be added to a list and then try clear it with
  2997. # a smaller tool
  2998. rest_geo.append(p)
  2999. elif isinstance(p, MultiPolygon):
  3000. for poly in p:
  3001. if poly is not None:
  3002. # provide the app with a way to process the GUI events when
  3003. # in a blocking loop
  3004. QtWidgets.QApplication.processEvents()
  3005. try:
  3006. if ncc_method == 'standard':
  3007. cp = self.clear_polygon(poly, tool_used,
  3008. self.grb_circle_steps,
  3009. overlap=overlap, contour=contour,
  3010. connect=connect,
  3011. prog_plot=False)
  3012. elif ncc_method == 'seed':
  3013. cp = self.clear_polygon2(poly, tool_used,
  3014. self.grb_circle_steps,
  3015. overlap=overlap, contour=contour,
  3016. connect=connect,
  3017. prog_plot=False)
  3018. else:
  3019. cp = self.clear_polygon3(poly, tool_used,
  3020. self.grb_circle_steps,
  3021. overlap=overlap, contour=contour,
  3022. connect=connect,
  3023. prog_plot=False)
  3024. cleared_geo.append(list(cp.get_objects()))
  3025. except Exception as e:
  3026. log.warning("Polygon can't be cleared. %s" % str(e))
  3027. # this polygon should be added to a list and then try clear it with
  3028. # a smaller tool
  3029. rest_geo.append(poly)
  3030. pol_nr += 1
  3031. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3032. # log.debug("Polygons cleared: %d" % pol_nr)
  3033. if old_disp_number < disp_number <= 100:
  3034. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3035. old_disp_number = disp_number
  3036. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3037. if self.app.abort_flag:
  3038. # graceful abort requested by the user
  3039. raise FlatCAMApp.GracefulException
  3040. # check if there is a geometry at all in the cleared geometry
  3041. if cleared_geo:
  3042. # Overall cleared area
  3043. cleared_area = list(self.flatten_list(cleared_geo))
  3044. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  3045. # for p in cleared_area])
  3046. # here we store the poly's already processed in the original geometry by the current tool
  3047. # into cleared_by_last_tool list
  3048. # this will be sutracted from the original geometry_to_be_cleared and make data for
  3049. # the next tool
  3050. buffer_value = tool_used / 2
  3051. for p in cleared_area:
  3052. if self.app.abort_flag:
  3053. # graceful abort requested by the user
  3054. raise FlatCAMApp.GracefulException
  3055. poly = p.buffer(buffer_value)
  3056. cleared_by_last_tool.append(poly)
  3057. # find the tooluid associated with the current tool_dia so we know
  3058. # where to add the tool solid_geometry
  3059. for k, v in tools_storage.items():
  3060. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  3061. tool)):
  3062. current_uid = int(k)
  3063. # add the solid_geometry to the current too in self.paint_tools dictionary
  3064. # and then reset the temporary list that stored that solid_geometry
  3065. v['solid_geometry'] = deepcopy(cleared_area)
  3066. v['data']['name'] = name
  3067. cleared_area[:] = []
  3068. break
  3069. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  3070. else:
  3071. log.debug("There are no geometries in the cleared polygon.")
  3072. geo_obj.multigeo = True
  3073. geo_obj.options["cnctooldia"] = str(tool)
  3074. # check to see if geo_obj.tools is empty
  3075. # it will be updated only if there is a solid_geometry for tools
  3076. if geo_obj.tools:
  3077. if warning_flag == 0:
  3078. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  3079. else:
  3080. self.app.inform.emit(
  3081. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  3082. "isolation is broken for"), str(warning_flag), _("tools")))
  3083. return
  3084. # create the solid_geometry
  3085. geo_obj.solid_geometry = list()
  3086. for tooluid in geo_obj.tools:
  3087. if geo_obj.tools[tooluid]['solid_geometry']:
  3088. try:
  3089. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  3090. geo_obj.solid_geometry.append(geo)
  3091. except TypeError:
  3092. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  3093. else:
  3094. # I will use this variable for this purpose although it was meant for something else
  3095. # signal that we have no geo in the object therefore don't create it
  3096. app_obj.poly_not_cleared = False
  3097. return "fail"
  3098. # ###########################################################################################
  3099. # Create the Job function and send it to the worker to be processed in another thread #######
  3100. # ###########################################################################################
  3101. def job_thread(app_obj):
  3102. try:
  3103. if rest_machining_choice is True:
  3104. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  3105. else:
  3106. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  3107. except FlatCAMApp.GracefulException:
  3108. if run_threaded:
  3109. proc.done()
  3110. return
  3111. except Exception:
  3112. if run_threaded:
  3113. proc.done()
  3114. traceback.print_stack()
  3115. return
  3116. if run_threaded:
  3117. proc.done()
  3118. else:
  3119. app_obj.proc_container.view.set_idle()
  3120. # focus on Selected Tab
  3121. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3122. if run_threaded:
  3123. # Promise object with the new name
  3124. self.app.collection.promise(name)
  3125. # Background
  3126. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3127. else:
  3128. job_thread(app_obj=self.app)
  3129. def get_ncc_empty_area(self, target, boundary=None):
  3130. """
  3131. Returns the complement of target geometry within
  3132. the given boundary polygon. If not specified, it defaults to
  3133. the rectangular bounding box of target geometry.
  3134. """
  3135. if isinstance(target, Polygon):
  3136. geo_len = 1
  3137. else:
  3138. geo_len = len(target)
  3139. pol_nr = 0
  3140. old_disp_number = 0
  3141. if boundary is None:
  3142. boundary = target.envelope
  3143. else:
  3144. boundary = boundary
  3145. try:
  3146. ret_val = boundary.difference(target)
  3147. except Exception as e:
  3148. try:
  3149. for el in target:
  3150. # provide the app with a way to process the GUI events when in a blocking loop
  3151. QtWidgets.QApplication.processEvents()
  3152. if self.app.abort_flag:
  3153. # graceful abort requested by the user
  3154. raise FlatCAMApp.GracefulException
  3155. boundary = boundary.difference(el)
  3156. pol_nr += 1
  3157. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3158. if old_disp_number < disp_number <= 100:
  3159. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3160. old_disp_number = disp_number
  3161. return boundary
  3162. except Exception as e:
  3163. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3164. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  3165. "Reload the Gerber file after this change."))
  3166. return 'fail'
  3167. return ret_val
  3168. def reset_fields(self):
  3169. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3170. def reset_usage(self):
  3171. self.obj_name = ""
  3172. self.ncc_obj = None
  3173. self.bound_obj = None
  3174. self.first_click = False
  3175. self.cursor_pos = None
  3176. self.mouse_is_dragging = False
  3177. self.sel_rect = []
  3178. @staticmethod
  3179. def poly2rings(poly):
  3180. return [poly.exterior] + [interior for interior in poly.interiors]
  3181. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  3182. # isolation_geometry produces an envelope that is going on the left of the geometry
  3183. # (the copper features). To leave the least amount of burrs on the features
  3184. # the tool needs to travel on the right side of the features (this is called conventional milling)
  3185. # the first pass is the one cutting all of the features, so it needs to be reversed
  3186. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  3187. # to cut on the right side of the left over copper i.e on the left side of the features.
  3188. try:
  3189. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  3190. except Exception as e:
  3191. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  3192. return 'fail'
  3193. if invert:
  3194. try:
  3195. try:
  3196. pl = []
  3197. for p in geom:
  3198. if p is not None:
  3199. if isinstance(p, Polygon):
  3200. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3201. elif isinstance(p, LinearRing):
  3202. pl.append(Polygon(p.coords[::-1]))
  3203. geom = MultiPolygon(pl)
  3204. except TypeError:
  3205. if isinstance(geom, Polygon) and geom is not None:
  3206. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3207. elif isinstance(geom, LinearRing) and geom is not None:
  3208. geom = Polygon(geom.coords[::-1])
  3209. else:
  3210. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  3211. type(geom))
  3212. except Exception as e:
  3213. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  3214. return 'fail'
  3215. return geom