ToolPaint.py 219 KB

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