ToolPaint.py 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186
  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
  15. from flatcamGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton
  16. import FlatCAMApp
  17. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing
  18. from shapely.ops import cascaded_union
  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 Rate'))
  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 Rate"))
  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.setObjectName(_("Margin"))
  303. grid4.addWidget(marginlabel, 2, 0)
  304. grid4.addWidget(self.paintmargin_entry, 2, 1)
  305. # Method
  306. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  307. methodlabel.setToolTip(
  308. _("Algorithm for painting:\n"
  309. "- Standard: Fixed step inwards.\n"
  310. "- Seed-based: Outwards from seed.\n"
  311. "- Line-based: Parallel lines.")
  312. )
  313. self.paintmethod_combo = RadioSet([
  314. {"label": _("Standard"), "value": "standard"},
  315. {"label": _("Seed-based"), "value": "seed"},
  316. {"label": _("Straight lines"), "value": "lines"}
  317. ], orientation='vertical', stretch=False)
  318. self.paintmethod_combo.setObjectName(_("Method"))
  319. grid4.addWidget(methodlabel, 3, 0)
  320. grid4.addWidget(self.paintmethod_combo, 3, 1)
  321. # Connect lines
  322. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  323. self.pathconnect_cb.setObjectName(_("Connect"))
  324. self.pathconnect_cb.setToolTip(
  325. _("Draw lines between resulting\n"
  326. "segments to minimize tool lifts.")
  327. )
  328. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  329. self.paintcontour_cb.setObjectName(_("Contour"))
  330. self.paintcontour_cb.setToolTip(
  331. _("Cut around the perimeter of the polygon\n"
  332. "to trim rough edges.")
  333. )
  334. grid4.addWidget(self.pathconnect_cb, 4, 0)
  335. grid4.addWidget(self.paintcontour_cb, 4, 1)
  336. separator_line = QtWidgets.QFrame()
  337. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  338. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  339. grid4.addWidget(separator_line, 5, 0, 1, 2)
  340. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  341. self.apply_param_to_all.setToolTip(
  342. _("The parameters in the current form will be applied\n"
  343. "on all the tools from the Tool Table.")
  344. )
  345. grid4.addWidget(self.apply_param_to_all, 7, 0, 1, 2)
  346. separator_line = QtWidgets.QFrame()
  347. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  348. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  349. grid4.addWidget(separator_line, 8, 0, 1, 2)
  350. # General Parameters
  351. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  352. self.gen_param_label.setToolTip(
  353. _("Parameters that are common for all tools.")
  354. )
  355. grid4.addWidget(self.gen_param_label, 10, 0, 1, 2)
  356. self.rest_cb = FCCheckBox('%s' % _("Rest Machining"))
  357. self.rest_cb.setObjectName(_("Rest Machining"))
  358. self.rest_cb.setToolTip(
  359. _("If checked, use 'rest machining'.\n"
  360. "Basically it will clear copper outside PCB features,\n"
  361. "using the biggest tool and continue with the next tools,\n"
  362. "from bigger to smaller, to clear areas of copper that\n"
  363. "could not be cleared by previous tool, until there is\n"
  364. "no more copper to clear or there are no more tools.\n\n"
  365. "If not checked, use the standard algorithm.")
  366. )
  367. grid4.addWidget(self.rest_cb, 11, 0, 1, 2)
  368. # Polygon selection
  369. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  370. selectlabel.setToolTip(
  371. _("How to select Polygons to be painted.\n"
  372. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  373. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  374. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  375. "- 'All Polygons' - the Paint will start after click.\n"
  376. "- 'Reference Object' - will do non copper clearing within the area\n"
  377. "specified by another object.")
  378. )
  379. # grid3 = QtWidgets.QGridLayout()
  380. self.selectmethod_combo = RadioSet([
  381. {"label": _("Polygon Selection"), "value": "single"},
  382. {"label": _("Area Selection"), "value": "area"},
  383. {"label": _("All Polygons"), "value": "all"},
  384. {"label": _("Reference Object"), "value": "ref"}
  385. ], orientation='vertical', stretch=False)
  386. self.selectmethod_combo.setObjectName(_("Selection"))
  387. self.selectmethod_combo.setToolTip(
  388. _("How to select Polygons to be painted.\n"
  389. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  390. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  391. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  392. "- 'All Polygons' - the Paint will start after click.\n"
  393. "- 'Reference Object' - will do non copper clearing within the area\n"
  394. "specified by another object.")
  395. )
  396. grid4.addWidget(selectlabel, 13, 0, 1, 2)
  397. grid4.addWidget(self.selectmethod_combo, 14, 0, 1, 2)
  398. form1 = QtWidgets.QFormLayout()
  399. grid4.addLayout(form1, 15, 0, 1, 2)
  400. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  401. self.box_combo_type_label.setToolTip(
  402. _("The type of FlatCAM object to be used as paint reference.\n"
  403. "It can be Gerber, Excellon or Geometry.")
  404. )
  405. self.box_combo_type = QtWidgets.QComboBox()
  406. self.box_combo_type.addItem(_("Reference Gerber"))
  407. self.box_combo_type.addItem(_("Reference Excellon"))
  408. self.box_combo_type.addItem(_("Reference Geometry"))
  409. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  410. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  411. self.box_combo_label.setToolTip(
  412. _("The FlatCAM object to be used as non copper clearing reference.")
  413. )
  414. self.box_combo = QtWidgets.QComboBox()
  415. self.box_combo.setModel(self.app.collection)
  416. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  417. self.box_combo.setCurrentIndex(1)
  418. form1.addRow(self.box_combo_label, self.box_combo)
  419. self.box_combo.hide()
  420. self.box_combo_label.hide()
  421. self.box_combo_type.hide()
  422. self.box_combo_type_label.hide()
  423. # GO Button
  424. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  425. self.generate_paint_button.setToolTip(
  426. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  427. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  428. "- 'All Polygons' - the Paint will start after click.\n"
  429. "- 'Reference Object' - will do non copper clearing within the area\n"
  430. "specified by another object.")
  431. )
  432. self.generate_paint_button.setStyleSheet("""
  433. QPushButton
  434. {
  435. font-weight: bold;
  436. }
  437. """)
  438. self.tools_box.addWidget(self.generate_paint_button)
  439. self.tools_box.addStretch()
  440. # ## Reset Tool
  441. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  442. self.reset_button.setToolTip(
  443. _("Will reset the tool parameters.")
  444. )
  445. self.reset_button.setStyleSheet("""
  446. QPushButton
  447. {
  448. font-weight: bold;
  449. }
  450. """)
  451. self.tools_box.addWidget(self.reset_button)
  452. # #################################### FINSIHED GUI ###########################
  453. # #############################################################################
  454. # #############################################################################
  455. # ###################### Setup CONTEXT MENU ###################################
  456. # #############################################################################
  457. self.tools_table.setupContextMenu()
  458. self.tools_table.addContextMenu(
  459. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  460. )
  461. self.tools_table.addContextMenu(
  462. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  463. )
  464. self.tools_table.addContextMenu(
  465. _("Delete"), lambda:
  466. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  467. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  468. )
  469. # #############################################################################
  470. # ########################## VARIABLES ########################################
  471. # #############################################################################
  472. self.obj_name = ""
  473. self.paint_obj = None
  474. self.bound_obj_name = ""
  475. self.bound_obj = None
  476. self.tooldia_list = []
  477. self.sel_rect = None
  478. self.o_name = None
  479. self.overlap = None
  480. self.connect = None
  481. self.contour = None
  482. self.select_method = None
  483. self.units = ''
  484. self.paint_tools = {}
  485. self.tooluid = 0
  486. self.first_click = False
  487. self.cursor_pos = None
  488. self.mouse_is_dragging = False
  489. self.mm = None
  490. self.mp = None
  491. self.mr = None
  492. self.sel_rect = []
  493. # store here if the grid snapping is active
  494. self.grid_status_memory = False
  495. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  496. self.poly_dict = dict()
  497. # store here the default data for Geometry Data
  498. self.default_data = {}
  499. self.default_data.update({
  500. "name": '_paint',
  501. "plot": self.app.defaults["geometry_plot"],
  502. "cutz": self.app.defaults["geometry_cutz"],
  503. "vtipdia": float(self.tipdia_entry.get_value()),
  504. "vtipangle": float(self.tipangle_entry.get_value()),
  505. "travelz": self.app.defaults["geometry_travelz"],
  506. "feedrate": self.app.defaults["geometry_feedrate"],
  507. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  508. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  509. "dwell": self.app.defaults["geometry_dwell"],
  510. "dwelltime": self.app.defaults["geometry_dwelltime"],
  511. "multidepth": self.app.defaults["geometry_multidepth"],
  512. "ppname_g": self.app.defaults["geometry_ppname_g"],
  513. "depthperpass": self.app.defaults["geometry_depthperpass"],
  514. "extracut": self.app.defaults["geometry_extracut"],
  515. "extracut_length": self.app.defaults["geometry_extracut_length"],
  516. "toolchange": self.app.defaults["geometry_toolchange"],
  517. "toolchangez": self.app.defaults["geometry_toolchangez"],
  518. "endz": self.app.defaults["geometry_endz"],
  519. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  520. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  521. "startz": self.app.defaults["geometry_startz"],
  522. "tooldia": self.app.defaults["tools_painttooldia"],
  523. "paintmargin": self.app.defaults["tools_paintmargin"],
  524. "paintmethod": self.app.defaults["tools_paintmethod"],
  525. "selectmethod": self.app.defaults["tools_selectmethod"],
  526. "pathconnect": self.app.defaults["tools_pathconnect"],
  527. "paintcontour": self.app.defaults["tools_paintcontour"],
  528. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  529. "paintrest": self.app.defaults["tools_paintrest"],
  530. })
  531. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  532. self.form_fields = {
  533. "paintoverlap": self.paintoverlap_entry,
  534. "paintmargin": self.paintmargin_entry,
  535. "paintmethod": self.paintmethod_combo,
  536. "pathconnect": self.pathconnect_cb,
  537. "paintcontour": self.paintcontour_cb,
  538. }
  539. self.name2option = {
  540. _('Overlap Rate'): "paintoverlap",
  541. _('Margin'): "paintmargin",
  542. _('Method'): "paintmethod",
  543. _("Connect"): "pathconnect",
  544. _("Contour"): "paintcontour",
  545. }
  546. # #############################################################################
  547. # ################################# Signals ###################################
  548. # #############################################################################
  549. self.addtool_btn.clicked.connect(self.on_tool_add)
  550. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  551. self.deltool_btn.clicked.connect(self.on_tool_delete)
  552. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  553. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  554. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  555. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  556. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  557. self.tools_table.currentItemChanged.connect(self.on_row_selection_change)
  558. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  559. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  560. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  561. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  562. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  563. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  564. self.reset_button.clicked.connect(self.set_tool_ui)
  565. # #############################################################################
  566. # ###################### Setup CONTEXT MENU ###################################
  567. # #############################################################################
  568. self.tools_table.setupContextMenu()
  569. self.tools_table.addContextMenu(
  570. "Add", self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  571. self.tools_table.addContextMenu(
  572. "Delete", lambda:
  573. self.on_tool_delete(rows_to_delete=None, all=None),
  574. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  575. def on_type_obj_index_changed(self, index):
  576. obj_type = self.type_obj_combo.currentIndex()
  577. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  578. self.obj_combo.setCurrentIndex(0)
  579. def install(self, icon=None, separator=None, **kwargs):
  580. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  581. def run(self, toggle=True):
  582. self.app.report_usage("ToolPaint()")
  583. if toggle:
  584. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  585. if self.app.ui.splitter.sizes()[0] == 0:
  586. self.app.ui.splitter.setSizes([1, 1])
  587. else:
  588. try:
  589. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  590. # if tab is populated with the tool but it does not have the focus, focus on it
  591. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  592. # focus on Tool Tab
  593. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  594. else:
  595. self.app.ui.splitter.setSizes([0, 1])
  596. except AttributeError:
  597. pass
  598. else:
  599. if self.app.ui.splitter.sizes()[0] == 0:
  600. self.app.ui.splitter.setSizes([1, 1])
  601. FlatCAMTool.run(self)
  602. self.set_tool_ui()
  603. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  604. def on_row_selection_change(self):
  605. self.update_ui()
  606. def update_ui(self, row=None):
  607. self.blockSignals(True)
  608. if row is None:
  609. try:
  610. current_row = self.tools_table.currentRow()
  611. except Exception:
  612. current_row = 0
  613. else:
  614. current_row = row
  615. if current_row < 0:
  616. current_row = 0
  617. # populate the form with the data from the tool associated with the row parameter
  618. try:
  619. item = self.tools_table.item(current_row, 3)
  620. if item is not None:
  621. tooluid = int(item.text())
  622. else:
  623. return
  624. except Exception as e:
  625. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  626. return
  627. # update the QLabel that shows for which Tool we have the parameters in the UI form
  628. self.tool_data_label.setText(
  629. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), (current_row + 1))
  630. )
  631. try:
  632. # set the form with data from the newly selected tool
  633. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  634. if int(tooluid_key) == tooluid:
  635. for key, value in tooluid_value.items():
  636. if key == 'data':
  637. form_value_storage = tooluid_value[key]
  638. self.storage_to_form(form_value_storage)
  639. except Exception as e:
  640. log.debug("ToolPaint ---> update_ui() " + str(e))
  641. self.blockSignals(False)
  642. def storage_to_form(self, dict_storage):
  643. for form_key in self.form_fields:
  644. for storage_key in dict_storage:
  645. if form_key == storage_key:
  646. try:
  647. self.form_fields[form_key].set_value(dict_storage[form_key])
  648. except Exception:
  649. pass
  650. def form_to_storage(self):
  651. if self.tools_table.rowCount() == 0:
  652. # there is no tool in tool table so we can't save the GUI elements values to storage
  653. return
  654. self.blockSignals(True)
  655. widget_changed = self.sender()
  656. wdg_objname = widget_changed.objectName()
  657. option_changed = self.name2option[wdg_objname]
  658. row = self.tools_table.currentRow()
  659. if row < 0:
  660. row = 0
  661. tooluid_item = int(self.tools_table.item(row, 3).text())
  662. for tooluid_key, tooluid_val in self.paint_tools.items():
  663. if int(tooluid_key) == tooluid_item:
  664. new_option_value = self.form_fields[option_changed].get_value()
  665. if option_changed in tooluid_val:
  666. tooluid_val[option_changed] = new_option_value
  667. if option_changed in tooluid_val['data']:
  668. tooluid_val['data'][option_changed] = new_option_value
  669. self.blockSignals(False)
  670. def on_apply_param_to_all_clicked(self):
  671. if self.tools_table.rowCount() == 0:
  672. # there is no tool in tool table so we can't save the GUI elements values to storage
  673. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  674. return
  675. self.blockSignals(True)
  676. row = self.tools_table.currentRow()
  677. if row < 0:
  678. row = 0
  679. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  680. temp_tools = {}
  681. temp_dia = {}
  682. temp_data = {}
  683. for tooluid_key, tooluid_value in self.paint_tools.items():
  684. for key, value in tooluid_value.items():
  685. if key == 'data':
  686. # update the 'data' section
  687. for data_key in tooluid_value[key].keys():
  688. for form_key, form_value in self.form_fields.items():
  689. if form_key == data_key:
  690. temp_data[data_key] = form_value.get_value()
  691. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  692. # updated from self.app.defaults
  693. if data_key not in self.form_fields:
  694. temp_data[data_key] = value[data_key]
  695. temp_dia[key] = deepcopy(temp_data)
  696. temp_data.clear()
  697. elif key == 'solid_geometry':
  698. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  699. else:
  700. temp_dia[key] = deepcopy(value)
  701. temp_tools[tooluid_key] = deepcopy(temp_dia)
  702. self.paint_tools.clear()
  703. self.paint_tools = deepcopy(temp_tools)
  704. temp_tools.clear()
  705. self.blockSignals(False)
  706. def on_add_tool_by_key(self):
  707. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  708. text='%s:' % _('Enter a Tool Diameter'),
  709. min=0.0000, max=99.9999, decimals=4)
  710. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  711. val, ok = tool_add_popup.get_value()
  712. if ok:
  713. if float(val) == 0:
  714. self.app.inform.emit('[WARNING_NOTCL] %s' %
  715. _("Please enter a tool diameter with non-zero value, in Float format."))
  716. return
  717. self.on_tool_add(dia=float(val))
  718. else:
  719. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  720. def on_tooltable_cellwidget_change(self):
  721. cw = self.sender()
  722. cw_index = self.tools_table.indexAt(cw.pos())
  723. cw_row = cw_index.row()
  724. cw_col = cw_index.column()
  725. current_uid = int(self.tools_table.item(cw_row, 3).text())
  726. # if the sender is in the column with index 2 then we update the tool_type key
  727. if cw_col == 2:
  728. tt = cw.currentText()
  729. typ = 'Iso' if tt == 'V' else "Rough"
  730. self.paint_tools[current_uid].update({
  731. 'type': typ,
  732. 'tool_type': tt,
  733. })
  734. def on_tool_type(self, val):
  735. if val == 'V':
  736. self.addtool_entry_lbl.setDisabled(True)
  737. self.addtool_entry.setDisabled(True)
  738. self.tipdialabel.show()
  739. self.tipdia_entry.show()
  740. self.tipanglelabel.show()
  741. self.tipangle_entry.show()
  742. else:
  743. self.addtool_entry_lbl.setDisabled(False)
  744. self.addtool_entry.setDisabled(False)
  745. self.tipdialabel.hide()
  746. self.tipdia_entry.hide()
  747. self.tipanglelabel.hide()
  748. self.tipangle_entry.hide()
  749. def on_calculate_tooldia(self):
  750. if self.tool_type_radio.get_value() == 'V':
  751. tip_dia = float(self.tipdia_entry.get_value())
  752. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  753. cut_z = float(self.cutz_entry.get_value())
  754. cut_z = -cut_z if cut_z < 0 else cut_z
  755. # calculated tool diameter so the cut_z parameter is obeyed
  756. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  757. # update the default_data so it is used in the ncc_tools dict
  758. self.default_data.update({
  759. "vtipdia": tip_dia,
  760. "vtipangle": (tip_angle * 2),
  761. })
  762. self.addtool_entry.set_value(tool_dia)
  763. return tool_dia
  764. else:
  765. return float(self.addtool_entry.get_value())
  766. def on_radio_selection(self):
  767. if self.selectmethod_combo.get_value() == "ref":
  768. self.box_combo.show()
  769. self.box_combo_label.show()
  770. self.box_combo_type.show()
  771. self.box_combo_type_label.show()
  772. else:
  773. self.box_combo.hide()
  774. self.box_combo_label.hide()
  775. self.box_combo_type.hide()
  776. self.box_combo_type_label.hide()
  777. if self.selectmethod_combo.get_value() == 'single':
  778. # disable rest-machining for single polygon painting
  779. self.rest_cb.set_value(False)
  780. self.rest_cb.setDisabled(True)
  781. if self.selectmethod_combo.get_value() == 'area':
  782. # disable rest-machining for single polygon painting
  783. self.rest_cb.set_value(False)
  784. self.rest_cb.setDisabled(True)
  785. else:
  786. self.rest_cb.setDisabled(False)
  787. self.addtool_entry.setDisabled(False)
  788. self.addtool_btn.setDisabled(False)
  789. self.deltool_btn.setDisabled(False)
  790. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  791. def on_order_changed(self, order):
  792. if order != 'no':
  793. self.build_ui()
  794. def on_rest_machining_check(self, state):
  795. if state:
  796. self.order_radio.set_value('rev')
  797. self.order_label.setDisabled(True)
  798. self.order_radio.setDisabled(True)
  799. else:
  800. self.order_label.setDisabled(False)
  801. self.order_radio.setDisabled(False)
  802. def set_tool_ui(self):
  803. self.tools_frame.show()
  804. self.reset_fields()
  805. # ## Init the GUI interface
  806. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  807. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  808. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  809. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  810. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  811. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  812. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  813. self.cutz_entry.set_value(self.app.defaults["tools_paintcutz"])
  814. self.tool_type_radio.set_value(self.app.defaults["tools_painttool_type"])
  815. self.tipdia_entry.set_value(self.app.defaults["tools_painttipdia"])
  816. self.tipangle_entry.set_value(self.app.defaults["tools_painttipangle"])
  817. self.addtool_entry.set_value(self.app.defaults["tools_paintnewdia"])
  818. self.on_tool_type(val=self.tool_type_radio.get_value())
  819. # make the default object type, "Geometry"
  820. self.type_obj_combo.setCurrentIndex(2)
  821. # updated units
  822. self.units = self.app.defaults['units'].upper()
  823. # set the working variables to a known state
  824. self.paint_tools.clear()
  825. self.tooluid = 0
  826. self.default_data.clear()
  827. self.default_data.update({
  828. "name": '_paint',
  829. "plot": self.app.defaults["geometry_plot"],
  830. "cutz": float(self.app.defaults["geometry_cutz"]),
  831. "vtipdia": float(self.tipdia_entry.get_value()),
  832. "vtipangle": float(self.tipangle_entry.get_value()),
  833. "travelz": float(self.app.defaults["geometry_travelz"]),
  834. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  835. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  836. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  837. "dwell": self.app.defaults["geometry_dwell"],
  838. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  839. "multidepth": self.app.defaults["geometry_multidepth"],
  840. "ppname_g": self.app.defaults["geometry_ppname_g"],
  841. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  842. "extracut": self.app.defaults["geometry_extracut"],
  843. "extracut_length": self.app.defaults["geometry_extracut_length"],
  844. "toolchange": self.app.defaults["geometry_toolchange"],
  845. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  846. "endz": float(self.app.defaults["geometry_endz"]),
  847. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  848. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  849. "startz": self.app.defaults["geometry_startz"],
  850. "tooldia": self.app.defaults["tools_painttooldia"],
  851. "paintmargin": float(self.app.defaults["tools_paintmargin"]),
  852. "paintmethod": self.app.defaults["tools_paintmethod"],
  853. "selectmethod": self.app.defaults["tools_selectmethod"],
  854. "pathconnect": self.app.defaults["tools_pathconnect"],
  855. "paintcontour": self.app.defaults["tools_paintcontour"],
  856. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  857. })
  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. try:
  946. self.tools_table.itemChanged.disconnect()
  947. except TypeError:
  948. pass
  949. if dia:
  950. tool_dia = dia
  951. else:
  952. tool_dia = float(self.addtool_entry.get_value())
  953. if tool_dia is None:
  954. self.build_ui()
  955. self.app.inform.emit('[WARNING_NOTCL] %s' %
  956. _("Please enter a tool diameter to add, in Float format."))
  957. return
  958. # construct a list of all 'tooluid' in the self.tools
  959. tool_uid_list = []
  960. for tooluid_key in self.paint_tools:
  961. tool_uid_item = int(tooluid_key)
  962. tool_uid_list.append(tool_uid_item)
  963. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  964. if not tool_uid_list:
  965. max_uid = 0
  966. else:
  967. max_uid = max(tool_uid_list)
  968. self.tooluid = int(max_uid + 1)
  969. tool_dias = []
  970. for k, v in self.paint_tools.items():
  971. for tool_v in v.keys():
  972. if tool_v == 'tooldia':
  973. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  974. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  975. if muted is None:
  976. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  977. self.tools_table.itemChanged.connect(self.on_tool_edit)
  978. return
  979. else:
  980. if muted is None:
  981. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  982. self.paint_tools.update({
  983. int(self.tooluid): {
  984. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  985. 'offset': 'Path',
  986. 'offset_value': 0.0,
  987. 'type': 'Iso',
  988. 'tool_type': self.tool_type_radio.get_value(),
  989. 'data': dict(self.default_data),
  990. 'solid_geometry': []
  991. }
  992. })
  993. self.build_ui()
  994. def on_tool_edit(self):
  995. old_tool_dia = ''
  996. try:
  997. self.tools_table.itemChanged.disconnect()
  998. except TypeError:
  999. pass
  1000. tool_dias = []
  1001. for k, v in self.paint_tools.items():
  1002. for tool_v in v.keys():
  1003. if tool_v == 'tooldia':
  1004. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1005. for row in range(self.tools_table.rowCount()):
  1006. try:
  1007. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1008. except ValueError:
  1009. # try to convert comma to decimal point. if it's still not working error message and return
  1010. try:
  1011. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1012. except ValueError:
  1013. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1014. _("Wrong value format entered, use a number."))
  1015. return
  1016. tooluid = int(self.tools_table.item(row, 3).text())
  1017. # identify the tool that was edited and get it's tooluid
  1018. if new_tool_dia not in tool_dias:
  1019. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  1020. self.app.inform.emit('[success] %s' %
  1021. _("Tool from Tool Table was edited."))
  1022. self.build_ui()
  1023. return
  1024. else:
  1025. # identify the old tool_dia and restore the text in tool table
  1026. for k, v in self.paint_tools.items():
  1027. if k == tooluid:
  1028. old_tool_dia = v['tooldia']
  1029. break
  1030. restore_dia_item = self.tools_table.item(row, 1)
  1031. restore_dia_item.setText(str(old_tool_dia))
  1032. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1033. _("Edit cancelled. New diameter value is already in the Tool Table."))
  1034. self.build_ui()
  1035. # def on_tool_copy(self, all=None):
  1036. # try:
  1037. # self.tools_table.itemChanged.disconnect()
  1038. # except:
  1039. # pass
  1040. #
  1041. # # find the tool_uid maximum value in the self.tools
  1042. # uid_list = []
  1043. # for key in self.paint_tools:
  1044. # uid_list.append(int(key))
  1045. # try:
  1046. # max_uid = max(uid_list, key=int)
  1047. # except ValueError:
  1048. # max_uid = 0
  1049. #
  1050. # if all is None:
  1051. # if self.tools_table.selectedItems():
  1052. # for current_row in self.tools_table.selectedItems():
  1053. # # sometime the header get selected and it has row number -1
  1054. # # we don't want to do anything with the header :)
  1055. # if current_row.row() < 0:
  1056. # continue
  1057. # try:
  1058. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  1059. # max_uid += 1
  1060. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  1061. # for td in self.paint_tools:
  1062. # print("COPIED", self.paint_tools[td])
  1063. # self.build_ui()
  1064. # except AttributeError:
  1065. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1066. # self.build_ui()
  1067. # return
  1068. # except Exception as e:
  1069. # log.debug("on_tool_copy() --> " + str(e))
  1070. # # deselect the table
  1071. # # self.ui.geo_tools_table.clearSelection()
  1072. # else:
  1073. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1074. # self.build_ui()
  1075. # return
  1076. # else:
  1077. # # we copy all tools in geo_tools_table
  1078. # try:
  1079. # temp_tools = dict(self.paint_tools)
  1080. # max_uid += 1
  1081. # for tooluid in temp_tools:
  1082. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  1083. # temp_tools.clear()
  1084. # self.build_ui()
  1085. # except Exception as e:
  1086. # log.debug("on_tool_copy() --> " + str(e))
  1087. #
  1088. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  1089. def on_tool_delete(self, rows_to_delete=None, all=None):
  1090. try:
  1091. self.tools_table.itemChanged.disconnect()
  1092. except TypeError:
  1093. pass
  1094. deleted_tools_list = []
  1095. if all:
  1096. self.paint_tools.clear()
  1097. self.build_ui()
  1098. return
  1099. if rows_to_delete:
  1100. try:
  1101. for row in rows_to_delete:
  1102. tooluid_del = int(self.tools_table.item(row, 3).text())
  1103. deleted_tools_list.append(tooluid_del)
  1104. except TypeError:
  1105. deleted_tools_list.append(rows_to_delete)
  1106. for t in deleted_tools_list:
  1107. self.paint_tools.pop(t, None)
  1108. self.build_ui()
  1109. return
  1110. try:
  1111. if self.tools_table.selectedItems():
  1112. for row_sel in self.tools_table.selectedItems():
  1113. row = row_sel.row()
  1114. if row < 0:
  1115. continue
  1116. tooluid_del = int(self.tools_table.item(row, 3).text())
  1117. deleted_tools_list.append(tooluid_del)
  1118. for t in deleted_tools_list:
  1119. self.paint_tools.pop(t, None)
  1120. except AttributeError:
  1121. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1122. _("Delete failed. Select a tool to delete."))
  1123. return
  1124. except Exception as e:
  1125. log.debug(str(e))
  1126. self.app.inform.emit('[success] %s' %
  1127. _("Tool(s) deleted from Tool Table."))
  1128. self.build_ui()
  1129. def on_paint_button_click(self):
  1130. # init values for the next usage
  1131. self.reset_usage()
  1132. self.app.report_usage("on_paint_button_click")
  1133. # self.app.call_source = 'paint'
  1134. # #####################################################
  1135. # ######### Reading Parameters ########################
  1136. # #####################################################
  1137. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  1138. self.overlap = float(self.paintoverlap_entry.get_value()) / 100.0
  1139. self.connect = self.pathconnect_cb.get_value()
  1140. self.contour = self.paintcontour_cb.get_value()
  1141. self.select_method = self.selectmethod_combo.get_value()
  1142. self.obj_name = self.obj_combo.currentText()
  1143. # Get source object.
  1144. try:
  1145. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  1146. except Exception as e:
  1147. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1148. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1149. (_("Could not retrieve object: %s"),
  1150. self.obj_name))
  1151. return
  1152. if self.paint_obj is None:
  1153. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  1154. (_("Object not found"),
  1155. self.paint_obj))
  1156. return
  1157. # test if the Geometry Object is multigeo and return Fail if True because
  1158. # for now Paint don't work on MultiGeo
  1159. if self.paint_obj.multigeo is True:
  1160. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  1161. _("Can't do Paint on MultiGeo geometries"))
  1162. return 'Fail'
  1163. o_name = '%s_multitool_paint' % self.obj_name
  1164. # use the selected tools in the tool table; get diameters
  1165. self.tooldia_list = list()
  1166. if self.tools_table.selectedItems():
  1167. for x in self.tools_table.selectedItems():
  1168. try:
  1169. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1170. except ValueError:
  1171. # try to convert comma to decimal point. if it's still not working error message and return
  1172. try:
  1173. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1174. except ValueError:
  1175. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1176. _("Wrong value format entered, use a number."))
  1177. continue
  1178. self.tooldia_list.append(self.tooldia)
  1179. else:
  1180. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1181. return
  1182. if self.select_method == "all":
  1183. self.paint_poly_all(self.paint_obj,
  1184. tooldia=self.tooldia_list,
  1185. outname=self.o_name,
  1186. overlap=self.overlap,
  1187. connect=self.connect,
  1188. contour=self.contour)
  1189. elif self.select_method == "single":
  1190. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  1191. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1192. if self.app.ui.grid_snap_btn.isChecked():
  1193. self.grid_status_memory = True
  1194. self.app.ui.grid_snap_btn.trigger()
  1195. else:
  1196. self.grid_status_memory = False
  1197. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  1198. if self.app.is_legacy is False:
  1199. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1200. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1201. else:
  1202. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1203. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1204. elif self.select_method == "area":
  1205. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  1206. if self.app.is_legacy is False:
  1207. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1208. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1209. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1210. else:
  1211. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1212. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1213. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1214. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1215. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1216. elif self.select_method == 'ref':
  1217. self.bound_obj_name = self.box_combo.currentText()
  1218. # Get source object.
  1219. try:
  1220. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1221. except Exception as e:
  1222. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  1223. return "Could not retrieve object: %s" % self.obj_name
  1224. self.paint_poly_ref(obj=self.paint_obj,
  1225. sel_obj=self.bound_obj,
  1226. tooldia=self.tooldia_list,
  1227. overlap=self.overlap,
  1228. outname=self.o_name,
  1229. connect=self.connect,
  1230. contour=self.contour)
  1231. # To be called after clicking on the plot.
  1232. def on_single_poly_mouse_release(self, event):
  1233. if self.app.is_legacy is False:
  1234. event_pos = event.pos
  1235. right_button = 2
  1236. event_is_dragging = self.app.event_is_dragging
  1237. else:
  1238. event_pos = (event.xdata, event.ydata)
  1239. right_button = 3
  1240. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1241. try:
  1242. x = float(event_pos[0])
  1243. y = float(event_pos[1])
  1244. except TypeError:
  1245. return
  1246. event_pos = (x, y)
  1247. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1248. # do paint single only for left mouse clicks
  1249. if event.button == 1:
  1250. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  1251. if clicked_poly:
  1252. if clicked_poly not in self.poly_dict.values():
  1253. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  1254. layer=0,
  1255. shape=clicked_poly,
  1256. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1257. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1258. visible=True)
  1259. self.poly_dict[shape_id] = clicked_poly
  1260. self.app.inform.emit(
  1261. '%s: %d. %s' % (_("Added polygon"),
  1262. int(len(self.poly_dict)),
  1263. _("Click to add next polygon or right click to start painting."))
  1264. )
  1265. else:
  1266. try:
  1267. for k, v in list(self.poly_dict.items()):
  1268. if v == clicked_poly:
  1269. self.app.tool_shapes.remove(k)
  1270. self.poly_dict.pop(k)
  1271. break
  1272. except TypeError:
  1273. return
  1274. self.app.inform.emit(
  1275. '%s. %s' % (_("Removed polygon"),
  1276. _("Click to add/remove next polygon or right click to start painting."))
  1277. )
  1278. self.app.tool_shapes.redraw()
  1279. else:
  1280. self.app.inform.emit(_("No polygon detected under click position."))
  1281. elif event.button == right_button and event_is_dragging is False:
  1282. # restore the Grid snapping if it was active before
  1283. if self.grid_status_memory is True:
  1284. self.app.ui.grid_snap_btn.trigger()
  1285. if self.app.is_legacy is False:
  1286. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1287. else:
  1288. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1289. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1290. self.app.on_mouse_click_over_plot)
  1291. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1292. self.app.on_mouse_click_release_over_plot)
  1293. self.app.tool_shapes.clear(update=True)
  1294. if self.poly_dict:
  1295. poly_list = deepcopy(list(self.poly_dict.values()))
  1296. self.paint_poly(self.paint_obj,
  1297. poly_list=poly_list,
  1298. tooldia=self.tooldia_list,
  1299. overlap=self.overlap,
  1300. connect=self.connect,
  1301. contour=self.contour)
  1302. self.poly_dict.clear()
  1303. else:
  1304. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1305. # To be called after clicking on the plot.
  1306. def on_mouse_release(self, event):
  1307. if self.app.is_legacy is False:
  1308. event_pos = event.pos
  1309. event_is_dragging = event.is_dragging
  1310. right_button = 2
  1311. else:
  1312. event_pos = (event.xdata, event.ydata)
  1313. event_is_dragging = self.app.plotcanvas.is_dragging
  1314. right_button = 3
  1315. try:
  1316. x = float(event_pos[0])
  1317. y = float(event_pos[1])
  1318. except TypeError:
  1319. return
  1320. event_pos = (x, y)
  1321. # do paint single only for left mouse clicks
  1322. if event.button == 1:
  1323. if not self.first_click:
  1324. self.first_click = True
  1325. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1326. _("Click the end point of the paint area."))
  1327. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1328. if self.app.grid_status() == True:
  1329. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  1330. else:
  1331. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1332. self.app.delete_selection_shape()
  1333. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1334. if self.app.grid_status() == True:
  1335. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1336. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1337. x1, y1 = curr_pos[0], curr_pos[1]
  1338. pt1 = (x0, y0)
  1339. pt2 = (x1, y0)
  1340. pt3 = (x1, y1)
  1341. pt4 = (x0, y1)
  1342. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1343. self.sel_rect.append(new_rectangle)
  1344. # add a temporary shape on canvas
  1345. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1346. self.first_click = False
  1347. return
  1348. elif event.button == right_button and self.mouse_is_dragging is False:
  1349. self.first_click = False
  1350. self.delete_tool_selection_shape()
  1351. if self.app.is_legacy is False:
  1352. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1353. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1354. else:
  1355. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1356. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1357. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1358. self.app.on_mouse_click_over_plot)
  1359. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1360. self.app.on_mouse_move_over_plot)
  1361. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1362. self.app.on_mouse_click_release_over_plot)
  1363. if len(self.sel_rect) == 0:
  1364. return
  1365. self.sel_rect = cascaded_union(self.sel_rect)
  1366. self.paint_poly_area(obj=self.paint_obj,
  1367. tooldia=self.tooldia_list,
  1368. sel_obj=self.sel_rect,
  1369. outname=self.o_name,
  1370. overlap=self.overlap,
  1371. connect=self.connect,
  1372. contour=self.contour)
  1373. # called on mouse move
  1374. def on_mouse_move(self, event):
  1375. if self.app.is_legacy is False:
  1376. event_pos = event.pos
  1377. event_is_dragging = event.is_dragging
  1378. right_button = 2
  1379. else:
  1380. event_pos = (event.xdata, event.ydata)
  1381. event_is_dragging = self.app.plotcanvas.is_dragging
  1382. right_button = 3
  1383. try:
  1384. x = float(event_pos[0])
  1385. y = float(event_pos[1])
  1386. except TypeError:
  1387. return
  1388. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1389. # detect mouse dragging motion
  1390. if event_is_dragging == 1:
  1391. self.mouse_is_dragging = True
  1392. else:
  1393. self.mouse_is_dragging = False
  1394. # update the cursor position
  1395. if self.app.grid_status() == True:
  1396. # Update cursor
  1397. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1398. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1399. symbol='++', edge_color=self.app.cursor_color_3D,
  1400. edge_width=self.app.defaults["global_cursor_width"],
  1401. size=self.app.defaults["global_cursor_size"])
  1402. # update the positions on status bar
  1403. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1404. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1405. if self.cursor_pos is None:
  1406. self.cursor_pos = (0, 0)
  1407. dx = curr_pos[0] - float(self.cursor_pos[0])
  1408. dy = curr_pos[1] - float(self.cursor_pos[1])
  1409. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1410. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1411. # draw the utility geometry
  1412. if self.first_click:
  1413. self.app.delete_selection_shape()
  1414. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1415. coords=(curr_pos[0], curr_pos[1]))
  1416. def paint_poly(self, obj,
  1417. inside_pt=None,
  1418. poly_list=None,
  1419. tooldia=None,
  1420. overlap=None,
  1421. order=None,
  1422. margin=None,
  1423. method=None,
  1424. outname=None,
  1425. connect=None,
  1426. contour=None,
  1427. tools_storage=None,
  1428. plot=True,
  1429. run_threaded=True):
  1430. """
  1431. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1432. Note:
  1433. * The margin is taken directly from the form.
  1434. :param obj: painted object
  1435. :param inside_pt: [x, y]
  1436. :param tooldia: Diameter of the painting tool
  1437. :param overlap: Overlap of the tool between passes.
  1438. :param order: if the tools are ordered and how
  1439. :param margin: a border around painting area
  1440. :param outname: Name of the resulting Geometry Object.
  1441. :param connect: Connect lines to avoid tool lifts.
  1442. :param contour: Paint around the edges.
  1443. :param method: choice out of 'seed', 'normal', 'lines'
  1444. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1445. Usage of the different one is related to when this function is called from a TcL command.
  1446. :return: None
  1447. """
  1448. if isinstance(obj, FlatCAMGerber):
  1449. if self.app.defaults["gerber_buffering"] == 'no':
  1450. self.app.inform.emit('%s %s %s' %
  1451. (_("Paint Tool."), _("Normal painting polygon task started."),
  1452. _("Buffering geometry...")))
  1453. else:
  1454. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1455. else:
  1456. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1457. if isinstance(obj, FlatCAMGerber):
  1458. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1459. if isinstance(obj.solid_geometry, list):
  1460. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1461. else:
  1462. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1463. polygon_list = None
  1464. if inside_pt and poly_list is None:
  1465. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1466. elif inside_pt is None and poly_list:
  1467. polygon_list = poly_list
  1468. # No polygon?
  1469. if polygon_list is None:
  1470. self.app.log.warning('No polygon found.')
  1471. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1472. return
  1473. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1474. paint_margin = float(self.paintmargin_entry.get_value()) if margin is None else margin
  1475. # determine if to use the progressive plotting
  1476. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1477. name = outname if outname is not None else self.obj_name + "_paint"
  1478. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1479. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1480. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1481. order = order if order is not None else self.order_radio.get_value()
  1482. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1483. sorted_tools = []
  1484. if tooldia is not None:
  1485. try:
  1486. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1487. except AttributeError:
  1488. if not isinstance(tooldia, list):
  1489. sorted_tools = [float(tooldia)]
  1490. else:
  1491. sorted_tools = tooldia
  1492. else:
  1493. for row in range(self.tools_table.rowCount()):
  1494. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1495. # sort the tools if we have an order selected in the UI
  1496. if order == 'fwd':
  1497. sorted_tools.sort(reverse=False)
  1498. elif order == 'rev':
  1499. sorted_tools.sort(reverse=True)
  1500. proc = self.app.proc_container.new(_("Painting polygon..."))
  1501. # Initializes the new geometry object
  1502. def gen_paintarea(geo_obj, app_obj):
  1503. geo_obj.solid_geometry = list()
  1504. def paint_p(polyg, tooldiameter):
  1505. cpoly = None
  1506. try:
  1507. if paint_method == "seed":
  1508. # Type(cp) == FlatCAMRTreeStorage | None
  1509. cpoly = self.clear_polygon2(polyg,
  1510. tooldia=tooldiameter,
  1511. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1512. overlap=over,
  1513. contour=cont,
  1514. connect=conn,
  1515. prog_plot=prog_plot)
  1516. elif paint_method == "lines":
  1517. # Type(cp) == FlatCAMRTreeStorage | None
  1518. cpoly = self.clear_polygon3(polyg,
  1519. tooldia=tooldiameter,
  1520. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1521. overlap=over,
  1522. contour=cont,
  1523. connect=conn,
  1524. prog_plot=prog_plot)
  1525. else:
  1526. # Type(cp) == FlatCAMRTreeStorage | None
  1527. cpoly = self.clear_polygon(polyg,
  1528. tooldia=tooldiameter,
  1529. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1530. overlap=over,
  1531. contour=cont,
  1532. connect=conn,
  1533. prog_plot=prog_plot)
  1534. except FlatCAMApp.GracefulException:
  1535. return "fail"
  1536. except Exception as e:
  1537. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1538. if cpoly is not None:
  1539. geo_obj.solid_geometry += list(cpoly.get_objects())
  1540. return cpoly
  1541. else:
  1542. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1543. return None
  1544. current_uid = int(1)
  1545. tool_dia = None
  1546. for tool_dia in sorted_tools:
  1547. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1548. for k, v in tools_storage.items():
  1549. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1550. current_uid = int(k)
  1551. break
  1552. try:
  1553. poly_buf = [pol.buffer(-paint_margin) for pol in polygon_list]
  1554. cp = list()
  1555. try:
  1556. for pp in poly_buf:
  1557. cp.append(paint_p(pp, tooldiameter=tool_dia))
  1558. except TypeError:
  1559. cp = paint_p(poly_buf, tooldiameter=tool_dia)
  1560. total_geometry = list()
  1561. if cp:
  1562. try:
  1563. for x in cp:
  1564. total_geometry += list(x.get_objects())
  1565. except TypeError:
  1566. total_geometry = list(cp.get_objects())
  1567. except FlatCAMApp.GracefulException:
  1568. return "fail"
  1569. except Exception as e:
  1570. log.debug("Could not Paint the polygons. %s" % str(e))
  1571. app_obj.inform.emit('[ERROR] %s\n%s' %
  1572. (_("Could not do Paint. Try a different combination of parameters. "
  1573. "Or a different strategy of paint"),
  1574. str(e)
  1575. )
  1576. )
  1577. return "fail"
  1578. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1579. # dictionary and then reset the temporary list that stored that solid_geometry
  1580. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1581. tools_storage[current_uid]['data']['name'] = name
  1582. # clean the progressive plotted shapes if it was used
  1583. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1584. self.temp_shapes.clear(update=True)
  1585. # delete tools with empty geometry
  1586. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1587. for uid in list(tools_storage.keys()):
  1588. # if the solid_geometry (type=list) is empty
  1589. if not tools_storage[uid]['solid_geometry']:
  1590. tools_storage.pop(uid, None)
  1591. geo_obj.options["cnctooldia"] = str(tool_dia)
  1592. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1593. geo_obj.multigeo = True
  1594. geo_obj.multitool = True
  1595. geo_obj.tools.clear()
  1596. geo_obj.tools = dict(tools_storage)
  1597. geo_obj.solid_geometry = cascaded_union(tools_storage[current_uid]['solid_geometry'])
  1598. try:
  1599. a, b, c, d = geo_obj.solid_geometry.bounds
  1600. geo_obj.options['xmin'] = a
  1601. geo_obj.options['ymin'] = b
  1602. geo_obj.options['xmax'] = c
  1603. geo_obj.options['ymax'] = d
  1604. except Exception as e:
  1605. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1606. return
  1607. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1608. has_solid_geo = 0
  1609. for tooluid in geo_obj.tools:
  1610. if geo_obj.tools[tooluid]['solid_geometry']:
  1611. has_solid_geo += 1
  1612. if has_solid_geo == 0:
  1613. self.app.inform.emit('[ERROR] %s' %
  1614. _("There is no Painting Geometry in the file.\n"
  1615. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1616. "Change the painting parameters and try again."))
  1617. return
  1618. total_geometry[:] = []
  1619. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1620. # Experimental...
  1621. # print("Indexing...", end=' ')
  1622. # geo_obj.make_index()
  1623. # if errors == 0:
  1624. # print("[success] Paint single polygon Done")
  1625. # self.app.inform.emit("[success] Paint single polygon Done")
  1626. # else:
  1627. # print("[WARNING] Paint single polygon done with errors")
  1628. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1629. # "%d area(s) could not be painted.\n"
  1630. # "Use different paint parameters or edit the paint geometry and correct"
  1631. # "the issue."
  1632. # % errors)
  1633. def job_thread(app_obj):
  1634. try:
  1635. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1636. except FlatCAMApp.GracefulException:
  1637. proc.done()
  1638. return
  1639. except Exception as e:
  1640. proc.done()
  1641. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1642. ('PaintTool.paint_poly()',
  1643. str(e)))
  1644. return
  1645. proc.done()
  1646. # focus on Selected Tab
  1647. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1648. self.app.inform.emit(_("Polygon Paint started ..."))
  1649. # Promise object with the new name
  1650. self.app.collection.promise(name)
  1651. if run_threaded:
  1652. # Background
  1653. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1654. else:
  1655. job_thread(app_obj=self.app)
  1656. def paint_poly_all(self, obj,
  1657. tooldia=None,
  1658. overlap=None,
  1659. order=None,
  1660. margin=None,
  1661. method=None,
  1662. outname=None,
  1663. connect=None,
  1664. contour=None,
  1665. tools_storage=None,
  1666. plot=True,
  1667. run_threaded=True):
  1668. """
  1669. Paints all polygons in this object.
  1670. :param obj: painted object
  1671. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1672. :param overlap: value by which the paths will overlap
  1673. :param order: if the tools are ordered and how
  1674. :param margin: a border around painting area
  1675. :param outname: name of the resulting object
  1676. :param connect: Connect lines to avoid tool lifts.
  1677. :param contour: Paint around the edges.
  1678. :param method: choice out of 'seed', 'normal', 'lines'
  1679. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1680. Usage of the different one is related to when this function is called from a TcL command.
  1681. :return:
  1682. """
  1683. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1684. if margin is not None:
  1685. paint_margin = margin
  1686. else:
  1687. paint_margin = float(self.paintmargin_entry.get_value())
  1688. # determine if to use the progressive plotting
  1689. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1690. prog_plot = True
  1691. else:
  1692. prog_plot = False
  1693. proc = self.app.proc_container.new(_("Painting polygons..."))
  1694. name = outname if outname is not None else self.obj_name + "_paint"
  1695. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1696. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1697. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1698. order = order if order is not None else self.order_radio.get_value()
  1699. sorted_tools = []
  1700. if tooldia is not None:
  1701. try:
  1702. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1703. except AttributeError:
  1704. if not isinstance(tooldia, list):
  1705. sorted_tools = [float(tooldia)]
  1706. else:
  1707. sorted_tools = tooldia
  1708. else:
  1709. for row in range(self.tools_table.rowCount()):
  1710. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1711. if tools_storage is not None:
  1712. tools_storage = tools_storage
  1713. else:
  1714. tools_storage = self.paint_tools
  1715. # This is a recursive generator of individual Polygons.
  1716. # Note: Double check correct implementation. Might exit
  1717. # early if it finds something that is not a Polygon?
  1718. # def recurse(geo):
  1719. # try:
  1720. # for subg in geo:
  1721. # for subsubg in recurse(subg):
  1722. # yield subsubg
  1723. # except TypeError:
  1724. # if isinstance(geo, Polygon):
  1725. # yield geo
  1726. #
  1727. # raise StopIteration
  1728. def recurse(geometry, reset=True):
  1729. """
  1730. Creates a list of non-iterable linear geometry objects.
  1731. Results are placed in self.flat_geometry
  1732. :param geometry: Shapely type or list or list of list of such.
  1733. :param reset: Clears the contents of self.flat_geometry.
  1734. """
  1735. if self.app.abort_flag:
  1736. # graceful abort requested by the user
  1737. raise FlatCAMApp.GracefulException
  1738. if geometry is None:
  1739. return
  1740. if reset:
  1741. self.flat_geometry = []
  1742. # ## If iterable, expand recursively.
  1743. try:
  1744. for geo in geometry:
  1745. if geo is not None:
  1746. recurse(geometry=geo, reset=False)
  1747. # ## Not iterable, do the actual indexing and add.
  1748. except TypeError:
  1749. if isinstance(geometry, LinearRing):
  1750. g = Polygon(geometry)
  1751. self.flat_geometry.append(g)
  1752. else:
  1753. self.flat_geometry.append(geometry)
  1754. return self.flat_geometry
  1755. # Initializes the new geometry object
  1756. def gen_paintarea(geo_obj, app_obj):
  1757. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1758. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1759. log.debug("Paint Tool. Normal painting all task started.")
  1760. if isinstance(obj, FlatCAMGerber):
  1761. if app_obj.defaults["gerber_buffering"] == 'no':
  1762. app_obj.inform.emit('%s %s' %
  1763. (_("Paint Tool. Normal painting all task started."),
  1764. _("Buffering geometry...")))
  1765. else:
  1766. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1767. else:
  1768. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1769. tool_dia = None
  1770. if order == 'fwd':
  1771. sorted_tools.sort(reverse=False)
  1772. elif order == 'rev':
  1773. sorted_tools.sort(reverse=True)
  1774. else:
  1775. pass
  1776. if isinstance(obj, FlatCAMGerber):
  1777. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1778. if isinstance(obj.solid_geometry, list):
  1779. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1780. else:
  1781. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1782. try:
  1783. a, b, c, d = obj.bounds()
  1784. geo_obj.options['xmin'] = a
  1785. geo_obj.options['ymin'] = b
  1786. geo_obj.options['xmax'] = c
  1787. geo_obj.options['ymax'] = d
  1788. except Exception as e:
  1789. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1790. return
  1791. total_geometry = []
  1792. current_uid = int(1)
  1793. geo_obj.solid_geometry = []
  1794. for tool_dia in sorted_tools:
  1795. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1796. app_obj.inform.emit(
  1797. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1798. str(tool_dia),
  1799. self.units.lower(),
  1800. _('started'))
  1801. )
  1802. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1803. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1804. for k, v in tools_storage.items():
  1805. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1806. current_uid = int(k)
  1807. break
  1808. painted_area = recurse(obj.solid_geometry)
  1809. # variables to display the percentage of work done
  1810. geo_len = len(painted_area)
  1811. old_disp_number = 0
  1812. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1813. pol_nr = 0
  1814. for geo in painted_area:
  1815. # provide the app with a way to process the GUI events when in a blocking loop
  1816. QtWidgets.QApplication.processEvents()
  1817. if self.app.abort_flag:
  1818. # graceful abort requested by the user
  1819. raise FlatCAMApp.GracefulException
  1820. # try to clean the Polygon but it may result into a MultiPolygon
  1821. geo = geo.buffer(0)
  1822. poly_buf = geo.buffer(-paint_margin)
  1823. if geo is not None and geo.is_valid:
  1824. poly_processed = list()
  1825. try:
  1826. for pol in poly_buf:
  1827. if pol is not None and isinstance(pol, Polygon):
  1828. if paint_method == 'standard':
  1829. cp = self.clear_polygon(pol,
  1830. tooldia=tool_dia,
  1831. steps_per_circle=self.app.defaults[
  1832. "geometry_circle_steps"],
  1833. overlap=over,
  1834. contour=cont,
  1835. connect=conn,
  1836. prog_plot=prog_plot)
  1837. elif paint_method == 'seed':
  1838. cp = self.clear_polygon2(pol,
  1839. tooldia=tool_dia,
  1840. steps_per_circle=self.app.defaults[
  1841. "geometry_circle_steps"],
  1842. overlap=over,
  1843. contour=cont,
  1844. connect=conn,
  1845. prog_plot=prog_plot)
  1846. else:
  1847. cp = self.clear_polygon3(pol,
  1848. tooldia=tool_dia,
  1849. steps_per_circle=self.app.defaults[
  1850. "geometry_circle_steps"],
  1851. overlap=over,
  1852. contour=cont,
  1853. connect=conn,
  1854. prog_plot=prog_plot)
  1855. if cp:
  1856. total_geometry += list(cp.get_objects())
  1857. poly_processed.append(True)
  1858. else:
  1859. poly_processed.append(False)
  1860. log.warning("Polygon in MultiPolygon can not be cleared.")
  1861. else:
  1862. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  1863. "It is: %s" % str(type(pol)))
  1864. except TypeError:
  1865. if isinstance(poly_buf, Polygon):
  1866. if paint_method == 'standard':
  1867. cp = self.clear_polygon(poly_buf,
  1868. tooldia=tool_dia,
  1869. steps_per_circle=self.app.defaults[
  1870. "geometry_circle_steps"],
  1871. overlap=over,
  1872. contour=cont,
  1873. connect=conn,
  1874. prog_plot=prog_plot)
  1875. elif paint_method == 'seed':
  1876. cp = self.clear_polygon2(poly_buf,
  1877. tooldia=tool_dia,
  1878. steps_per_circle=self.app.defaults[
  1879. "geometry_circle_steps"],
  1880. overlap=over,
  1881. contour=cont,
  1882. connect=conn,
  1883. prog_plot=prog_plot)
  1884. else:
  1885. cp = self.clear_polygon3(poly_buf,
  1886. tooldia=tool_dia,
  1887. steps_per_circle=self.app.defaults[
  1888. "geometry_circle_steps"],
  1889. overlap=over,
  1890. contour=cont,
  1891. connect=conn,
  1892. prog_plot=prog_plot)
  1893. if cp:
  1894. total_geometry += list(cp.get_objects())
  1895. poly_processed.append(True)
  1896. else:
  1897. poly_processed.append(False)
  1898. log.warning("Polygon can not be cleared.")
  1899. else:
  1900. log.warning("Geo can not be cleared because it is: %s" % str(type(poly_buf)))
  1901. p_cleared = poly_processed.count(True)
  1902. p_not_cleared = poly_processed.count(False)
  1903. if p_not_cleared:
  1904. app_obj.poly_not_cleared = True
  1905. if p_cleared == 0:
  1906. continue
  1907. # try:
  1908. # # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1909. # if not isinstance(geo, Polygon):
  1910. # continue
  1911. # poly_buf = geo.buffer(-paint_margin)
  1912. #
  1913. # if paint_method == "seed":
  1914. # # Type(cp) == FlatCAMRTreeStorage | None
  1915. # cp = self.clear_polygon2(poly_buf,
  1916. # tooldia=tool_dia,
  1917. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1918. # overlap=over,
  1919. # contour=cont,
  1920. # connect=conn,
  1921. # prog_plot=prog_plot)
  1922. #
  1923. # elif paint_method == "lines":
  1924. # # Type(cp) == FlatCAMRTreeStorage | None
  1925. # cp = self.clear_polygon3(poly_buf,
  1926. # tooldia=tool_dia,
  1927. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1928. # overlap=over,
  1929. # contour=cont,
  1930. # connect=conn,
  1931. # prog_plot=prog_plot)
  1932. #
  1933. # else:
  1934. # # Type(cp) == FlatCAMRTreeStorage | None
  1935. # cp = self.clear_polygon(poly_buf,
  1936. # tooldia=tool_dia,
  1937. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1938. # overlap=over,
  1939. # contour=cont,
  1940. # connect=conn,
  1941. # prog_plot=prog_plot)
  1942. #
  1943. # if cp is not None:
  1944. # total_geometry += list(cp.get_objects())
  1945. # except FlatCAMApp.GracefulException:
  1946. # return "fail"
  1947. # except Exception as e:
  1948. # log.debug("Could not Paint the polygons. %s" % str(e))
  1949. # self.app.inform.emit('[ERROR] %s\n%s' %
  1950. # (_("Could not do Paint All. Try a different combination of parameters. "
  1951. # "Or a different Method of paint"),
  1952. # str(e)))
  1953. # return "fail"
  1954. pol_nr += 1
  1955. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1956. # log.debug("Polygons cleared: %d" % pol_nr)
  1957. if old_disp_number < disp_number <= 100:
  1958. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1959. old_disp_number = disp_number
  1960. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1961. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1962. # dictionary and then reset the temporary list that stored that solid_geometry
  1963. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1964. tools_storage[current_uid]['data']['name'] = name
  1965. total_geometry[:] = []
  1966. # clean the progressive plotted shapes if it was used
  1967. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1968. self.temp_shapes.clear(update=True)
  1969. # # delete tools with empty geometry
  1970. # keys_to_delete = []
  1971. # # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1972. # for uid in tools_storage:
  1973. # # if the solid_geometry (type=list) is empty
  1974. # if not tools_storage[uid]['solid_geometry']:
  1975. # keys_to_delete.append(uid)
  1976. #
  1977. # # actual delete of keys from the tools_storage dict
  1978. # for k in keys_to_delete:
  1979. # tools_storage.pop(k, None)
  1980. # delete tools with empty geometry
  1981. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1982. for uid in list(tools_storage.keys()):
  1983. # if the solid_geometry (type=list) is empty
  1984. if not tools_storage[uid]['solid_geometry']:
  1985. tools_storage.pop(uid, None)
  1986. geo_obj.options["cnctooldia"] = str(tool_dia)
  1987. # this turn on the FlatCAMCNCJob plot for multiple tools
  1988. geo_obj.multigeo = True
  1989. geo_obj.multitool = True
  1990. geo_obj.tools.clear()
  1991. geo_obj.tools = dict(tools_storage)
  1992. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1993. has_solid_geo = 0
  1994. for tooluid in geo_obj.tools:
  1995. if geo_obj.tools[tooluid]['solid_geometry']:
  1996. has_solid_geo += 1
  1997. if has_solid_geo == 0:
  1998. self.app.inform.emit('[ERROR] %s' %
  1999. _("There is no Painting Geometry in the file.\n"
  2000. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2001. "Change the painting parameters and try again."))
  2002. return
  2003. # Experimental...
  2004. # print("Indexing...", end=' ')
  2005. # geo_obj.make_index()
  2006. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  2007. # Initializes the new geometry object
  2008. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2009. assert isinstance(geo_obj, FlatCAMGeometry), \
  2010. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2011. log.debug("Paint Tool. Rest machining painting all task started.")
  2012. if isinstance(obj, FlatCAMGerber):
  2013. if app_obj.defaults["gerber_buffering"] == 'no':
  2014. app_obj.inform.emit('%s %s %s' %
  2015. (_("Paint Tool."), _("Rest machining painting all task started."),
  2016. _("Buffering geometry...")))
  2017. else:
  2018. app_obj.inform.emit('%s %s' %
  2019. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2020. else:
  2021. app_obj.inform.emit('%s %s' %
  2022. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2023. tool_dia = None
  2024. sorted_tools.sort(reverse=True)
  2025. cleared_geo = []
  2026. current_uid = int(1)
  2027. geo_obj.solid_geometry = []
  2028. if isinstance(obj, FlatCAMGerber):
  2029. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2030. if isinstance(obj.solid_geometry, list):
  2031. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  2032. else:
  2033. obj.solid_geometry = obj.solid_geometry.buffer(0)
  2034. try:
  2035. a, b, c, d = obj.bounds()
  2036. geo_obj.options['xmin'] = a
  2037. geo_obj.options['ymin'] = b
  2038. geo_obj.options['xmax'] = c
  2039. geo_obj.options['ymax'] = d
  2040. except Exception as e:
  2041. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2042. return
  2043. for tool_dia in sorted_tools:
  2044. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2045. app_obj.inform.emit(
  2046. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2047. str(tool_dia),
  2048. self.units.lower(),
  2049. _('started'))
  2050. )
  2051. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2052. painted_area = recurse(obj.solid_geometry)
  2053. # variables to display the percentage of work done
  2054. geo_len = int(len(painted_area) / 100)
  2055. old_disp_number = 0
  2056. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2057. pol_nr = 0
  2058. for geo in painted_area:
  2059. try:
  2060. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2061. poly_buf = geo.buffer(-paint_margin)
  2062. cp = None
  2063. if paint_method == "standard":
  2064. # Type(cp) == FlatCAMRTreeStorage | None
  2065. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2066. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2067. overlap=over, contour=cont, connect=conn,
  2068. prog_plot=prog_plot)
  2069. elif paint_method == "seed":
  2070. # Type(cp) == FlatCAMRTreeStorage | None
  2071. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2072. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2073. overlap=over, contour=cont, connect=conn,
  2074. prog_plot=prog_plot)
  2075. elif paint_method == "lines":
  2076. # Type(cp) == FlatCAMRTreeStorage | None
  2077. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2078. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2079. overlap=over, contour=cont, connect=conn,
  2080. prog_plot=prog_plot)
  2081. if cp is not None:
  2082. cleared_geo += list(cp.get_objects())
  2083. except FlatCAMApp.GracefulException:
  2084. return "fail"
  2085. except Exception as e:
  2086. log.debug("Could not Paint the polygons. %s" % str(e))
  2087. self.app.inform.emit('[ERROR] %s\n%s' %
  2088. (_("Could not do Paint All. Try a different combination of parameters. "
  2089. "Or a different Method of paint"),
  2090. str(e)))
  2091. return "fail"
  2092. pol_nr += 1
  2093. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2094. # log.debug("Polygons cleared: %d" % pol_nr)
  2095. if old_disp_number < disp_number <= 100:
  2096. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2097. old_disp_number = disp_number
  2098. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2099. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2100. for k, v in tools_storage.items():
  2101. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2102. current_uid = int(k)
  2103. break
  2104. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2105. # then reset the temporary list that stored that solid_geometry
  2106. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2107. tools_storage[current_uid]['data']['name'] = name
  2108. cleared_geo[:] = []
  2109. geo_obj.options["cnctooldia"] = str(tool_dia)
  2110. # this turn on the FlatCAMCNCJob plot for multiple tools
  2111. geo_obj.multigeo = True
  2112. geo_obj.multitool = True
  2113. geo_obj.tools.clear()
  2114. geo_obj.tools = dict(tools_storage)
  2115. # clean the progressive plotted shapes if it was used
  2116. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2117. self.temp_shapes.clear(update=True)
  2118. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2119. has_solid_geo = 0
  2120. for tooluid in geo_obj.tools:
  2121. if geo_obj.tools[tooluid]['solid_geometry']:
  2122. has_solid_geo += 1
  2123. if has_solid_geo == 0:
  2124. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2125. _("There is no Painting Geometry in the file.\n"
  2126. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2127. "Change the painting parameters and try again."))
  2128. return
  2129. # Experimental...
  2130. # print("Indexing...", end=' ')
  2131. # geo_obj.make_index()
  2132. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2133. def job_thread(app_obj):
  2134. try:
  2135. if self.rest_cb.isChecked():
  2136. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2137. else:
  2138. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2139. except FlatCAMApp.GracefulException:
  2140. proc.done()
  2141. return
  2142. except Exception:
  2143. proc.done()
  2144. traceback.print_stack()
  2145. return
  2146. proc.done()
  2147. # focus on Selected Tab
  2148. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2149. self.app.inform.emit(_("Polygon Paint started ..."))
  2150. # Promise object with the new name
  2151. self.app.collection.promise(name)
  2152. if run_threaded:
  2153. # Background
  2154. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2155. else:
  2156. job_thread(app_obj=self.app)
  2157. def paint_poly_area(self, obj, sel_obj,
  2158. tooldia=None,
  2159. overlap=None,
  2160. order=None,
  2161. margin=None,
  2162. method=None,
  2163. outname=None,
  2164. connect=None,
  2165. contour=None,
  2166. tools_storage=None,
  2167. plot=True,
  2168. run_threaded=True):
  2169. """
  2170. Paints all polygons in this object that are within the sel_obj object
  2171. :param obj: painted object
  2172. :param sel_obj: paint only what is inside this object bounds
  2173. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2174. :param overlap: value by which the paths will overlap
  2175. :param order: if the tools are ordered and how
  2176. :param margin: a border around painting area
  2177. :param outname: name of the resulting object
  2178. :param connect: Connect lines to avoid tool lifts.
  2179. :param contour: Paint around the edges.
  2180. :param method: choice out of 'seed', 'normal', 'lines'
  2181. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2182. Usage of the different one is related to when this function is called from a TcL command.
  2183. :return:
  2184. """
  2185. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  2186. if margin is not None:
  2187. paint_margin = margin
  2188. else:
  2189. try:
  2190. paint_margin = float(self.paintmargin_entry.get_value())
  2191. except ValueError:
  2192. # try to convert comma to decimal point. if it's still not working error message and return
  2193. try:
  2194. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  2195. except ValueError:
  2196. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2197. _("Wrong value format entered, use a number."))
  2198. return
  2199. # determine if to use the progressive plotting
  2200. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2201. prog_plot = True
  2202. else:
  2203. prog_plot = False
  2204. proc = self.app.proc_container.new(_("Painting polygons..."))
  2205. name = outname if outname is not None else self.obj_name + "_paint"
  2206. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  2207. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  2208. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  2209. order = order if order is not None else self.order_radio.get_value()
  2210. sorted_tools = []
  2211. if tooldia is not None:
  2212. try:
  2213. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  2214. except AttributeError:
  2215. if not isinstance(tooldia, list):
  2216. sorted_tools = [float(tooldia)]
  2217. else:
  2218. sorted_tools = tooldia
  2219. else:
  2220. for row in range(self.tools_table.rowCount()):
  2221. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  2222. if tools_storage is not None:
  2223. tools_storage = tools_storage
  2224. else:
  2225. tools_storage = self.paint_tools
  2226. def recurse(geometry, reset=True):
  2227. """
  2228. Creates a list of non-iterable linear geometry objects.
  2229. Results are placed in self.flat_geometry
  2230. :param geometry: Shapely type or list or list of list of such.
  2231. :param reset: Clears the contents of self.flat_geometry.
  2232. """
  2233. if self.app.abort_flag:
  2234. # graceful abort requested by the user
  2235. raise FlatCAMApp.GracefulException
  2236. if geometry is None:
  2237. return
  2238. if reset:
  2239. self.flat_geometry = []
  2240. # ## If iterable, expand recursively.
  2241. try:
  2242. for geo in geometry:
  2243. if geo is not None:
  2244. recurse(geometry=geo, reset=False)
  2245. # ## Not iterable, do the actual indexing and add.
  2246. except TypeError:
  2247. if isinstance(geometry, LinearRing):
  2248. g = Polygon(geometry)
  2249. self.flat_geometry.append(g)
  2250. else:
  2251. self.flat_geometry.append(geometry)
  2252. return self.flat_geometry
  2253. # Initializes the new geometry object
  2254. def gen_paintarea(geo_obj, app_obj):
  2255. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2256. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2257. log.debug("Paint Tool. Normal painting area task started.")
  2258. if isinstance(obj, FlatCAMGerber):
  2259. if app_obj.defaults["gerber_buffering"] == 'no':
  2260. app_obj.inform.emit('%s %s %s' %
  2261. (_("Paint Tool."),
  2262. _("Normal painting area task started."),
  2263. _("Buffering geometry...")))
  2264. else:
  2265. app_obj.inform.emit('%s %s' %
  2266. (_("Paint Tool."), _("Normal painting area task started.")))
  2267. else:
  2268. app_obj.inform.emit('%s %s' %
  2269. (_("Paint Tool."), _("Normal painting area task started.")))
  2270. tool_dia = None
  2271. if order == 'fwd':
  2272. sorted_tools.sort(reverse=False)
  2273. elif order == 'rev':
  2274. sorted_tools.sort(reverse=True)
  2275. else:
  2276. pass
  2277. # this is were heavy lifting is done and creating the geometry to be painted
  2278. target_geo = MultiPolygon(obj.solid_geometry)
  2279. if isinstance(obj, FlatCAMGerber):
  2280. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2281. if isinstance(target_geo, list):
  2282. target_geo = MultiPolygon(target_geo).buffer(0)
  2283. else:
  2284. target_geo = target_geo.buffer(0)
  2285. geo_to_paint = target_geo.intersection(sel_obj)
  2286. painted_area = recurse(geo_to_paint)
  2287. try:
  2288. a, b, c, d = self.paint_bounds(geo_to_paint)
  2289. geo_obj.options['xmin'] = a
  2290. geo_obj.options['ymin'] = b
  2291. geo_obj.options['xmax'] = c
  2292. geo_obj.options['ymax'] = d
  2293. except Exception as e:
  2294. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2295. return
  2296. total_geometry = []
  2297. current_uid = int(1)
  2298. geo_obj.solid_geometry = []
  2299. for tool_dia in sorted_tools:
  2300. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2301. app_obj.inform.emit(
  2302. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2303. str(tool_dia),
  2304. self.units.lower(),
  2305. _('started'))
  2306. )
  2307. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2308. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2309. for k, v in tools_storage.items():
  2310. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2311. current_uid = int(k)
  2312. break
  2313. # variables to display the percentage of work done
  2314. geo_len = len(painted_area)
  2315. old_disp_number = 0
  2316. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2317. pol_nr = 0
  2318. for geo in painted_area:
  2319. try:
  2320. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  2321. if not isinstance(geo, Polygon):
  2322. continue
  2323. poly_buf = geo.buffer(-paint_margin)
  2324. if paint_method == "seed":
  2325. # Type(cp) == FlatCAMRTreeStorage | None
  2326. cp = self.clear_polygon2(poly_buf,
  2327. tooldia=tool_dia,
  2328. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2329. overlap=over,
  2330. contour=cont,
  2331. connect=conn,
  2332. prog_plot=prog_plot)
  2333. elif paint_method == "lines":
  2334. # Type(cp) == FlatCAMRTreeStorage | None
  2335. cp = self.clear_polygon3(poly_buf,
  2336. tooldia=tool_dia,
  2337. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2338. overlap=over,
  2339. contour=cont,
  2340. connect=conn,
  2341. prog_plot=prog_plot)
  2342. else:
  2343. # Type(cp) == FlatCAMRTreeStorage | None
  2344. cp = self.clear_polygon(poly_buf,
  2345. tooldia=tool_dia,
  2346. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2347. overlap=over,
  2348. contour=cont,
  2349. connect=conn,
  2350. prog_plot=prog_plot)
  2351. if cp is not None:
  2352. total_geometry += list(cp.get_objects())
  2353. except FlatCAMApp.GracefulException:
  2354. return "fail"
  2355. except Exception as e:
  2356. log.debug("Could not Paint the polygons. %s" % str(e))
  2357. self.app.inform.emit('[ERROR] %s\n%s' %
  2358. (_("Could not do Paint All. Try a different combination of parameters. "
  2359. "Or a different Method of paint"), str(e)))
  2360. return
  2361. pol_nr += 1
  2362. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2363. # log.debug("Polygons cleared: %d" % pol_nr)
  2364. if old_disp_number < disp_number <= 100:
  2365. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2366. old_disp_number = disp_number
  2367. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2368. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  2369. # dictionary and then reset the temporary list that stored that solid_geometry
  2370. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  2371. tools_storage[current_uid]['data']['name'] = name
  2372. total_geometry[:] = []
  2373. # clean the progressive plotted shapes if it was used
  2374. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2375. self.temp_shapes.clear(update=True)
  2376. # delete tools with empty geometry
  2377. keys_to_delete = []
  2378. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2379. for uid in tools_storage:
  2380. # if the solid_geometry (type=list) is empty
  2381. if not tools_storage[uid]['solid_geometry']:
  2382. keys_to_delete.append(uid)
  2383. # actual delete of keys from the tools_storage dict
  2384. for k in keys_to_delete:
  2385. tools_storage.pop(k, None)
  2386. geo_obj.options["cnctooldia"] = str(tool_dia)
  2387. # this turn on the FlatCAMCNCJob plot for multiple tools
  2388. geo_obj.multigeo = True
  2389. geo_obj.multitool = True
  2390. geo_obj.tools.clear()
  2391. geo_obj.tools = dict(tools_storage)
  2392. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2393. has_solid_geo = 0
  2394. for tooluid in geo_obj.tools:
  2395. if geo_obj.tools[tooluid]['solid_geometry']:
  2396. has_solid_geo += 1
  2397. if has_solid_geo == 0:
  2398. self.app.inform.emit('[ERROR] %s' %
  2399. _("There is no Painting Geometry in the file.\n"
  2400. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2401. "Change the painting parameters and try again."))
  2402. return
  2403. # Experimental...
  2404. # print("Indexing...", end=' ')
  2405. # geo_obj.make_index()
  2406. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  2407. # Initializes the new geometry object
  2408. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2409. assert isinstance(geo_obj, FlatCAMGeometry), \
  2410. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2411. log.debug("Paint Tool. Rest machining painting area task started.")
  2412. if isinstance(obj, FlatCAMGerber):
  2413. if app_obj.defaults["gerber_buffering"] == 'no':
  2414. app_obj.inform.emit('%s %s %s' %
  2415. (_("Paint Tool."),
  2416. _("Rest machining painting area task started."),
  2417. _("Buffering geometry...")))
  2418. else:
  2419. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  2420. else:
  2421. app_obj.inform.emit('%s %s' %
  2422. (_("Paint Tool."), _("Rest machining painting area task started.")))
  2423. tool_dia = None
  2424. sorted_tools.sort(reverse=True)
  2425. cleared_geo = []
  2426. current_uid = int(1)
  2427. geo_obj.solid_geometry = []
  2428. # this is were heavy lifting is done and creating the geometry to be painted
  2429. target_geo = obj.solid_geometry
  2430. if isinstance(obj, FlatCAMGerber):
  2431. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2432. if isinstance(target_geo, list):
  2433. target_geo = MultiPolygon(target_geo).buffer(0)
  2434. else:
  2435. target_geo = target_geo.buffer(0)
  2436. geo_to_paint = target_geo.intersection(sel_obj)
  2437. painted_area = recurse(geo_to_paint)
  2438. try:
  2439. a, b, c, d = obj.bounds()
  2440. geo_obj.options['xmin'] = a
  2441. geo_obj.options['ymin'] = b
  2442. geo_obj.options['xmax'] = c
  2443. geo_obj.options['ymax'] = d
  2444. except Exception as e:
  2445. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2446. return
  2447. for tool_dia in sorted_tools:
  2448. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2449. app_obj.inform.emit(
  2450. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2451. str(tool_dia),
  2452. self.units.lower(),
  2453. _('started'))
  2454. )
  2455. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2456. # variables to display the percentage of work done
  2457. geo_len = len(painted_area)
  2458. old_disp_number = 0
  2459. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2460. pol_nr = 0
  2461. for geo in painted_area:
  2462. try:
  2463. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2464. poly_buf = geo.buffer(-paint_margin)
  2465. cp = None
  2466. if paint_method == "standard":
  2467. # Type(cp) == FlatCAMRTreeStorage | None
  2468. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2469. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2470. overlap=over, contour=cont, connect=conn,
  2471. prog_plot=prog_plot)
  2472. elif paint_method == "seed":
  2473. # Type(cp) == FlatCAMRTreeStorage | None
  2474. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2475. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2476. overlap=over, contour=cont, connect=conn,
  2477. prog_plot=prog_plot)
  2478. elif paint_method == "lines":
  2479. # Type(cp) == FlatCAMRTreeStorage | None
  2480. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2481. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2482. overlap=over, contour=cont, connect=conn,
  2483. prog_plot=prog_plot)
  2484. if cp is not None:
  2485. cleared_geo += list(cp.get_objects())
  2486. except FlatCAMApp.GracefulException:
  2487. return "fail"
  2488. except Exception as e:
  2489. log.debug("Could not Paint the polygons. %s" % str(e))
  2490. self.app.inform.emit('[ERROR] %s\n%s' %
  2491. (_("Could not do Paint All. Try a different combination of parameters. "
  2492. "Or a different Method of paint"), str(e)))
  2493. return
  2494. pol_nr += 1
  2495. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2496. # log.debug("Polygons cleared: %d" % pol_nr)
  2497. if old_disp_number < disp_number <= 100:
  2498. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2499. old_disp_number = disp_number
  2500. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2501. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2502. for k, v in tools_storage.items():
  2503. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2504. current_uid = int(k)
  2505. break
  2506. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2507. # then reset the temporary list that stored that solid_geometry
  2508. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2509. tools_storage[current_uid]['data']['name'] = name
  2510. cleared_geo[:] = []
  2511. geo_obj.options["cnctooldia"] = str(tool_dia)
  2512. # this turn on the FlatCAMCNCJob plot for multiple tools
  2513. geo_obj.multigeo = True
  2514. geo_obj.multitool = True
  2515. geo_obj.tools.clear()
  2516. geo_obj.tools = dict(self.paint_tools)
  2517. # clean the progressive plotted shapes if it was used
  2518. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2519. self.temp_shapes.clear(update=True)
  2520. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2521. has_solid_geo = 0
  2522. for tooluid in geo_obj.tools:
  2523. if geo_obj.tools[tooluid]['solid_geometry']:
  2524. has_solid_geo += 1
  2525. if has_solid_geo == 0:
  2526. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2527. _("There is no Painting Geometry in the file.\n"
  2528. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2529. "Change the painting parameters and try again."))
  2530. return
  2531. # Experimental...
  2532. # print("Indexing...", end=' ')
  2533. # geo_obj.make_index()
  2534. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2535. def job_thread(app_obj):
  2536. try:
  2537. if self.rest_cb.isChecked():
  2538. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2539. else:
  2540. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2541. except FlatCAMApp.GracefulException:
  2542. proc.done()
  2543. return
  2544. except Exception:
  2545. proc.done()
  2546. traceback.print_stack()
  2547. return
  2548. proc.done()
  2549. # focus on Selected Tab
  2550. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2551. self.app.inform.emit(_("Polygon Paint started ..."))
  2552. # Promise object with the new name
  2553. self.app.collection.promise(name)
  2554. if run_threaded:
  2555. # Background
  2556. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2557. else:
  2558. job_thread(app_obj=self.app)
  2559. def paint_poly_ref(self, obj, sel_obj,
  2560. tooldia=None,
  2561. overlap=None,
  2562. order=None,
  2563. margin=None,
  2564. method=None,
  2565. outname=None,
  2566. connect=None,
  2567. contour=None,
  2568. tools_storage=None,
  2569. plot=True,
  2570. run_threaded=True):
  2571. """
  2572. Paints all polygons in this object that are within the sel_obj object
  2573. :param obj: painted object
  2574. :param sel_obj: paint only what is inside this object bounds
  2575. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2576. :param overlap: value by which the paths will overlap
  2577. :param order: if the tools are ordered and how
  2578. :param margin: a border around painting area
  2579. :param outname: name of the resulting object
  2580. :param connect: Connect lines to avoid tool lifts.
  2581. :param contour: Paint around the edges.
  2582. :param method: choice out of 'seed', 'normal', 'lines'
  2583. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2584. Usage of the different one is related to when this function is called from a TcL command.
  2585. :return:
  2586. """
  2587. geo = sel_obj.solid_geometry
  2588. try:
  2589. if isinstance(geo, MultiPolygon):
  2590. env_obj = geo.convex_hull
  2591. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2592. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2593. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2594. else:
  2595. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2596. env_obj = env_obj.convex_hull
  2597. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2598. except Exception as e:
  2599. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  2600. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2601. return
  2602. self.paint_poly_area(obj=obj,
  2603. sel_obj=sel_rect,
  2604. tooldia=tooldia,
  2605. overlap=overlap,
  2606. order=order,
  2607. margin=margin,
  2608. method=method,
  2609. outname=outname,
  2610. connect=connect,
  2611. contour=contour,
  2612. tools_storage=tools_storage,
  2613. plot=plot,
  2614. run_threaded=run_threaded)
  2615. def ui_connect(self):
  2616. self.tools_table.itemChanged.connect(self.on_tool_edit)
  2617. for row in range(self.tools_table.rowCount()):
  2618. try:
  2619. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2620. except AttributeError:
  2621. pass
  2622. try:
  2623. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  2624. except AttributeError:
  2625. pass
  2626. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  2627. # first disconnect
  2628. for opt in self.form_fields:
  2629. current_widget = self.form_fields[opt]
  2630. if isinstance(current_widget, FCCheckBox):
  2631. try:
  2632. current_widget.stateChanged.disconnect()
  2633. except (TypeError, ValueError):
  2634. pass
  2635. if isinstance(current_widget, RadioSet):
  2636. try:
  2637. current_widget.activated_custom.disconnect()
  2638. except (TypeError, ValueError):
  2639. pass
  2640. elif isinstance(current_widget, FCDoubleSpinner):
  2641. try:
  2642. current_widget.returnPressed.disconnect()
  2643. except (TypeError, ValueError):
  2644. pass
  2645. # then reconnect
  2646. for opt in self.form_fields:
  2647. current_widget = self.form_fields[opt]
  2648. if isinstance(current_widget, FCCheckBox):
  2649. current_widget.stateChanged.connect(self.form_to_storage)
  2650. if isinstance(current_widget, RadioSet):
  2651. current_widget.activated_custom.connect(self.form_to_storage)
  2652. elif isinstance(current_widget, FCDoubleSpinner):
  2653. current_widget.returnPressed.connect(self.form_to_storage)
  2654. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  2655. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  2656. def ui_disconnect(self):
  2657. try:
  2658. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2659. self.tools_table.itemChanged.disconnect()
  2660. except (TypeError, AttributeError):
  2661. pass
  2662. try:
  2663. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2664. self.tool_type_radio.activated_custom.disconnect()
  2665. except (TypeError, AttributeError):
  2666. pass
  2667. for row in range(self.tools_table.rowCount()):
  2668. for col in [2, 4]:
  2669. try:
  2670. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2671. except (TypeError, AttributeError):
  2672. pass
  2673. for opt in self.form_fields:
  2674. current_widget = self.form_fields[opt]
  2675. if isinstance(current_widget, FCCheckBox):
  2676. try:
  2677. current_widget.stateChanged.disconnect()
  2678. except (TypeError, ValueError):
  2679. pass
  2680. if isinstance(current_widget, RadioSet):
  2681. try:
  2682. current_widget.activated_custom.disconnect()
  2683. except (TypeError, ValueError):
  2684. pass
  2685. elif isinstance(current_widget, FCDoubleSpinner):
  2686. try:
  2687. current_widget.returnPressed.disconnect()
  2688. except (TypeError, ValueError):
  2689. pass
  2690. def reset_usage(self):
  2691. self.obj_name = ""
  2692. self.paint_obj = None
  2693. self.bound_obj = None
  2694. self.first_click = False
  2695. self.cursor_pos = None
  2696. self.mouse_is_dragging = False
  2697. self.sel_rect = []
  2698. @staticmethod
  2699. def paint_bounds(geometry):
  2700. def bounds_rec(o):
  2701. if type(o) is list:
  2702. minx = Inf
  2703. miny = Inf
  2704. maxx = -Inf
  2705. maxy = -Inf
  2706. for k in o:
  2707. try:
  2708. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2709. except Exception as e:
  2710. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2711. return
  2712. minx = min(minx, minx_)
  2713. miny = min(miny, miny_)
  2714. maxx = max(maxx, maxx_)
  2715. maxy = max(maxy, maxy_)
  2716. return minx, miny, maxx, maxy
  2717. else:
  2718. # it's a Shapely object, return it's bounds
  2719. return o.bounds
  2720. return bounds_rec(geometry)
  2721. def reset_fields(self):
  2722. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))