ToolNonCopperClear.py 181 KB

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