ToolPaint.py 124 KB

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