ToolPaint.py 219 KB

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