ToolNCC.py 182 KB

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