ToolPaint.py 114 KB

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