ToolPaint.py 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593
  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
  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. from numpy import Inf
  21. import traceback
  22. import logging
  23. import gettext
  24. import FlatCAMTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. log = logging.getLogger('base')
  30. class ToolPaint(FlatCAMTool, Gerber):
  31. toolName = _("Paint Tool")
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = 4
  35. FlatCAMTool.__init__(self, app)
  36. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  37. # ## Title
  38. title_label = QtWidgets.QLabel("%s" % self.toolName)
  39. title_label.setStyleSheet("""
  40. QLabel
  41. {
  42. font-size: 16px;
  43. font-weight: bold;
  44. }
  45. """)
  46. self.layout.addWidget(title_label)
  47. self.tools_frame = QtWidgets.QFrame()
  48. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  49. self.layout.addWidget(self.tools_frame)
  50. self.tools_box = QtWidgets.QVBoxLayout()
  51. self.tools_box.setContentsMargins(0, 0, 0, 0)
  52. self.tools_frame.setLayout(self.tools_box)
  53. # ## Form Layout
  54. form_layout = QtWidgets.QFormLayout()
  55. self.tools_box.addLayout(form_layout)
  56. # ################################################
  57. # ##### Type of object to be painted #############
  58. # ################################################
  59. self.type_obj_combo = QtWidgets.QComboBox()
  60. self.type_obj_combo.addItem("Gerber")
  61. self.type_obj_combo.addItem("Excellon")
  62. self.type_obj_combo.addItem("Geometry")
  63. # we get rid of item1 ("Excellon") as it is not suitable
  64. self.type_obj_combo.view().setRowHidden(1, True)
  65. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  66. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  67. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  68. self.type_obj_combo_label.setToolTip(
  69. _("Specify the type of object to be painted.\n"
  70. "It can be of type: Gerber or Geometry.\n"
  71. "What is selected here will dictate the kind\n"
  72. "of objects that will populate the 'Object' combobox.")
  73. )
  74. self.type_obj_combo_label.setMinimumWidth(60)
  75. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  76. # ################################################
  77. # ##### The object to be painted #################
  78. # ################################################
  79. self.obj_combo = QtWidgets.QComboBox()
  80. self.obj_combo.setModel(self.app.collection)
  81. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  82. self.obj_combo.setCurrentIndex(1)
  83. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  84. self.object_label.setToolTip(_("Object to be painted."))
  85. form_layout.addRow(self.object_label, self.obj_combo)
  86. e_lab_0 = QtWidgets.QLabel('')
  87. form_layout.addRow(e_lab_0)
  88. # ### Tools ## ##
  89. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  90. self.tools_table_label.setToolTip(
  91. _("Tools pool from which the algorithm\n"
  92. "will pick the ones used for painting.")
  93. )
  94. self.tools_box.addWidget(self.tools_table_label)
  95. self.tools_table = FCTable()
  96. self.tools_box.addWidget(self.tools_table)
  97. self.tools_table.setColumnCount(4)
  98. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  99. self.tools_table.setColumnHidden(3, True)
  100. # self.tools_table.setSortingEnabled(False)
  101. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  102. self.tools_table.horizontalHeaderItem(0).setToolTip(
  103. _("This is the Tool Number.\n"
  104. "Painting will start with the tool with the biggest diameter,\n"
  105. "continuing until there are no more tools.\n"
  106. "Only tools that create painting geometry will still be present\n"
  107. "in the resulting geometry. This is because with some tools\n"
  108. "this function will not be able to create painting geometry.")
  109. )
  110. self.tools_table.horizontalHeaderItem(1).setToolTip(
  111. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  112. "is the cut width into the material."))
  113. self.tools_table.horizontalHeaderItem(2).setToolTip(
  114. _("The Tool Type (TT) can be:<BR>"
  115. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  116. "the cut width in material is exactly the tool diameter.<BR>"
  117. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  118. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  119. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  120. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  121. "as the cut width into material will be equal with the value in the Tool Diameter "
  122. "column of this table.<BR>"
  123. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  124. "in the resulting geometry as Isolation."))
  125. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  126. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  127. "'No' --> means that the used order is the one in the tool table\n"
  128. "'Forward' --> means that the tools will be ordered from small to big\n"
  129. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  130. "WARNING: using rest machining will automatically set the order\n"
  131. "in reverse and disable this control."))
  132. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  133. {'label': _('Forward'), 'value': 'fwd'},
  134. {'label': _('Reverse'), 'value': 'rev'}])
  135. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  136. "'No' --> means that the used order is the one in the tool table\n"
  137. "'Forward' --> means that the tools will be ordered from small to big\n"
  138. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  139. "WARNING: using rest machining will automatically set the order\n"
  140. "in reverse and disable this control."))
  141. form = QtWidgets.QFormLayout()
  142. self.tools_box.addLayout(form)
  143. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  144. form.addRow(self.order_label, self.order_radio)
  145. # ### Add a new Tool ## ##
  146. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  147. self.addtool_entry_lbl.setToolTip(
  148. _("Diameter for the new tool.")
  149. )
  150. self.addtool_entry = FCDoubleSpinner()
  151. self.addtool_entry.set_precision(self.decimals)
  152. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  153. grid2 = QtWidgets.QGridLayout()
  154. self.tools_box.addLayout(grid2)
  155. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  156. self.addtool_btn.setToolTip(
  157. _("Add a new tool to the Tool Table\n"
  158. "with the diameter specified above.")
  159. )
  160. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  161. # self.copytool_btn.setToolTip(
  162. # "Copy a selection of tools in the Tool Table\n"
  163. # "by first selecting a row in the Tool Table."
  164. # )
  165. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  166. self.deltool_btn.setToolTip(
  167. _("Delete a selection of tools in the Tool Table\n"
  168. "by first selecting a row(s) in the Tool Table.")
  169. )
  170. grid2.addWidget(self.addtool_btn, 0, 0)
  171. # grid2.addWidget(self.copytool_btn, 0, 1)
  172. grid2.addWidget(self.deltool_btn, 0, 2)
  173. self.empty_label_0 = QtWidgets.QLabel('')
  174. self.tools_box.addWidget(self.empty_label_0)
  175. grid3 = QtWidgets.QGridLayout()
  176. self.tools_box.addLayout(grid3)
  177. grid3.setColumnStretch(0, 0)
  178. grid3.setColumnStretch(1, 1)
  179. # Overlap
  180. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  181. ovlabel.setToolTip(
  182. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  183. "Adjust the value starting with lower values\n"
  184. "and increasing it if areas that should be painted are still \n"
  185. "not painted.\n"
  186. "Lower values = faster processing, faster execution on CNC.\n"
  187. "Higher values = slow processing and slow execution on CNC\n"
  188. "due of too many paths.")
  189. )
  190. self.paintoverlap_entry = FCDoubleSpinner(suffix='%')
  191. self.paintoverlap_entry.set_precision(3)
  192. self.paintoverlap_entry.setWrapping(True)
  193. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  194. self.paintoverlap_entry.setSingleStep(0.1)
  195. grid3.addWidget(ovlabel, 1, 0)
  196. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  197. # Margin
  198. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  199. marginlabel.setToolTip(
  200. _("Distance by which to avoid\n"
  201. "the edges of the polygon to\n"
  202. "be painted.")
  203. )
  204. grid3.addWidget(marginlabel, 2, 0)
  205. self.paintmargin_entry = FCDoubleSpinner()
  206. self.paintmargin_entry.set_precision(self.decimals)
  207. grid3.addWidget(self.paintmargin_entry, 2, 1)
  208. # Method
  209. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  210. methodlabel.setToolTip(
  211. _("Algorithm for painting:\n"
  212. "- Standard: Fixed step inwards.\n"
  213. "- Seed-based: Outwards from seed.\n"
  214. "- Line-based: Parallel lines.")
  215. )
  216. grid3.addWidget(methodlabel, 3, 0)
  217. self.paintmethod_combo = RadioSet([
  218. {"label": _("Standard"), "value": "standard"},
  219. {"label": _("Seed-based"), "value": "seed"},
  220. {"label": _("Straight lines"), "value": "lines"}
  221. ], orientation='vertical', stretch=False)
  222. grid3.addWidget(self.paintmethod_combo, 3, 1)
  223. # Connect lines
  224. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  225. pathconnectlabel.setToolTip(
  226. _("Draw lines between resulting\n"
  227. "segments to minimize tool lifts.")
  228. )
  229. grid3.addWidget(pathconnectlabel, 4, 0)
  230. self.pathconnect_cb = FCCheckBox()
  231. grid3.addWidget(self.pathconnect_cb, 4, 1)
  232. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  233. contourlabel.setToolTip(
  234. _("Cut around the perimeter of the polygon\n"
  235. "to trim rough edges.")
  236. )
  237. grid3.addWidget(contourlabel, 5, 0)
  238. self.paintcontour_cb = FCCheckBox()
  239. grid3.addWidget(self.paintcontour_cb, 5, 1)
  240. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  241. restlabel.setToolTip(
  242. _("If checked, use 'rest machining'.\n"
  243. "Basically it will clear copper outside PCB features,\n"
  244. "using the biggest tool and continue with the next tools,\n"
  245. "from bigger to smaller, to clear areas of copper that\n"
  246. "could not be cleared by previous tool, until there is\n"
  247. "no more copper to clear or there are no more tools.\n\n"
  248. "If not checked, use the standard algorithm.")
  249. )
  250. grid3.addWidget(restlabel, 6, 0)
  251. self.rest_cb = FCCheckBox()
  252. grid3.addWidget(self.rest_cb, 6, 1)
  253. # Polygon selection
  254. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  255. selectlabel.setToolTip(
  256. _("How to select Polygons to be painted.\n"
  257. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  258. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  259. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  260. "- 'All Polygons' - the Paint will start after click.\n"
  261. "- 'Reference Object' - will do non copper clearing within the area\n"
  262. "specified by another object.")
  263. )
  264. grid3.addWidget(selectlabel, 7, 0)
  265. # grid3 = QtWidgets.QGridLayout()
  266. self.selectmethod_combo = RadioSet([
  267. {"label": _("Polygon Selection"), "value": "single"},
  268. {"label": _("Area Selection"), "value": "area"},
  269. {"label": _("All Polygons"), "value": "all"},
  270. {"label": _("Reference Object"), "value": "ref"}
  271. ], orientation='vertical', stretch=False)
  272. self.selectmethod_combo.setToolTip(
  273. _("How to select Polygons to be painted.\n"
  274. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  275. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  276. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  277. "- 'All Polygons' - the Paint will start after click.\n"
  278. "- 'Reference Object' - will do non copper clearing within the area\n"
  279. "specified by another object.")
  280. )
  281. grid3.addWidget(self.selectmethod_combo, 7, 1)
  282. form1 = QtWidgets.QFormLayout()
  283. self.tools_box.addLayout(form1)
  284. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  285. self.box_combo_type_label.setToolTip(
  286. _("The type of FlatCAM object to be used as paint reference.\n"
  287. "It can be Gerber, Excellon or Geometry.")
  288. )
  289. self.box_combo_type = QtWidgets.QComboBox()
  290. self.box_combo_type.addItem(_("Reference Gerber"))
  291. self.box_combo_type.addItem(_("Reference Excellon"))
  292. self.box_combo_type.addItem(_("Reference Geometry"))
  293. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  294. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  295. self.box_combo_label.setToolTip(
  296. _("The FlatCAM object to be used as non copper clearing reference.")
  297. )
  298. self.box_combo = QtWidgets.QComboBox()
  299. self.box_combo.setModel(self.app.collection)
  300. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  301. self.box_combo.setCurrentIndex(1)
  302. form1.addRow(self.box_combo_label, self.box_combo)
  303. self.box_combo.hide()
  304. self.box_combo_label.hide()
  305. self.box_combo_type.hide()
  306. self.box_combo_type_label.hide()
  307. # GO Button
  308. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  309. self.generate_paint_button.setToolTip(
  310. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  311. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  312. "- 'All Polygons' - the Paint will start after click.\n"
  313. "- 'Reference Object' - will do non copper clearing within the area\n"
  314. "specified by another object.")
  315. )
  316. self.tools_box.addWidget(self.generate_paint_button)
  317. self.tools_box.addStretch()
  318. # #################################### FINSIHED GUI #####################################
  319. # #######################################################################################
  320. self.obj_name = ""
  321. self.paint_obj = None
  322. self.bound_obj_name = ""
  323. self.bound_obj = None
  324. self.tooldia_list = []
  325. self.sel_rect = None
  326. self.o_name = None
  327. self.overlap = None
  328. self.connect = None
  329. self.contour = None
  330. self.select_method = None
  331. self.units = ''
  332. self.paint_tools = {}
  333. self.tooluid = 0
  334. self.first_click = False
  335. self.cursor_pos = None
  336. self.mouse_is_dragging = False
  337. self.mm = None
  338. self.mp = None
  339. self.mr = None
  340. self.sel_rect = []
  341. # store here if the grid snapping is active
  342. self.grid_status_memory = False
  343. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  344. self.poly_dict = dict()
  345. # store here the default data for Geometry Data
  346. self.default_data = {}
  347. self.default_data.update({
  348. "name": '_paint',
  349. "plot": self.app.defaults["geometry_plot"],
  350. "cutz": self.app.defaults["geometry_cutz"],
  351. "vtipdia": 0.1,
  352. "vtipangle": 30,
  353. "travelz": self.app.defaults["geometry_travelz"],
  354. "feedrate": self.app.defaults["geometry_feedrate"],
  355. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  356. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  357. "dwell": self.app.defaults["geometry_dwell"],
  358. "dwelltime": self.app.defaults["geometry_dwelltime"],
  359. "multidepth": self.app.defaults["geometry_multidepth"],
  360. "ppname_g": self.app.defaults["geometry_ppname_g"],
  361. "depthperpass": self.app.defaults["geometry_depthperpass"],
  362. "extracut": self.app.defaults["geometry_extracut"],
  363. "toolchange": self.app.defaults["geometry_toolchange"],
  364. "toolchangez": self.app.defaults["geometry_toolchangez"],
  365. "endz": self.app.defaults["geometry_endz"],
  366. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  367. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  368. "startz": self.app.defaults["geometry_startz"],
  369. "tooldia": self.app.defaults["tools_painttooldia"],
  370. "paintmargin": self.app.defaults["tools_paintmargin"],
  371. "paintmethod": self.app.defaults["tools_paintmethod"],
  372. "selectmethod": self.app.defaults["tools_selectmethod"],
  373. "pathconnect": self.app.defaults["tools_pathconnect"],
  374. "paintcontour": self.app.defaults["tools_paintcontour"],
  375. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  376. })
  377. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  378. # #############################################################################
  379. # ################################# Signals ###################################
  380. # #############################################################################
  381. self.addtool_btn.clicked.connect(self.on_tool_add)
  382. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  383. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  384. self.tools_table.itemChanged.connect(self.on_tool_edit)
  385. self.deltool_btn.clicked.connect(self.on_tool_delete)
  386. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  387. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  388. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  389. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  390. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  391. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  392. # #############################################################################
  393. # ###################### Setup CONTEXT MENU ###################################
  394. # #############################################################################
  395. self.tools_table.setupContextMenu()
  396. self.tools_table.addContextMenu(
  397. "Add", self.on_add_tool_by_key, icon=QtGui.QIcon("share/plus16.png"))
  398. self.tools_table.addContextMenu(
  399. "Delete", lambda:
  400. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  401. def on_type_obj_index_changed(self, index):
  402. obj_type = self.type_obj_combo.currentIndex()
  403. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  404. self.obj_combo.setCurrentIndex(0)
  405. def install(self, icon=None, separator=None, **kwargs):
  406. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  407. def on_add_tool_by_key(self):
  408. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  409. text='%s:' % _('Enter a Tool Diameter'),
  410. min=0.0000, max=99.9999, decimals=4)
  411. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  412. val, ok = tool_add_popup.get_value()
  413. if ok:
  414. if float(val) == 0:
  415. self.app.inform.emit('[WARNING_NOTCL] %s' %
  416. _("Please enter a tool diameter with non-zero value, in Float format."))
  417. return
  418. self.on_tool_add(dia=float(val))
  419. else:
  420. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  421. def run(self, toggle=True):
  422. self.app.report_usage("ToolPaint()")
  423. if toggle:
  424. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  425. if self.app.ui.splitter.sizes()[0] == 0:
  426. self.app.ui.splitter.setSizes([1, 1])
  427. else:
  428. try:
  429. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  430. # if tab is populated with the tool but it does not have the focus, focus on it
  431. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  432. # focus on Tool Tab
  433. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  434. else:
  435. self.app.ui.splitter.setSizes([0, 1])
  436. except AttributeError:
  437. pass
  438. else:
  439. if self.app.ui.splitter.sizes()[0] == 0:
  440. self.app.ui.splitter.setSizes([1, 1])
  441. FlatCAMTool.run(self)
  442. self.set_tool_ui()
  443. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  444. def reset_usage(self):
  445. self.obj_name = ""
  446. self.paint_obj = None
  447. self.bound_obj = None
  448. self.first_click = False
  449. self.cursor_pos = None
  450. self.mouse_is_dragging = False
  451. self.sel_rect = []
  452. def on_radio_selection(self):
  453. if self.selectmethod_combo.get_value() == "ref":
  454. self.box_combo.show()
  455. self.box_combo_label.show()
  456. self.box_combo_type.show()
  457. self.box_combo_type_label.show()
  458. else:
  459. self.box_combo.hide()
  460. self.box_combo_label.hide()
  461. self.box_combo_type.hide()
  462. self.box_combo_type_label.hide()
  463. if self.selectmethod_combo.get_value() == 'single':
  464. # disable rest-machining for single polygon painting
  465. self.rest_cb.set_value(False)
  466. self.rest_cb.setDisabled(True)
  467. if self.selectmethod_combo.get_value() == 'area':
  468. # disable rest-machining for single polygon painting
  469. self.rest_cb.set_value(False)
  470. self.rest_cb.setDisabled(True)
  471. else:
  472. self.rest_cb.setDisabled(False)
  473. self.addtool_entry.setDisabled(False)
  474. self.addtool_btn.setDisabled(False)
  475. self.deltool_btn.setDisabled(False)
  476. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  477. def on_order_changed(self, order):
  478. if order != 'no':
  479. self.build_ui()
  480. def on_rest_machining_check(self, state):
  481. if state:
  482. self.order_radio.set_value('rev')
  483. self.order_label.setDisabled(True)
  484. self.order_radio.setDisabled(True)
  485. else:
  486. self.order_label.setDisabled(False)
  487. self.order_radio.setDisabled(False)
  488. def set_tool_ui(self):
  489. self.tools_frame.show()
  490. self.reset_fields()
  491. # ## Init the GUI interface
  492. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  493. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  494. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  495. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  496. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  497. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  498. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  499. # make the default object type, "Geometry"
  500. self.type_obj_combo.setCurrentIndex(2)
  501. # updated units
  502. self.units = self.app.defaults['units'].upper()
  503. if self.units == "IN":
  504. self.decimals = 4
  505. self.addtool_entry.set_value(0.039)
  506. else:
  507. self.decimals = 2
  508. self.addtool_entry.set_value(1)
  509. # set the working variables to a known state
  510. self.paint_tools.clear()
  511. self.tooluid = 0
  512. self.default_data.clear()
  513. self.default_data.update({
  514. "name": '_paint',
  515. "plot": self.app.defaults["geometry_plot"],
  516. "cutz": float(self.app.defaults["geometry_cutz"]),
  517. "vtipdia": 0.1,
  518. "vtipangle": 30,
  519. "travelz": float(self.app.defaults["geometry_travelz"]),
  520. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  521. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  522. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  523. "dwell": self.app.defaults["geometry_dwell"],
  524. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  525. "multidepth": self.app.defaults["geometry_multidepth"],
  526. "ppname_g": self.app.defaults["geometry_ppname_g"],
  527. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  528. "extracut": self.app.defaults["geometry_extracut"],
  529. "toolchange": self.app.defaults["geometry_toolchange"],
  530. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  531. "endz": float(self.app.defaults["geometry_endz"]),
  532. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  533. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  534. "startz": self.app.defaults["geometry_startz"],
  535. "tooldia": float(self.app.defaults["tools_painttooldia"]),
  536. "paintmargin": float(self.app.defaults["tools_paintmargin"]),
  537. "paintmethod": self.app.defaults["tools_paintmethod"],
  538. "selectmethod": self.app.defaults["tools_selectmethod"],
  539. "pathconnect": self.app.defaults["tools_pathconnect"],
  540. "paintcontour": self.app.defaults["tools_paintcontour"],
  541. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  542. })
  543. # call on self.on_tool_add() counts as an call to self.build_ui()
  544. # through this, we add a initial row / tool in the tool_table
  545. self.on_tool_add(float(self.app.defaults["tools_painttooldia"]), muted=True)
  546. # if the Paint Method is "Single" disable the tool table context menu
  547. if self.default_data["selectmethod"] == "single":
  548. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  549. def build_ui(self):
  550. try:
  551. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  552. self.tools_table.itemChanged.disconnect()
  553. except (TypeError, AttributeError):
  554. pass
  555. # updated units
  556. self.units = self.app.defaults['units'].upper()
  557. sorted_tools = []
  558. for k, v in self.paint_tools.items():
  559. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  560. order = self.order_radio.get_value()
  561. if order == 'fwd':
  562. sorted_tools.sort(reverse=False)
  563. elif order == 'rev':
  564. sorted_tools.sort(reverse=True)
  565. else:
  566. pass
  567. n = len(sorted_tools)
  568. self.tools_table.setRowCount(n)
  569. tool_id = 0
  570. for tool_sorted in sorted_tools:
  571. for tooluid_key, tooluid_value in self.paint_tools.items():
  572. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  573. tool_id += 1
  574. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  575. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  576. row_no = tool_id - 1
  577. self.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  578. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  579. # There are no drill bits in MM with more than 2 decimals diameter
  580. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  581. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  582. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  583. tool_type_item = QtWidgets.QComboBox()
  584. for item in self.tool_type_item_options:
  585. tool_type_item.addItem(item)
  586. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  587. idx = tool_type_item.findText(tooluid_value['tool_type'])
  588. tool_type_item.setCurrentIndex(idx)
  589. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  590. self.tools_table.setItem(row_no, 1, dia) # Diameter
  591. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  592. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  593. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  594. # make the diameter column editable
  595. for row in range(tool_id):
  596. self.tools_table.item(row, 1).setFlags(
  597. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  598. # all the tools are selected by default
  599. self.tools_table.selectColumn(0)
  600. #
  601. self.tools_table.resizeColumnsToContents()
  602. self.tools_table.resizeRowsToContents()
  603. vertical_header = self.tools_table.verticalHeader()
  604. vertical_header.hide()
  605. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  606. horizontal_header = self.tools_table.horizontalHeader()
  607. horizontal_header.setMinimumSectionSize(10)
  608. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  609. horizontal_header.resizeSection(0, 20)
  610. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  611. # self.tools_table.setSortingEnabled(True)
  612. # sort by tool diameter
  613. # self.tools_table.sortItems(1)
  614. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  615. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  616. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  617. self.tools_table.itemChanged.connect(self.on_tool_edit)
  618. def on_combo_box_type(self):
  619. obj_type = self.box_combo_type.currentIndex()
  620. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  621. self.box_combo.setCurrentIndex(0)
  622. def on_tool_add(self, dia=None, muted=None):
  623. try:
  624. self.tools_table.itemChanged.disconnect()
  625. except TypeError:
  626. pass
  627. if dia:
  628. tool_dia = dia
  629. else:
  630. tool_dia = float(self.addtool_entry.get_value())
  631. if tool_dia is None:
  632. self.build_ui()
  633. self.app.inform.emit('[WARNING_NOTCL] %s' %
  634. _("Please enter a tool diameter to add, in Float format."))
  635. return
  636. # construct a list of all 'tooluid' in the self.tools
  637. tool_uid_list = []
  638. for tooluid_key in self.paint_tools:
  639. tool_uid_item = int(tooluid_key)
  640. tool_uid_list.append(tool_uid_item)
  641. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  642. if not tool_uid_list:
  643. max_uid = 0
  644. else:
  645. max_uid = max(tool_uid_list)
  646. self.tooluid = int(max_uid + 1)
  647. tool_dias = []
  648. for k, v in self.paint_tools.items():
  649. for tool_v in v.keys():
  650. if tool_v == 'tooldia':
  651. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  652. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  653. if muted is None:
  654. self.app.inform.emit('[WARNING_NOTCL] %s' %
  655. _("Adding tool cancelled. Tool already in Tool Table."))
  656. self.tools_table.itemChanged.connect(self.on_tool_edit)
  657. return
  658. else:
  659. if muted is None:
  660. self.app.inform.emit('[success] %s' %
  661. _("New tool added to Tool Table."))
  662. self.paint_tools.update({
  663. int(self.tooluid): {
  664. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  665. 'offset': 'Path',
  666. 'offset_value': 0.0,
  667. 'type': 'Iso',
  668. 'tool_type': 'V',
  669. 'data': dict(self.default_data),
  670. 'solid_geometry': []
  671. }
  672. })
  673. self.build_ui()
  674. def on_tool_edit(self):
  675. old_tool_dia = ''
  676. try:
  677. self.tools_table.itemChanged.disconnect()
  678. except TypeError:
  679. pass
  680. tool_dias = []
  681. for k, v in self.paint_tools.items():
  682. for tool_v in v.keys():
  683. if tool_v == 'tooldia':
  684. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  685. for row in range(self.tools_table.rowCount()):
  686. try:
  687. new_tool_dia = float(self.tools_table.item(row, 1).text())
  688. except ValueError:
  689. # try to convert comma to decimal point. if it's still not working error message and return
  690. try:
  691. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  692. except ValueError:
  693. self.app.inform.emit('[ERROR_NOTCL] %s' %
  694. _("Wrong value format entered, use a number."))
  695. return
  696. tooluid = int(self.tools_table.item(row, 3).text())
  697. # identify the tool that was edited and get it's tooluid
  698. if new_tool_dia not in tool_dias:
  699. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  700. self.app.inform.emit('[success] %s' %
  701. _("Tool from Tool Table was edited."))
  702. self.build_ui()
  703. return
  704. else:
  705. # identify the old tool_dia and restore the text in tool table
  706. for k, v in self.paint_tools.items():
  707. if k == tooluid:
  708. old_tool_dia = v['tooldia']
  709. break
  710. restore_dia_item = self.tools_table.item(row, 1)
  711. restore_dia_item.setText(str(old_tool_dia))
  712. self.app.inform.emit('[WARNING_NOTCL] %s' %
  713. _("Edit cancelled. New diameter value is already in the Tool Table."))
  714. self.build_ui()
  715. # def on_tool_copy(self, all=None):
  716. # try:
  717. # self.tools_table.itemChanged.disconnect()
  718. # except:
  719. # pass
  720. #
  721. # # find the tool_uid maximum value in the self.tools
  722. # uid_list = []
  723. # for key in self.paint_tools:
  724. # uid_list.append(int(key))
  725. # try:
  726. # max_uid = max(uid_list, key=int)
  727. # except ValueError:
  728. # max_uid = 0
  729. #
  730. # if all is None:
  731. # if self.tools_table.selectedItems():
  732. # for current_row in self.tools_table.selectedItems():
  733. # # sometime the header get selected and it has row number -1
  734. # # we don't want to do anything with the header :)
  735. # if current_row.row() < 0:
  736. # continue
  737. # try:
  738. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  739. # max_uid += 1
  740. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  741. # for td in self.paint_tools:
  742. # print("COPIED", self.paint_tools[td])
  743. # self.build_ui()
  744. # except AttributeError:
  745. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  746. # self.build_ui()
  747. # return
  748. # except Exception as e:
  749. # log.debug("on_tool_copy() --> " + str(e))
  750. # # deselect the table
  751. # # self.ui.geo_tools_table.clearSelection()
  752. # else:
  753. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  754. # self.build_ui()
  755. # return
  756. # else:
  757. # # we copy all tools in geo_tools_table
  758. # try:
  759. # temp_tools = dict(self.paint_tools)
  760. # max_uid += 1
  761. # for tooluid in temp_tools:
  762. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  763. # temp_tools.clear()
  764. # self.build_ui()
  765. # except Exception as e:
  766. # log.debug("on_tool_copy() --> " + str(e))
  767. #
  768. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  769. def on_tool_delete(self, rows_to_delete=None, all=None):
  770. try:
  771. self.tools_table.itemChanged.disconnect()
  772. except TypeError:
  773. pass
  774. deleted_tools_list = []
  775. if all:
  776. self.paint_tools.clear()
  777. self.build_ui()
  778. return
  779. if rows_to_delete:
  780. try:
  781. for row in rows_to_delete:
  782. tooluid_del = int(self.tools_table.item(row, 3).text())
  783. deleted_tools_list.append(tooluid_del)
  784. except TypeError:
  785. deleted_tools_list.append(rows_to_delete)
  786. for t in deleted_tools_list:
  787. self.paint_tools.pop(t, None)
  788. self.build_ui()
  789. return
  790. try:
  791. if self.tools_table.selectedItems():
  792. for row_sel in self.tools_table.selectedItems():
  793. row = row_sel.row()
  794. if row < 0:
  795. continue
  796. tooluid_del = int(self.tools_table.item(row, 3).text())
  797. deleted_tools_list.append(tooluid_del)
  798. for t in deleted_tools_list:
  799. self.paint_tools.pop(t, None)
  800. except AttributeError:
  801. self.app.inform.emit('[WARNING_NOTCL] %s' %
  802. _("Delete failed. Select a tool to delete."))
  803. return
  804. except Exception as e:
  805. log.debug(str(e))
  806. self.app.inform.emit('[success] %s' %
  807. _("Tool(s) deleted from Tool Table."))
  808. self.build_ui()
  809. def on_paint_button_click(self):
  810. # init values for the next usage
  811. self.reset_usage()
  812. self.app.report_usage("on_paint_button_click")
  813. # self.app.call_source = 'paint'
  814. # #####################################################
  815. # ######### Reading Parameters ########################
  816. # #####################################################
  817. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  818. self.overlap = float(self.paintoverlap_entry.get_value()) / 100.0
  819. self.connect = self.pathconnect_cb.get_value()
  820. self.contour = self.paintcontour_cb.get_value()
  821. self.select_method = self.selectmethod_combo.get_value()
  822. self.obj_name = self.obj_combo.currentText()
  823. # Get source object.
  824. try:
  825. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  826. except Exception as e:
  827. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  828. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  829. (_("Could not retrieve object: %s"),
  830. self.obj_name))
  831. return
  832. if self.paint_obj is None:
  833. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  834. (_("Object not found"),
  835. self.paint_obj))
  836. return
  837. # test if the Geometry Object is multigeo and return Fail if True because
  838. # for now Paint don't work on MultiGeo
  839. if self.paint_obj.multigeo is True:
  840. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  841. _("Can't do Paint on MultiGeo geometries"))
  842. return 'Fail'
  843. o_name = '%s_multitool_paint' % self.obj_name
  844. # use the selected tools in the tool table; get diameters
  845. self.tooldia_list = list()
  846. if self.tools_table.selectedItems():
  847. for x in self.tools_table.selectedItems():
  848. try:
  849. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  850. except ValueError:
  851. # try to convert comma to decimal point. if it's still not working error message and return
  852. try:
  853. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  854. except ValueError:
  855. self.app.inform.emit('[ERROR_NOTCL] %s' %
  856. _("Wrong value format entered, use a number."))
  857. continue
  858. self.tooldia_list.append(self.tooldia)
  859. else:
  860. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  861. return
  862. if self.select_method == "all":
  863. self.paint_poly_all(self.paint_obj,
  864. tooldia=self.tooldia_list,
  865. outname=self.o_name,
  866. overlap=self.overlap,
  867. connect=self.connect,
  868. contour=self.contour)
  869. elif self.select_method == "single":
  870. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  871. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  872. if self.app.ui.grid_snap_btn.isChecked():
  873. self.grid_status_memory = True
  874. self.app.ui.grid_snap_btn.trigger()
  875. else:
  876. self.grid_status_memory = False
  877. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  878. if self.app.is_legacy is False:
  879. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  880. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  881. else:
  882. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  883. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  884. elif self.select_method == "area":
  885. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  886. if self.app.is_legacy is False:
  887. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  888. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  889. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  890. else:
  891. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  892. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  893. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  894. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  895. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  896. elif self.select_method == 'ref':
  897. self.bound_obj_name = self.box_combo.currentText()
  898. # Get source object.
  899. try:
  900. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  901. except Exception as e:
  902. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  903. (_("Could not retrieve object"),
  904. self.obj_name))
  905. return "Could not retrieve object: %s" % self.obj_name
  906. self.paint_poly_ref(obj=self.paint_obj,
  907. sel_obj=self.bound_obj,
  908. tooldia=self.tooldia_list,
  909. overlap=self.overlap,
  910. outname=self.o_name,
  911. connect=self.connect,
  912. contour=self.contour)
  913. # To be called after clicking on the plot.
  914. def on_single_poly_mouse_release(self, event):
  915. if self.app.is_legacy is False:
  916. event_pos = event.pos
  917. right_button = 2
  918. event_is_dragging = self.app.event_is_dragging
  919. else:
  920. event_pos = (event.xdata, event.ydata)
  921. right_button = 3
  922. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  923. try:
  924. x = float(event_pos[0])
  925. y = float(event_pos[1])
  926. except TypeError:
  927. return
  928. event_pos = (x, y)
  929. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  930. # do paint single only for left mouse clicks
  931. if event.button == 1:
  932. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  933. if clicked_poly:
  934. if clicked_poly not in self.poly_dict.values():
  935. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  936. layer=0,
  937. shape=clicked_poly,
  938. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  939. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  940. visible=True)
  941. self.poly_dict[shape_id] = clicked_poly
  942. self.app.inform.emit(
  943. '%s: %d. %s' % (_("Added polygon"),
  944. int(len(self.poly_dict)),
  945. _("Click to add next polygon or right click to start painting."))
  946. )
  947. else:
  948. try:
  949. for k, v in list(self.poly_dict.items()):
  950. if v == clicked_poly:
  951. self.app.tool_shapes.remove(k)
  952. self.poly_dict.pop(k)
  953. break
  954. except TypeError:
  955. return
  956. self.app.inform.emit(
  957. '%s. %s' % (_("Removed polygon"),
  958. _("Click to add/remove next polygon or right click to start painting."))
  959. )
  960. self.app.tool_shapes.redraw()
  961. else:
  962. self.app.inform.emit(_("No polygon detected under click position."))
  963. elif event.button == right_button and event_is_dragging is False:
  964. # restore the Grid snapping if it was active before
  965. if self.grid_status_memory is True:
  966. self.app.ui.grid_snap_btn.trigger()
  967. if self.app.is_legacy is False:
  968. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  969. else:
  970. self.app.plotcanvas.graph_event_disconnect(self.mr)
  971. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  972. self.app.on_mouse_click_over_plot)
  973. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  974. self.app.on_mouse_click_release_over_plot)
  975. self.app.tool_shapes.clear(update=True)
  976. if self.poly_dict:
  977. poly_list = deepcopy(list(self.poly_dict.values()))
  978. self.paint_poly(self.paint_obj,
  979. poly_list=poly_list,
  980. tooldia=self.tooldia_list,
  981. overlap=self.overlap,
  982. connect=self.connect,
  983. contour=self.contour)
  984. self.poly_dict.clear()
  985. else:
  986. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  987. # To be called after clicking on the plot.
  988. def on_mouse_release(self, event):
  989. if self.app.is_legacy is False:
  990. event_pos = event.pos
  991. event_is_dragging = event.is_dragging
  992. right_button = 2
  993. else:
  994. event_pos = (event.xdata, event.ydata)
  995. event_is_dragging = self.app.plotcanvas.is_dragging
  996. right_button = 3
  997. try:
  998. x = float(event_pos[0])
  999. y = float(event_pos[1])
  1000. except TypeError:
  1001. return
  1002. event_pos = (x, y)
  1003. # do paint single only for left mouse clicks
  1004. if event.button == 1:
  1005. if not self.first_click:
  1006. self.first_click = True
  1007. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1008. _("Click the end point of the paint area."))
  1009. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1010. if self.app.grid_status() == True:
  1011. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  1012. else:
  1013. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1014. self.app.delete_selection_shape()
  1015. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1016. if self.app.grid_status() == True:
  1017. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1018. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1019. x1, y1 = curr_pos[0], curr_pos[1]
  1020. pt1 = (x0, y0)
  1021. pt2 = (x1, y0)
  1022. pt3 = (x1, y1)
  1023. pt4 = (x0, y1)
  1024. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1025. self.sel_rect.append(new_rectangle)
  1026. # add a temporary shape on canvas
  1027. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1028. self.first_click = False
  1029. return
  1030. elif event.button == right_button and self.mouse_is_dragging is False:
  1031. self.first_click = False
  1032. self.delete_tool_selection_shape()
  1033. if self.app.is_legacy is False:
  1034. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1035. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1036. else:
  1037. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1038. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1039. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1040. self.app.on_mouse_click_over_plot)
  1041. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1042. self.app.on_mouse_move_over_plot)
  1043. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1044. self.app.on_mouse_click_release_over_plot)
  1045. if len(self.sel_rect) == 0:
  1046. return
  1047. self.sel_rect = cascaded_union(self.sel_rect)
  1048. self.paint_poly_area(obj=self.paint_obj,
  1049. tooldia=self.tooldia_list,
  1050. sel_obj=self.sel_rect,
  1051. outname=self.o_name,
  1052. overlap=self.overlap,
  1053. connect=self.connect,
  1054. contour=self.contour)
  1055. # called on mouse move
  1056. def on_mouse_move(self, event):
  1057. if self.app.is_legacy is False:
  1058. event_pos = event.pos
  1059. event_is_dragging = event.is_dragging
  1060. right_button = 2
  1061. else:
  1062. event_pos = (event.xdata, event.ydata)
  1063. event_is_dragging = self.app.plotcanvas.is_dragging
  1064. right_button = 3
  1065. try:
  1066. x = float(event_pos[0])
  1067. y = float(event_pos[1])
  1068. except TypeError:
  1069. return
  1070. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1071. # detect mouse dragging motion
  1072. if event_is_dragging == 1:
  1073. self.mouse_is_dragging = True
  1074. else:
  1075. self.mouse_is_dragging = False
  1076. # update the cursor position
  1077. if self.app.grid_status() == True:
  1078. # Update cursor
  1079. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1080. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1081. symbol='++', edge_color=self.app.cursor_color_3D,
  1082. size=self.app.defaults["global_cursor_size"])
  1083. # update the positions on status bar
  1084. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1085. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1086. if self.cursor_pos is None:
  1087. self.cursor_pos = (0, 0)
  1088. dx = curr_pos[0] - float(self.cursor_pos[0])
  1089. dy = curr_pos[1] - float(self.cursor_pos[1])
  1090. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1091. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1092. # draw the utility geometry
  1093. if self.first_click:
  1094. self.app.delete_selection_shape()
  1095. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1096. coords=(curr_pos[0], curr_pos[1]))
  1097. def paint_poly(self, obj,
  1098. inside_pt=None,
  1099. poly_list=None,
  1100. tooldia=None,
  1101. overlap=None,
  1102. order=None,
  1103. margin=None,
  1104. method=None,
  1105. outname=None,
  1106. connect=None,
  1107. contour=None,
  1108. tools_storage=None,
  1109. plot=True,
  1110. run_threaded=True):
  1111. """
  1112. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1113. Note:
  1114. * The margin is taken directly from the form.
  1115. :param obj: painted object
  1116. :param inside_pt: [x, y]
  1117. :param tooldia: Diameter of the painting tool
  1118. :param overlap: Overlap of the tool between passes.
  1119. :param order: if the tools are ordered and how
  1120. :param margin: a border around painting area
  1121. :param outname: Name of the resulting Geometry Object.
  1122. :param connect: Connect lines to avoid tool lifts.
  1123. :param contour: Paint around the edges.
  1124. :param method: choice out of 'seed', 'normal', 'lines'
  1125. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1126. Usage of the different one is related to when this function is called from a TcL command.
  1127. :return: None
  1128. """
  1129. if isinstance(obj, FlatCAMGerber):
  1130. if self.app.defaults["gerber_buffering"] == 'no':
  1131. self.app.inform.emit('%s %s %s' %
  1132. (_("Paint Tool."), _("Normal painting polygon task started."),
  1133. _("Buffering geometry...")))
  1134. else:
  1135. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1136. else:
  1137. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1138. if isinstance(obj, FlatCAMGerber):
  1139. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1140. if isinstance(obj.solid_geometry, list):
  1141. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1142. else:
  1143. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1144. polygon_list = None
  1145. if inside_pt and poly_list is None:
  1146. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1147. elif inside_pt is None and poly_list:
  1148. polygon_list = poly_list
  1149. # No polygon?
  1150. if polygon_list is None:
  1151. self.app.log.warning('No polygon found.')
  1152. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1153. return
  1154. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1155. paint_margin = float(self.paintmargin_entry.get_value()) if margin is None else margin
  1156. # determine if to use the progressive plotting
  1157. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1158. name = outname if outname is not None else self.obj_name + "_paint"
  1159. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1160. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1161. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1162. order = order if order is not None else self.order_radio.get_value()
  1163. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1164. sorted_tools = []
  1165. if tooldia is not None:
  1166. try:
  1167. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1168. except AttributeError:
  1169. if not isinstance(tooldia, list):
  1170. sorted_tools = [float(tooldia)]
  1171. else:
  1172. sorted_tools = tooldia
  1173. else:
  1174. for row in range(self.tools_table.rowCount()):
  1175. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1176. # sort the tools if we have an order selected in the UI
  1177. if order == 'fwd':
  1178. sorted_tools.sort(reverse=False)
  1179. elif order == 'rev':
  1180. sorted_tools.sort(reverse=True)
  1181. proc = self.app.proc_container.new(_("Painting polygon..."))
  1182. # Initializes the new geometry object
  1183. def gen_paintarea(geo_obj, app_obj):
  1184. geo_obj.solid_geometry = list()
  1185. def paint_p(polyg, tooldiameter):
  1186. cpoly = None
  1187. try:
  1188. if paint_method == "seed":
  1189. # Type(cp) == FlatCAMRTreeStorage | None
  1190. cpoly = self.clear_polygon2(polyg,
  1191. tooldia=tooldiameter,
  1192. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1193. overlap=over,
  1194. contour=cont,
  1195. connect=conn,
  1196. prog_plot=prog_plot)
  1197. elif paint_method == "lines":
  1198. # Type(cp) == FlatCAMRTreeStorage | None
  1199. cpoly = self.clear_polygon3(polyg,
  1200. tooldia=tooldiameter,
  1201. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1202. overlap=over,
  1203. contour=cont,
  1204. connect=conn,
  1205. prog_plot=prog_plot)
  1206. else:
  1207. # Type(cp) == FlatCAMRTreeStorage | None
  1208. cpoly = self.clear_polygon(polyg,
  1209. tooldia=tooldiameter,
  1210. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1211. overlap=over,
  1212. contour=cont,
  1213. connect=conn,
  1214. prog_plot=prog_plot)
  1215. except FlatCAMApp.GracefulException:
  1216. return "fail"
  1217. except Exception as e:
  1218. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1219. if cpoly is not None:
  1220. geo_obj.solid_geometry += list(cpoly.get_objects())
  1221. return cpoly
  1222. else:
  1223. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1224. _('Geometry could not be painted completely'))
  1225. return None
  1226. current_uid = int(1)
  1227. tool_dia = None
  1228. for tool_dia in sorted_tools:
  1229. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1230. for k, v in tools_storage.items():
  1231. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1232. current_uid = int(k)
  1233. break
  1234. try:
  1235. poly_buf = [pol.buffer(-paint_margin) for pol in polygon_list]
  1236. cp = list()
  1237. try:
  1238. for pp in poly_buf:
  1239. cp.append(paint_p(pp, tooldiameter=tool_dia))
  1240. except TypeError:
  1241. cp = paint_p(poly_buf, tooldiameter=tool_dia)
  1242. total_geometry = list()
  1243. if cp:
  1244. try:
  1245. for x in cp:
  1246. total_geometry += list(x.get_objects())
  1247. except TypeError:
  1248. total_geometry = list(cp.get_objects())
  1249. except FlatCAMApp.GracefulException:
  1250. return "fail"
  1251. except Exception as e:
  1252. log.debug("Could not Paint the polygons. %s" % str(e))
  1253. app_obj.inform.emit('[ERROR] %s\n%s' %
  1254. (_("Could not do Paint. Try a different combination of parameters. "
  1255. "Or a different strategy of paint"),
  1256. str(e)
  1257. )
  1258. )
  1259. return "fail"
  1260. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1261. # dictionary and then reset the temporary list that stored that solid_geometry
  1262. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1263. tools_storage[current_uid]['data']['name'] = name
  1264. # clean the progressive plotted shapes if it was used
  1265. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1266. self.temp_shapes.clear(update=True)
  1267. # delete tools with empty geometry
  1268. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1269. for uid in list(tools_storage.keys()):
  1270. # if the solid_geometry (type=list) is empty
  1271. if not tools_storage[uid]['solid_geometry']:
  1272. tools_storage.pop(uid, None)
  1273. geo_obj.options["cnctooldia"] = str(tool_dia)
  1274. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1275. geo_obj.multigeo = True
  1276. geo_obj.multitool = True
  1277. geo_obj.tools.clear()
  1278. geo_obj.tools = dict(tools_storage)
  1279. geo_obj.solid_geometry = cascaded_union(tools_storage[current_uid]['solid_geometry'])
  1280. try:
  1281. a, b, c, d = geo_obj.solid_geometry.bounds
  1282. geo_obj.options['xmin'] = a
  1283. geo_obj.options['ymin'] = b
  1284. geo_obj.options['xmax'] = c
  1285. geo_obj.options['ymax'] = d
  1286. except Exception as e:
  1287. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1288. return
  1289. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1290. has_solid_geo = 0
  1291. for tooluid in geo_obj.tools:
  1292. if geo_obj.tools[tooluid]['solid_geometry']:
  1293. has_solid_geo += 1
  1294. if has_solid_geo == 0:
  1295. self.app.inform.emit('[ERROR] %s' %
  1296. _("There is no Painting Geometry in the file.\n"
  1297. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1298. "Change the painting parameters and try again."))
  1299. return
  1300. total_geometry[:] = []
  1301. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1302. # Experimental...
  1303. # print("Indexing...", end=' ')
  1304. # geo_obj.make_index()
  1305. # if errors == 0:
  1306. # print("[success] Paint single polygon Done")
  1307. # self.app.inform.emit("[success] Paint single polygon Done")
  1308. # else:
  1309. # print("[WARNING] Paint single polygon done with errors")
  1310. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1311. # "%d area(s) could not be painted.\n"
  1312. # "Use different paint parameters or edit the paint geometry and correct"
  1313. # "the issue."
  1314. # % errors)
  1315. def job_thread(app_obj):
  1316. try:
  1317. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1318. except FlatCAMApp.GracefulException:
  1319. proc.done()
  1320. return
  1321. except Exception as e:
  1322. proc.done()
  1323. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1324. ('PaintTool.paint_poly()',
  1325. str(e)))
  1326. return
  1327. proc.done()
  1328. # focus on Selected Tab
  1329. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1330. self.app.inform.emit(_("Polygon Paint started ..."))
  1331. # Promise object with the new name
  1332. self.app.collection.promise(name)
  1333. if run_threaded:
  1334. # Background
  1335. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1336. else:
  1337. job_thread(app_obj=self.app)
  1338. def paint_poly_all(self, obj,
  1339. tooldia=None,
  1340. overlap=None,
  1341. order=None,
  1342. margin=None,
  1343. method=None,
  1344. outname=None,
  1345. connect=None,
  1346. contour=None,
  1347. tools_storage=None,
  1348. plot=True,
  1349. run_threaded=True):
  1350. """
  1351. Paints all polygons in this object.
  1352. :param obj: painted object
  1353. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1354. :param overlap: value by which the paths will overlap
  1355. :param order: if the tools are ordered and how
  1356. :param margin: a border around painting area
  1357. :param outname: name of the resulting object
  1358. :param connect: Connect lines to avoid tool lifts.
  1359. :param contour: Paint around the edges.
  1360. :param method: choice out of 'seed', 'normal', 'lines'
  1361. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1362. Usage of the different one is related to when this function is called from a TcL command.
  1363. :return:
  1364. """
  1365. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1366. if margin is not None:
  1367. paint_margin = margin
  1368. else:
  1369. paint_margin = float(self.paintmargin_entry.get_value())
  1370. # determine if to use the progressive plotting
  1371. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1372. prog_plot = True
  1373. else:
  1374. prog_plot = False
  1375. proc = self.app.proc_container.new(_("Painting polygons..."))
  1376. name = outname if outname is not None else self.obj_name + "_paint"
  1377. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1378. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1379. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1380. order = order if order is not None else self.order_radio.get_value()
  1381. sorted_tools = []
  1382. if tooldia is not None:
  1383. try:
  1384. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1385. except AttributeError:
  1386. if not isinstance(tooldia, list):
  1387. sorted_tools = [float(tooldia)]
  1388. else:
  1389. sorted_tools = tooldia
  1390. else:
  1391. for row in range(self.tools_table.rowCount()):
  1392. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1393. if tools_storage is not None:
  1394. tools_storage = tools_storage
  1395. else:
  1396. tools_storage = self.paint_tools
  1397. # This is a recursive generator of individual Polygons.
  1398. # Note: Double check correct implementation. Might exit
  1399. # early if it finds something that is not a Polygon?
  1400. # def recurse(geo):
  1401. # try:
  1402. # for subg in geo:
  1403. # for subsubg in recurse(subg):
  1404. # yield subsubg
  1405. # except TypeError:
  1406. # if isinstance(geo, Polygon):
  1407. # yield geo
  1408. #
  1409. # raise StopIteration
  1410. def recurse(geometry, reset=True):
  1411. """
  1412. Creates a list of non-iterable linear geometry objects.
  1413. Results are placed in self.flat_geometry
  1414. :param geometry: Shapely type or list or list of list of such.
  1415. :param reset: Clears the contents of self.flat_geometry.
  1416. """
  1417. if self.app.abort_flag:
  1418. # graceful abort requested by the user
  1419. raise FlatCAMApp.GracefulException
  1420. if geometry is None:
  1421. return
  1422. if reset:
  1423. self.flat_geometry = []
  1424. # ## If iterable, expand recursively.
  1425. try:
  1426. for geo in geometry:
  1427. if geo is not None:
  1428. recurse(geometry=geo, reset=False)
  1429. # ## Not iterable, do the actual indexing and add.
  1430. except TypeError:
  1431. if isinstance(geometry, LinearRing):
  1432. g = Polygon(geometry)
  1433. self.flat_geometry.append(g)
  1434. else:
  1435. self.flat_geometry.append(geometry)
  1436. return self.flat_geometry
  1437. # Initializes the new geometry object
  1438. def gen_paintarea(geo_obj, app_obj):
  1439. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1440. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1441. log.debug("Paint Tool. Normal painting all task started.")
  1442. if isinstance(obj, FlatCAMGerber):
  1443. if app_obj.defaults["gerber_buffering"] == 'no':
  1444. app_obj.inform.emit('%s %s' %
  1445. (_("Paint Tool. Normal painting all task started."),
  1446. _("Buffering geometry...")))
  1447. else:
  1448. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1449. else:
  1450. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1451. tool_dia = None
  1452. if order == 'fwd':
  1453. sorted_tools.sort(reverse=False)
  1454. elif order == 'rev':
  1455. sorted_tools.sort(reverse=True)
  1456. else:
  1457. pass
  1458. if isinstance(obj, FlatCAMGerber):
  1459. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1460. if isinstance(obj.solid_geometry, list):
  1461. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1462. else:
  1463. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1464. try:
  1465. a, b, c, d = obj.bounds()
  1466. geo_obj.options['xmin'] = a
  1467. geo_obj.options['ymin'] = b
  1468. geo_obj.options['xmax'] = c
  1469. geo_obj.options['ymax'] = d
  1470. except Exception as e:
  1471. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1472. return
  1473. total_geometry = []
  1474. current_uid = int(1)
  1475. geo_obj.solid_geometry = []
  1476. for tool_dia in sorted_tools:
  1477. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1478. app_obj.inform.emit(
  1479. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1480. str(tool_dia),
  1481. self.units.lower(),
  1482. _('started'))
  1483. )
  1484. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1485. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1486. for k, v in tools_storage.items():
  1487. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1488. current_uid = int(k)
  1489. break
  1490. painted_area = recurse(obj.solid_geometry)
  1491. # variables to display the percentage of work done
  1492. geo_len = len(painted_area)
  1493. old_disp_number = 0
  1494. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1495. pol_nr = 0
  1496. for geo in painted_area:
  1497. try:
  1498. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1499. if not isinstance(geo, Polygon):
  1500. continue
  1501. poly_buf = geo.buffer(-paint_margin)
  1502. if paint_method == "seed":
  1503. # Type(cp) == FlatCAMRTreeStorage | None
  1504. cp = self.clear_polygon2(poly_buf,
  1505. tooldia=tool_dia,
  1506. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1507. overlap=over,
  1508. contour=cont,
  1509. connect=conn,
  1510. prog_plot=prog_plot)
  1511. elif paint_method == "lines":
  1512. # Type(cp) == FlatCAMRTreeStorage | None
  1513. cp = self.clear_polygon3(poly_buf,
  1514. tooldia=tool_dia,
  1515. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1516. overlap=over,
  1517. contour=cont,
  1518. connect=conn,
  1519. prog_plot=prog_plot)
  1520. else:
  1521. # Type(cp) == FlatCAMRTreeStorage | None
  1522. cp = self.clear_polygon(poly_buf,
  1523. tooldia=tool_dia,
  1524. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1525. overlap=over,
  1526. contour=cont,
  1527. connect=conn,
  1528. prog_plot=prog_plot)
  1529. if cp is not None:
  1530. total_geometry += list(cp.get_objects())
  1531. except FlatCAMApp.GracefulException:
  1532. return "fail"
  1533. except Exception as e:
  1534. log.debug("Could not Paint the polygons. %s" % str(e))
  1535. self.app.inform.emit('[ERROR] %s\n%s' %
  1536. (_("Could not do Paint All. Try a different combination of parameters. "
  1537. "Or a different Method of paint"),
  1538. str(e)))
  1539. return "fail"
  1540. pol_nr += 1
  1541. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1542. # log.debug("Polygons cleared: %d" % pol_nr)
  1543. if old_disp_number < disp_number <= 100:
  1544. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1545. old_disp_number = disp_number
  1546. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1547. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1548. # dictionary and then reset the temporary list that stored that solid_geometry
  1549. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1550. tools_storage[current_uid]['data']['name'] = name
  1551. total_geometry[:] = []
  1552. # clean the progressive plotted shapes if it was used
  1553. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1554. self.temp_shapes.clear(update=True)
  1555. # delete tools with empty geometry
  1556. keys_to_delete = []
  1557. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1558. for uid in tools_storage:
  1559. # if the solid_geometry (type=list) is empty
  1560. if not tools_storage[uid]['solid_geometry']:
  1561. keys_to_delete.append(uid)
  1562. # actual delete of keys from the tools_storage dict
  1563. for k in keys_to_delete:
  1564. tools_storage.pop(k, None)
  1565. geo_obj.options["cnctooldia"] = str(tool_dia)
  1566. # this turn on the FlatCAMCNCJob plot for multiple tools
  1567. geo_obj.multigeo = True
  1568. geo_obj.multitool = True
  1569. geo_obj.tools.clear()
  1570. geo_obj.tools = dict(tools_storage)
  1571. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1572. has_solid_geo = 0
  1573. for tooluid in geo_obj.tools:
  1574. if geo_obj.tools[tooluid]['solid_geometry']:
  1575. has_solid_geo += 1
  1576. if has_solid_geo == 0:
  1577. self.app.inform.emit('[ERROR] %s' %
  1578. _("There is no Painting Geometry in the file.\n"
  1579. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1580. "Change the painting parameters and try again."))
  1581. return
  1582. # Experimental...
  1583. # print("Indexing...", end=' ')
  1584. # geo_obj.make_index()
  1585. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1586. # Initializes the new geometry object
  1587. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1588. assert isinstance(geo_obj, FlatCAMGeometry), \
  1589. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1590. log.debug("Paint Tool. Rest machining painting all task started.")
  1591. if isinstance(obj, FlatCAMGerber):
  1592. if app_obj.defaults["gerber_buffering"] == 'no':
  1593. app_obj.inform.emit('%s %s %s' %
  1594. (_("Paint Tool."), _("Rest machining painting all task started."),
  1595. _("Buffering geometry...")))
  1596. else:
  1597. app_obj.inform.emit('%s %s' %
  1598. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1599. else:
  1600. app_obj.inform.emit('%s %s' %
  1601. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1602. tool_dia = None
  1603. sorted_tools.sort(reverse=True)
  1604. cleared_geo = []
  1605. current_uid = int(1)
  1606. geo_obj.solid_geometry = []
  1607. if isinstance(obj, FlatCAMGerber):
  1608. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1609. if isinstance(obj.solid_geometry, list):
  1610. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1611. else:
  1612. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1613. try:
  1614. a, b, c, d = obj.bounds()
  1615. geo_obj.options['xmin'] = a
  1616. geo_obj.options['ymin'] = b
  1617. geo_obj.options['xmax'] = c
  1618. geo_obj.options['ymax'] = d
  1619. except Exception as e:
  1620. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1621. return
  1622. for tool_dia in sorted_tools:
  1623. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1624. app_obj.inform.emit(
  1625. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1626. str(tool_dia),
  1627. self.units.lower(),
  1628. _('started'))
  1629. )
  1630. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1631. painted_area = recurse(obj.solid_geometry)
  1632. # variables to display the percentage of work done
  1633. geo_len = int(len(painted_area) / 100)
  1634. old_disp_number = 0
  1635. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1636. pol_nr = 0
  1637. for geo in painted_area:
  1638. try:
  1639. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1640. poly_buf = geo.buffer(-paint_margin)
  1641. cp = None
  1642. if paint_method == "standard":
  1643. # Type(cp) == FlatCAMRTreeStorage | None
  1644. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1645. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1646. overlap=over, contour=cont, connect=conn,
  1647. prog_plot=prog_plot)
  1648. elif paint_method == "seed":
  1649. # Type(cp) == FlatCAMRTreeStorage | None
  1650. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1651. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1652. overlap=over, contour=cont, connect=conn,
  1653. prog_plot=prog_plot)
  1654. elif paint_method == "lines":
  1655. # Type(cp) == FlatCAMRTreeStorage | None
  1656. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1657. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1658. overlap=over, contour=cont, connect=conn,
  1659. prog_plot=prog_plot)
  1660. if cp is not None:
  1661. cleared_geo += list(cp.get_objects())
  1662. except FlatCAMApp.GracefulException:
  1663. return "fail"
  1664. except Exception as e:
  1665. log.debug("Could not Paint the polygons. %s" % str(e))
  1666. self.app.inform.emit('[ERROR] %s\n%s' %
  1667. (_("Could not do Paint All. Try a different combination of parameters. "
  1668. "Or a different Method of paint"),
  1669. str(e)))
  1670. return "fail"
  1671. pol_nr += 1
  1672. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1673. # log.debug("Polygons cleared: %d" % pol_nr)
  1674. if old_disp_number < disp_number <= 100:
  1675. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1676. old_disp_number = disp_number
  1677. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1678. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1679. for k, v in tools_storage.items():
  1680. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1681. current_uid = int(k)
  1682. break
  1683. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1684. # then reset the temporary list that stored that solid_geometry
  1685. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1686. tools_storage[current_uid]['data']['name'] = name
  1687. cleared_geo[:] = []
  1688. geo_obj.options["cnctooldia"] = str(tool_dia)
  1689. # this turn on the FlatCAMCNCJob plot for multiple tools
  1690. geo_obj.multigeo = True
  1691. geo_obj.multitool = True
  1692. geo_obj.tools.clear()
  1693. geo_obj.tools = dict(tools_storage)
  1694. # clean the progressive plotted shapes if it was used
  1695. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1696. self.temp_shapes.clear(update=True)
  1697. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1698. has_solid_geo = 0
  1699. for tooluid in geo_obj.tools:
  1700. if geo_obj.tools[tooluid]['solid_geometry']:
  1701. has_solid_geo += 1
  1702. if has_solid_geo == 0:
  1703. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1704. _("There is no Painting Geometry in the file.\n"
  1705. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1706. "Change the painting parameters and try again."))
  1707. return
  1708. # Experimental...
  1709. # print("Indexing...", end=' ')
  1710. # geo_obj.make_index()
  1711. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1712. def job_thread(app_obj):
  1713. try:
  1714. if self.rest_cb.isChecked():
  1715. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  1716. else:
  1717. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1718. except FlatCAMApp.GracefulException:
  1719. proc.done()
  1720. return
  1721. except Exception:
  1722. proc.done()
  1723. traceback.print_stack()
  1724. return
  1725. proc.done()
  1726. # focus on Selected Tab
  1727. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1728. self.app.inform.emit(_("Polygon Paint started ..."))
  1729. # Promise object with the new name
  1730. self.app.collection.promise(name)
  1731. if run_threaded:
  1732. # Background
  1733. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1734. else:
  1735. job_thread(app_obj=self.app)
  1736. def paint_poly_area(self, obj, sel_obj,
  1737. tooldia=None,
  1738. overlap=None,
  1739. order=None,
  1740. margin=None,
  1741. method=None,
  1742. outname=None,
  1743. connect=None,
  1744. contour=None,
  1745. tools_storage=None,
  1746. plot=True,
  1747. run_threaded=True):
  1748. """
  1749. Paints all polygons in this object that are within the sel_obj object
  1750. :param obj: painted object
  1751. :param sel_obj: paint only what is inside this object bounds
  1752. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1753. :param overlap: value by which the paths will overlap
  1754. :param order: if the tools are ordered and how
  1755. :param margin: a border around painting area
  1756. :param outname: name of the resulting object
  1757. :param connect: Connect lines to avoid tool lifts.
  1758. :param contour: Paint around the edges.
  1759. :param method: choice out of 'seed', 'normal', 'lines'
  1760. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1761. Usage of the different one is related to when this function is called from a TcL command.
  1762. :return:
  1763. """
  1764. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1765. if margin is not None:
  1766. paint_margin = margin
  1767. else:
  1768. try:
  1769. paint_margin = float(self.paintmargin_entry.get_value())
  1770. except ValueError:
  1771. # try to convert comma to decimal point. if it's still not working error message and return
  1772. try:
  1773. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1774. except ValueError:
  1775. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1776. _("Wrong value format entered, use a number."))
  1777. return
  1778. # determine if to use the progressive plotting
  1779. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1780. prog_plot = True
  1781. else:
  1782. prog_plot = False
  1783. proc = self.app.proc_container.new(_("Painting polygons..."))
  1784. name = outname if outname is not None else self.obj_name + "_paint"
  1785. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1786. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1787. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1788. order = order if order is not None else self.order_radio.get_value()
  1789. sorted_tools = []
  1790. if tooldia is not None:
  1791. try:
  1792. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1793. except AttributeError:
  1794. if not isinstance(tooldia, list):
  1795. sorted_tools = [float(tooldia)]
  1796. else:
  1797. sorted_tools = tooldia
  1798. else:
  1799. for row in range(self.tools_table.rowCount()):
  1800. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1801. if tools_storage is not None:
  1802. tools_storage = tools_storage
  1803. else:
  1804. tools_storage = self.paint_tools
  1805. def recurse(geometry, reset=True):
  1806. """
  1807. Creates a list of non-iterable linear geometry objects.
  1808. Results are placed in self.flat_geometry
  1809. :param geometry: Shapely type or list or list of list of such.
  1810. :param reset: Clears the contents of self.flat_geometry.
  1811. """
  1812. if self.app.abort_flag:
  1813. # graceful abort requested by the user
  1814. raise FlatCAMApp.GracefulException
  1815. if geometry is None:
  1816. return
  1817. if reset:
  1818. self.flat_geometry = []
  1819. # ## If iterable, expand recursively.
  1820. try:
  1821. for geo in geometry:
  1822. if geo is not None:
  1823. recurse(geometry=geo, reset=False)
  1824. # ## Not iterable, do the actual indexing and add.
  1825. except TypeError:
  1826. if isinstance(geometry, LinearRing):
  1827. g = Polygon(geometry)
  1828. self.flat_geometry.append(g)
  1829. else:
  1830. self.flat_geometry.append(geometry)
  1831. return self.flat_geometry
  1832. # Initializes the new geometry object
  1833. def gen_paintarea(geo_obj, app_obj):
  1834. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1835. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1836. log.debug("Paint Tool. Normal painting area task started.")
  1837. if isinstance(obj, FlatCAMGerber):
  1838. if app_obj.defaults["gerber_buffering"] == 'no':
  1839. app_obj.inform.emit('%s %s %s' %
  1840. (_("Paint Tool."),
  1841. _("Normal painting area task started."),
  1842. _("Buffering geometry...")))
  1843. else:
  1844. app_obj.inform.emit('%s %s' %
  1845. (_("Paint Tool."), _("Normal painting area task started.")))
  1846. else:
  1847. app_obj.inform.emit('%s %s' %
  1848. (_("Paint Tool."), _("Normal painting area task started.")))
  1849. tool_dia = None
  1850. if order == 'fwd':
  1851. sorted_tools.sort(reverse=False)
  1852. elif order == 'rev':
  1853. sorted_tools.sort(reverse=True)
  1854. else:
  1855. pass
  1856. # this is were heavy lifting is done and creating the geometry to be painted
  1857. target_geo = MultiPolygon(obj.solid_geometry)
  1858. if isinstance(obj, FlatCAMGerber):
  1859. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1860. if isinstance(target_geo, list):
  1861. target_geo = MultiPolygon(target_geo).buffer(0)
  1862. else:
  1863. target_geo = target_geo.buffer(0)
  1864. geo_to_paint = target_geo.intersection(sel_obj)
  1865. painted_area = recurse(geo_to_paint)
  1866. try:
  1867. a, b, c, d = self.paint_bounds(geo_to_paint)
  1868. geo_obj.options['xmin'] = a
  1869. geo_obj.options['ymin'] = b
  1870. geo_obj.options['xmax'] = c
  1871. geo_obj.options['ymax'] = d
  1872. except Exception as e:
  1873. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1874. return
  1875. total_geometry = []
  1876. current_uid = int(1)
  1877. geo_obj.solid_geometry = []
  1878. for tool_dia in sorted_tools:
  1879. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1880. app_obj.inform.emit(
  1881. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1882. str(tool_dia),
  1883. self.units.lower(),
  1884. _('started'))
  1885. )
  1886. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1887. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1888. for k, v in tools_storage.items():
  1889. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1890. current_uid = int(k)
  1891. break
  1892. # variables to display the percentage of work done
  1893. geo_len = len(painted_area)
  1894. old_disp_number = 0
  1895. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1896. pol_nr = 0
  1897. for geo in painted_area:
  1898. try:
  1899. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1900. if not isinstance(geo, Polygon):
  1901. continue
  1902. poly_buf = geo.buffer(-paint_margin)
  1903. if paint_method == "seed":
  1904. # Type(cp) == FlatCAMRTreeStorage | None
  1905. cp = self.clear_polygon2(poly_buf,
  1906. tooldia=tool_dia,
  1907. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1908. overlap=over,
  1909. contour=cont,
  1910. connect=conn,
  1911. prog_plot=prog_plot)
  1912. elif paint_method == "lines":
  1913. # Type(cp) == FlatCAMRTreeStorage | None
  1914. cp = self.clear_polygon3(poly_buf,
  1915. tooldia=tool_dia,
  1916. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1917. overlap=over,
  1918. contour=cont,
  1919. connect=conn,
  1920. prog_plot=prog_plot)
  1921. else:
  1922. # Type(cp) == FlatCAMRTreeStorage | None
  1923. cp = self.clear_polygon(poly_buf,
  1924. tooldia=tool_dia,
  1925. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1926. overlap=over,
  1927. contour=cont,
  1928. connect=conn,
  1929. prog_plot=prog_plot)
  1930. if cp is not None:
  1931. total_geometry += list(cp.get_objects())
  1932. except FlatCAMApp.GracefulException:
  1933. return "fail"
  1934. except Exception as e:
  1935. log.debug("Could not Paint the polygons. %s" % str(e))
  1936. self.app.inform.emit('[ERROR] %s\n%s' %
  1937. (_("Could not do Paint All. Try a different combination of parameters. "
  1938. "Or a different Method of paint"), str(e)))
  1939. return
  1940. pol_nr += 1
  1941. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1942. # log.debug("Polygons cleared: %d" % pol_nr)
  1943. if old_disp_number < disp_number <= 100:
  1944. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1945. old_disp_number = disp_number
  1946. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1947. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1948. # dictionary and then reset the temporary list that stored that solid_geometry
  1949. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1950. tools_storage[current_uid]['data']['name'] = name
  1951. total_geometry[:] = []
  1952. # clean the progressive plotted shapes if it was used
  1953. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1954. self.temp_shapes.clear(update=True)
  1955. # delete tools with empty geometry
  1956. keys_to_delete = []
  1957. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1958. for uid in tools_storage:
  1959. # if the solid_geometry (type=list) is empty
  1960. if not tools_storage[uid]['solid_geometry']:
  1961. keys_to_delete.append(uid)
  1962. # actual delete of keys from the tools_storage dict
  1963. for k in keys_to_delete:
  1964. tools_storage.pop(k, None)
  1965. geo_obj.options["cnctooldia"] = str(tool_dia)
  1966. # this turn on the FlatCAMCNCJob plot for multiple tools
  1967. geo_obj.multigeo = True
  1968. geo_obj.multitool = True
  1969. geo_obj.tools.clear()
  1970. geo_obj.tools = dict(tools_storage)
  1971. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1972. has_solid_geo = 0
  1973. for tooluid in geo_obj.tools:
  1974. if geo_obj.tools[tooluid]['solid_geometry']:
  1975. has_solid_geo += 1
  1976. if has_solid_geo == 0:
  1977. self.app.inform.emit('[ERROR] %s' %
  1978. _("There is no Painting Geometry in the file.\n"
  1979. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1980. "Change the painting parameters and try again."))
  1981. return
  1982. # Experimental...
  1983. # print("Indexing...", end=' ')
  1984. # geo_obj.make_index()
  1985. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  1986. # Initializes the new geometry object
  1987. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1988. assert isinstance(geo_obj, FlatCAMGeometry), \
  1989. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1990. log.debug("Paint Tool. Rest machining painting area task started.")
  1991. if isinstance(obj, FlatCAMGerber):
  1992. if app_obj.defaults["gerber_buffering"] == 'no':
  1993. app_obj.inform.emit('%s %s %s' %
  1994. (_("Paint Tool."),
  1995. _("Rest machining painting area task started."),
  1996. _("Buffering geometry...")))
  1997. else:
  1998. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  1999. else:
  2000. app_obj.inform.emit('%s %s' %
  2001. (_("Paint Tool."), _("Rest machining painting area task started.")))
  2002. tool_dia = None
  2003. sorted_tools.sort(reverse=True)
  2004. cleared_geo = []
  2005. current_uid = int(1)
  2006. geo_obj.solid_geometry = []
  2007. # this is were heavy lifting is done and creating the geometry to be painted
  2008. target_geo = obj.solid_geometry
  2009. if isinstance(obj, FlatCAMGerber):
  2010. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2011. if isinstance(target_geo, list):
  2012. target_geo = MultiPolygon(target_geo).buffer(0)
  2013. else:
  2014. target_geo = target_geo.buffer(0)
  2015. geo_to_paint = target_geo.intersection(sel_obj)
  2016. painted_area = recurse(geo_to_paint)
  2017. try:
  2018. a, b, c, d = obj.bounds()
  2019. geo_obj.options['xmin'] = a
  2020. geo_obj.options['ymin'] = b
  2021. geo_obj.options['xmax'] = c
  2022. geo_obj.options['ymax'] = d
  2023. except Exception as e:
  2024. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2025. return
  2026. for tool_dia in sorted_tools:
  2027. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2028. app_obj.inform.emit(
  2029. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2030. str(tool_dia),
  2031. self.units.lower(),
  2032. _('started'))
  2033. )
  2034. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2035. # variables to display the percentage of work done
  2036. geo_len = len(painted_area)
  2037. old_disp_number = 0
  2038. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2039. pol_nr = 0
  2040. for geo in painted_area:
  2041. try:
  2042. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2043. poly_buf = geo.buffer(-paint_margin)
  2044. cp = None
  2045. if paint_method == "standard":
  2046. # Type(cp) == FlatCAMRTreeStorage | None
  2047. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2048. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2049. overlap=over, contour=cont, connect=conn,
  2050. prog_plot=prog_plot)
  2051. elif paint_method == "seed":
  2052. # Type(cp) == FlatCAMRTreeStorage | None
  2053. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2054. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2055. overlap=over, contour=cont, connect=conn,
  2056. prog_plot=prog_plot)
  2057. elif paint_method == "lines":
  2058. # Type(cp) == FlatCAMRTreeStorage | None
  2059. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2060. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2061. overlap=over, contour=cont, connect=conn,
  2062. prog_plot=prog_plot)
  2063. if cp is not None:
  2064. cleared_geo += list(cp.get_objects())
  2065. except FlatCAMApp.GracefulException:
  2066. return "fail"
  2067. except Exception as e:
  2068. log.debug("Could not Paint the polygons. %s" % str(e))
  2069. self.app.inform.emit('[ERROR] %s\n%s' %
  2070. (_("Could not do Paint All. Try a different combination of parameters. "
  2071. "Or a different Method of paint"), str(e)))
  2072. return
  2073. pol_nr += 1
  2074. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2075. # log.debug("Polygons cleared: %d" % pol_nr)
  2076. if old_disp_number < disp_number <= 100:
  2077. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2078. old_disp_number = disp_number
  2079. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2080. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2081. for k, v in tools_storage.items():
  2082. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2083. current_uid = int(k)
  2084. break
  2085. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2086. # then reset the temporary list that stored that solid_geometry
  2087. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2088. tools_storage[current_uid]['data']['name'] = name
  2089. cleared_geo[:] = []
  2090. geo_obj.options["cnctooldia"] = str(tool_dia)
  2091. # this turn on the FlatCAMCNCJob plot for multiple tools
  2092. geo_obj.multigeo = True
  2093. geo_obj.multitool = True
  2094. geo_obj.tools.clear()
  2095. geo_obj.tools = dict(self.paint_tools)
  2096. # clean the progressive plotted shapes if it was used
  2097. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2098. self.temp_shapes.clear(update=True)
  2099. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2100. has_solid_geo = 0
  2101. for tooluid in geo_obj.tools:
  2102. if geo_obj.tools[tooluid]['solid_geometry']:
  2103. has_solid_geo += 1
  2104. if has_solid_geo == 0:
  2105. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2106. _("There is no Painting Geometry in the file.\n"
  2107. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2108. "Change the painting parameters and try again."))
  2109. return
  2110. # Experimental...
  2111. # print("Indexing...", end=' ')
  2112. # geo_obj.make_index()
  2113. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2114. def job_thread(app_obj):
  2115. try:
  2116. if self.rest_cb.isChecked():
  2117. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2118. else:
  2119. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2120. except FlatCAMApp.GracefulException:
  2121. proc.done()
  2122. return
  2123. except Exception:
  2124. proc.done()
  2125. traceback.print_stack()
  2126. return
  2127. proc.done()
  2128. # focus on Selected Tab
  2129. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2130. self.app.inform.emit(_("Polygon Paint started ..."))
  2131. # Promise object with the new name
  2132. self.app.collection.promise(name)
  2133. if run_threaded:
  2134. # Background
  2135. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2136. else:
  2137. job_thread(app_obj=self.app)
  2138. def paint_poly_ref(self, obj, sel_obj,
  2139. tooldia=None,
  2140. overlap=None,
  2141. order=None,
  2142. margin=None,
  2143. method=None,
  2144. outname=None,
  2145. connect=None,
  2146. contour=None,
  2147. tools_storage=None,
  2148. plot=True,
  2149. run_threaded=True):
  2150. """
  2151. Paints all polygons in this object that are within the sel_obj object
  2152. :param obj: painted object
  2153. :param sel_obj: paint only what is inside this object bounds
  2154. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2155. :param overlap: value by which the paths will overlap
  2156. :param order: if the tools are ordered and how
  2157. :param margin: a border around painting area
  2158. :param outname: name of the resulting object
  2159. :param connect: Connect lines to avoid tool lifts.
  2160. :param contour: Paint around the edges.
  2161. :param method: choice out of 'seed', 'normal', 'lines'
  2162. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2163. Usage of the different one is related to when this function is called from a TcL command.
  2164. :return:
  2165. """
  2166. geo = sel_obj.solid_geometry
  2167. try:
  2168. if isinstance(geo, MultiPolygon):
  2169. env_obj = geo.convex_hull
  2170. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2171. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2172. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2173. else:
  2174. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2175. env_obj = env_obj.convex_hull
  2176. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2177. except Exception as e:
  2178. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  2179. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2180. return
  2181. self.paint_poly_area(obj=obj,
  2182. sel_obj=sel_rect,
  2183. tooldia=tooldia,
  2184. overlap=overlap,
  2185. order=order,
  2186. margin=margin,
  2187. method=method,
  2188. outname=outname,
  2189. connect=connect,
  2190. contour=contour,
  2191. tools_storage=tools_storage,
  2192. plot=plot,
  2193. run_threaded=run_threaded)
  2194. @staticmethod
  2195. def paint_bounds(geometry):
  2196. def bounds_rec(o):
  2197. if type(o) is list:
  2198. minx = Inf
  2199. miny = Inf
  2200. maxx = -Inf
  2201. maxy = -Inf
  2202. for k in o:
  2203. try:
  2204. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2205. except Exception as e:
  2206. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2207. return
  2208. minx = min(minx, minx_)
  2209. miny = min(miny, miny_)
  2210. maxx = max(maxx, maxx_)
  2211. maxy = max(maxy, maxy_)
  2212. return minx, miny, maxx, maxy
  2213. else:
  2214. # it's a Shapely object, return it's bounds
  2215. return o.bounds
  2216. return bounds_rec(geometry)
  2217. def reset_fields(self):
  2218. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))