ToolNCC.py 193 KB

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