ToolPaint.py 211 KB

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