ToolPaint.py 114 KB

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