ToolPaint.py 211 KB

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