ToolPaint.py 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  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.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  878. self.app.plotcanvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  879. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  880. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  881. self.app.plotcanvas.graph_event_connect('mouse_press', doit)
  882. elif select_method == "area":
  883. self.app.inform.emit('[WARNING_NOTCL] %s' %
  884. _("Click the start point of the paint area."))
  885. # use the first tool in the tool table; get the diameter
  886. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  887. # To be called after clicking on the plot.
  888. def on_mouse_release(event):
  889. # do paint single only for left mouse clicks
  890. if event.button == 1:
  891. if not self.first_click:
  892. self.first_click = True
  893. self.app.inform.emit('[WARNING_NOTCL] %s' %
  894. _("Click the end point of the paint area."))
  895. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  896. if self.app.grid_status() == True:
  897. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  898. else:
  899. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  900. self.app.delete_selection_shape()
  901. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  902. if self.app.grid_status() == True:
  903. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  904. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  905. x1, y1 = curr_pos[0], curr_pos[1]
  906. pt1 = (x0, y0)
  907. pt2 = (x1, y0)
  908. pt3 = (x1, y1)
  909. pt4 = (x0, y1)
  910. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  911. self.first_click = False
  912. return
  913. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  914. #
  915. # if modifiers == QtCore.Qt.ShiftModifier:
  916. # mod_key = 'Shift'
  917. # elif modifiers == QtCore.Qt.ControlModifier:
  918. # mod_key = 'Control'
  919. # else:
  920. # mod_key = None
  921. #
  922. # if mod_key == self.app.defaults["global_mselect_key"]:
  923. # self.first_click = False
  924. # return
  925. #
  926. # self.sel_rect = cascaded_union(self.sel_rect)
  927. # self.paint_poly_area(obj=self.paint_obj,
  928. # tooldia=tooldia_list,
  929. # sel_obj= self.sel_rect,
  930. # outname=o_name,
  931. # overlap=overlap,
  932. # connect=connect,
  933. # contour=contour)
  934. #
  935. # self.app.plotcanvas.graph_event_disconnect('mouse_release', on_mouse_release)
  936. # self.app.plotcanvas.graph_event_disconnect('mouse_move', on_mouse_move)
  937. #
  938. # self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  939. # self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  940. # self.app.plotcanvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  941. elif event.button == 2 and self.mouse_is_dragging is False:
  942. self.first_click = False
  943. self.app.plotcanvas.graph_event_disconnect('mouse_release', on_mouse_release)
  944. self.app.plotcanvas.graph_event_disconnect('mouse_move', on_mouse_move)
  945. self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  946. self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  947. self.app.plotcanvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  948. if len(self.sel_rect) == 0:
  949. return
  950. self.sel_rect = cascaded_union(self.sel_rect)
  951. self.paint_poly_area(obj=self.paint_obj,
  952. tooldia=tooldia_list,
  953. sel_obj=self.sel_rect,
  954. outname=o_name,
  955. overlap=overlap,
  956. connect=connect,
  957. contour=contour)
  958. # called on mouse move
  959. def on_mouse_move(event):
  960. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  961. # detect mouse dragging motion
  962. if event.is_dragging is True:
  963. self.mouse_is_dragging = True
  964. else:
  965. self.mouse_is_dragging = False
  966. # update the cursor position
  967. if self.app.grid_status() == True:
  968. # Update cursor
  969. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  970. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  971. symbol='++', edge_color='black', size=20)
  972. # draw the utility geometry
  973. if self.first_click:
  974. self.app.delete_selection_shape()
  975. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  976. coords=(curr_pos[0], curr_pos[1]),
  977. face_alpha=0.0)
  978. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  979. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  980. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  981. self.app.plotcanvas.graph_event_connect('mouse_release', on_mouse_release)
  982. self.app.plotcanvas.graph_event_connect('mouse_move', on_mouse_move)
  983. elif select_method == 'ref':
  984. self.bound_obj_name = self.box_combo.currentText()
  985. # Get source object.
  986. try:
  987. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  988. except Exception as e:
  989. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  990. (_("Could not retrieve object"),
  991. self.obj_name))
  992. return "Could not retrieve object: %s" % self.obj_name
  993. self.paint_poly_ref(obj=self.paint_obj,
  994. sel_obj=self.bound_obj,
  995. tooldia=tooldia_list,
  996. overlap=overlap,
  997. outname=o_name,
  998. connect=connect,
  999. contour=contour)
  1000. def paint_poly(self, obj,
  1001. inside_pt=None,
  1002. tooldia=None,
  1003. overlap=None,
  1004. order=None,
  1005. margin=None,
  1006. method=None,
  1007. outname=None,
  1008. connect=None,
  1009. contour=None,
  1010. tools_storage=None,
  1011. plot=True,
  1012. run_threaded=True):
  1013. """
  1014. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1015. Note:
  1016. * The margin is taken directly from the form.
  1017. :param obj: painted object
  1018. :param inside_pt: [x, y]
  1019. :param tooldia: Diameter of the painting tool
  1020. :param overlap: Overlap of the tool between passes.
  1021. :param order: if the tools are ordered and how
  1022. :param margin: a border around painting area
  1023. :param outname: Name of the resulting Geometry Object.
  1024. :param connect: Connect lines to avoid tool lifts.
  1025. :param contour: Paint around the edges.
  1026. :param method: choice out of 'seed', 'normal', 'lines'
  1027. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1028. Usage of the different one is related to when this function is called from a TcL command.
  1029. :return: None
  1030. """
  1031. # Which polygon.
  1032. # poly = find_polygon(self.solid_geometry, inside_pt)
  1033. if isinstance(obj, FlatCAMGerber):
  1034. if self.app.defaults["gerber_buffering"] == 'no':
  1035. self.app.inform.emit('%s %s' %
  1036. (_("Paint Tool. Normal painting polygon task started."),
  1037. _("Buffering geometry...")))
  1038. else:
  1039. self.app.inform.emit(_("Paint Tool. Normal painting polygon task started."))
  1040. else:
  1041. self.app.inform.emit(_("Paint Tool. Normal painting polygon task started."))
  1042. if isinstance(obj, FlatCAMGerber):
  1043. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1044. if isinstance(obj.solid_geometry, list):
  1045. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1046. else:
  1047. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1048. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  1049. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1050. if margin is not None:
  1051. paint_margin = margin
  1052. else:
  1053. try:
  1054. paint_margin = float(self.paintmargin_entry.get_value())
  1055. except ValueError:
  1056. # try to convert comma to decimal point. if it's still not working error message and return
  1057. try:
  1058. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1059. except ValueError:
  1060. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1061. _("Wrong value format entered, use a number."))
  1062. return
  1063. # determine if to use the progressive plotting
  1064. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1065. prog_plot = True
  1066. else:
  1067. prog_plot = False
  1068. # No polygon?
  1069. if poly is None:
  1070. self.app.log.warning('No polygon found.')
  1071. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1072. return
  1073. proc = self.app.proc_container.new(_("Painting polygon..."))
  1074. self.app.inform.emit('%s: %s' % (_("Paint Tool. Painting polygon at location"), str(inside_pt)))
  1075. name = outname if outname is not None else self.obj_name + "_paint"
  1076. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1077. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1078. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1079. order = order if order is not None else self.order_radio.get_value()
  1080. sorted_tools = []
  1081. if tooldia is not None:
  1082. try:
  1083. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1084. except AttributeError:
  1085. if not isinstance(tooldia, list):
  1086. sorted_tools = [float(tooldia)]
  1087. else:
  1088. sorted_tools = tooldia
  1089. else:
  1090. for row in range(self.tools_table.rowCount()):
  1091. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1092. if tools_storage is not None:
  1093. tools_storage = tools_storage
  1094. else:
  1095. tools_storage = self.paint_tools
  1096. # Initializes the new geometry object
  1097. def gen_paintarea(geo_obj, app_obj):
  1098. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1099. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1100. # assert isinstance(app_obj, App)
  1101. tool_dia = None
  1102. if order == 'fwd':
  1103. sorted_tools.sort(reverse=False)
  1104. elif order == 'rev':
  1105. sorted_tools.sort(reverse=True)
  1106. else:
  1107. pass
  1108. def paint_p(polyg, tooldiameter):
  1109. cpoly = None
  1110. try:
  1111. if paint_method == "seed":
  1112. # Type(cp) == FlatCAMRTreeStorage | None
  1113. cpoly = self.clear_polygon2(polyg,
  1114. tooldia=tooldiameter,
  1115. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1116. overlap=over,
  1117. contour=cont,
  1118. connect=conn,
  1119. prog_plot=prog_plot)
  1120. elif paint_method == "lines":
  1121. # Type(cp) == FlatCAMRTreeStorage | None
  1122. cpoly = self.clear_polygon3(polyg,
  1123. tooldia=tooldiameter,
  1124. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1125. overlap=over,
  1126. contour=cont,
  1127. connect=conn,
  1128. prog_plot=prog_plot)
  1129. else:
  1130. # Type(cp) == FlatCAMRTreeStorage | None
  1131. cpoly = self.clear_polygon(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. except FlatCAMApp.GracefulException:
  1139. return "fail"
  1140. except Exception as e:
  1141. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1142. if cpoly is not None:
  1143. geo_obj.solid_geometry += list(cpoly.get_objects())
  1144. return cpoly
  1145. else:
  1146. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1147. _('Geometry could not be painted completely'))
  1148. return None
  1149. try:
  1150. a, b, c, d = poly.bounds
  1151. geo_obj.options['xmin'] = a
  1152. geo_obj.options['ymin'] = b
  1153. geo_obj.options['xmax'] = c
  1154. geo_obj.options['ymax'] = d
  1155. except Exception as e:
  1156. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1157. return
  1158. total_geometry = []
  1159. current_uid = int(1)
  1160. geo_obj.solid_geometry = []
  1161. for tool_dia in sorted_tools:
  1162. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1163. for k, v in tools_storage.items():
  1164. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1165. current_uid = int(k)
  1166. break
  1167. try:
  1168. poly_buf = poly.buffer(-paint_margin)
  1169. if isinstance(poly_buf, MultiPolygon):
  1170. cp = []
  1171. for pp in poly_buf:
  1172. cp.append(paint_p(pp, tooldia=tool_dia))
  1173. else:
  1174. cp = paint_p(poly_buf, tooldia=tool_dia)
  1175. if cp is not None:
  1176. if isinstance(cp, list):
  1177. for x in cp:
  1178. total_geometry += list(x.get_objects())
  1179. else:
  1180. total_geometry = list(cp.get_objects())
  1181. except FlatCAMApp.GracefulException:
  1182. return "fail"
  1183. except Exception as e:
  1184. log.debug("Could not Paint the polygons. %s" % str(e))
  1185. app_obj.inform.emit('[ERROR] %s\n%s' %
  1186. (_("Could not do Paint. Try a different combination of parameters. "
  1187. "Or a different strategy of paint"),
  1188. str(e)
  1189. )
  1190. )
  1191. return "fail"
  1192. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1193. # dictionary and then reset the temporary list that stored that solid_geometry
  1194. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1195. tools_storage[current_uid]['data']['name'] = name
  1196. total_geometry[:] = []
  1197. # clean the progressive plotted shapes if it was used
  1198. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1199. self.temp_shapes.clear(update=True)
  1200. # delete tools with empty geometry
  1201. keys_to_delete = []
  1202. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1203. for uid in tools_storage:
  1204. # if the solid_geometry (type=list) is empty
  1205. if not tools_storage[uid]['solid_geometry']:
  1206. keys_to_delete.append(uid)
  1207. # actual delete of keys from the tools_storage dict
  1208. for k in keys_to_delete:
  1209. tools_storage.pop(k, None)
  1210. geo_obj.options["cnctooldia"] = str(tool_dia)
  1211. # this turn on the FlatCAMCNCJob plot for multiple tools
  1212. geo_obj.multigeo = True
  1213. geo_obj.multitool = True
  1214. geo_obj.tools.clear()
  1215. geo_obj.tools = dict(tools_storage)
  1216. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1217. has_solid_geo = 0
  1218. for tooluid in geo_obj.tools:
  1219. if geo_obj.tools[tooluid]['solid_geometry']:
  1220. has_solid_geo += 1
  1221. if has_solid_geo == 0:
  1222. self.app.inform.emit('[ERROR] %s' %
  1223. _("There is no Painting Geometry in the file.\n"
  1224. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1225. "Change the painting parameters and try again."))
  1226. return
  1227. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1228. # Experimental...
  1229. # print("Indexing...", end=' ')
  1230. # geo_obj.make_index()
  1231. # if errors == 0:
  1232. # print("[success] Paint single polygon Done")
  1233. # self.app.inform.emit("[success] Paint single polygon Done")
  1234. # else:
  1235. # print("[WARNING] Paint single polygon done with errors")
  1236. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1237. # "%d area(s) could not be painted.\n"
  1238. # "Use different paint parameters or edit the paint geometry and correct"
  1239. # "the issue."
  1240. # % errors)
  1241. def job_thread(app_obj):
  1242. try:
  1243. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1244. except FlatCAMApp.GracefulException:
  1245. proc.done()
  1246. return
  1247. except Exception as e:
  1248. proc.done()
  1249. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1250. (_('PaintTool.paint_poly()'),
  1251. str(e)))
  1252. return
  1253. proc.done()
  1254. # focus on Selected Tab
  1255. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1256. self.app.inform.emit(_("Polygon Paint started ..."))
  1257. # Promise object with the new name
  1258. self.app.collection.promise(name)
  1259. if run_threaded:
  1260. # Background
  1261. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1262. else:
  1263. job_thread(app_obj=self.app)
  1264. def paint_poly_all(self, obj,
  1265. tooldia=None,
  1266. overlap=None,
  1267. order=None,
  1268. margin=None,
  1269. method=None,
  1270. outname=None,
  1271. connect=None,
  1272. contour=None,
  1273. tools_storage=None,
  1274. plot=True,
  1275. run_threaded=True):
  1276. """
  1277. Paints all polygons in this object.
  1278. :param obj: painted object
  1279. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1280. :param overlap: value by which the paths will overlap
  1281. :param order: if the tools are ordered and how
  1282. :param margin: a border around painting area
  1283. :param outname: name of the resulting object
  1284. :param connect: Connect lines to avoid tool lifts.
  1285. :param contour: Paint around the edges.
  1286. :param method: choice out of 'seed', 'normal', 'lines'
  1287. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1288. Usage of the different one is related to when this function is called from a TcL command.
  1289. :return:
  1290. """
  1291. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1292. if margin is not None:
  1293. paint_margin = margin
  1294. else:
  1295. try:
  1296. paint_margin = float(self.paintmargin_entry.get_value())
  1297. except ValueError:
  1298. # try to convert comma to decimal point. if it's still not working error message and return
  1299. try:
  1300. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1301. except ValueError:
  1302. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1303. _("Wrong value format entered, use a number."))
  1304. return
  1305. # determine if to use the progressive plotting
  1306. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1307. prog_plot = True
  1308. else:
  1309. prog_plot = False
  1310. proc = self.app.proc_container.new(_("Painting polygons..."))
  1311. name = outname if outname is not None else self.obj_name + "_paint"
  1312. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1313. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1314. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1315. order = order if order is not None else self.order_radio.get_value()
  1316. sorted_tools = []
  1317. if tooldia is not None:
  1318. try:
  1319. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1320. except AttributeError:
  1321. if not isinstance(tooldia, list):
  1322. sorted_tools = [float(tooldia)]
  1323. else:
  1324. sorted_tools = tooldia
  1325. else:
  1326. for row in range(self.tools_table.rowCount()):
  1327. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1328. if tools_storage is not None:
  1329. tools_storage = tools_storage
  1330. else:
  1331. tools_storage = self.paint_tools
  1332. # This is a recursive generator of individual Polygons.
  1333. # Note: Double check correct implementation. Might exit
  1334. # early if it finds something that is not a Polygon?
  1335. # def recurse(geo):
  1336. # try:
  1337. # for subg in geo:
  1338. # for subsubg in recurse(subg):
  1339. # yield subsubg
  1340. # except TypeError:
  1341. # if isinstance(geo, Polygon):
  1342. # yield geo
  1343. #
  1344. # raise StopIteration
  1345. def recurse(geometry, reset=True):
  1346. """
  1347. Creates a list of non-iterable linear geometry objects.
  1348. Results are placed in self.flat_geometry
  1349. :param geometry: Shapely type or list or list of list of such.
  1350. :param reset: Clears the contents of self.flat_geometry.
  1351. """
  1352. if self.app.abort_flag:
  1353. # graceful abort requested by the user
  1354. raise FlatCAMApp.GracefulException
  1355. if geometry is None:
  1356. return
  1357. if reset:
  1358. self.flat_geometry = []
  1359. # ## If iterable, expand recursively.
  1360. try:
  1361. for geo in geometry:
  1362. if geo is not None:
  1363. recurse(geometry=geo, reset=False)
  1364. # ## Not iterable, do the actual indexing and add.
  1365. except TypeError:
  1366. if isinstance(geometry, LinearRing):
  1367. g = Polygon(geometry)
  1368. self.flat_geometry.append(g)
  1369. else:
  1370. self.flat_geometry.append(geometry)
  1371. return self.flat_geometry
  1372. # Initializes the new geometry object
  1373. def gen_paintarea(geo_obj, app_obj):
  1374. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1375. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1376. log.debug("Paint Tool. Normal painting all task started.")
  1377. if isinstance(obj, FlatCAMGerber):
  1378. if app_obj.defaults["gerber_buffering"] == 'no':
  1379. app_obj.inform.emit('%s %s' %
  1380. (_("Paint Tool. Normal painting all task started."),
  1381. _("Buffering geometry...")))
  1382. else:
  1383. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1384. else:
  1385. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1386. tool_dia = None
  1387. if order == 'fwd':
  1388. sorted_tools.sort(reverse=False)
  1389. elif order == 'rev':
  1390. sorted_tools.sort(reverse=True)
  1391. else:
  1392. pass
  1393. if isinstance(obj, FlatCAMGerber):
  1394. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1395. if isinstance(obj.solid_geometry, list):
  1396. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1397. else:
  1398. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1399. try:
  1400. a, b, c, d = obj.bounds()
  1401. geo_obj.options['xmin'] = a
  1402. geo_obj.options['ymin'] = b
  1403. geo_obj.options['xmax'] = c
  1404. geo_obj.options['ymax'] = d
  1405. except Exception as e:
  1406. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1407. return
  1408. total_geometry = []
  1409. current_uid = int(1)
  1410. geo_obj.solid_geometry = []
  1411. for tool_dia in sorted_tools:
  1412. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1413. app_obj.inform.emit(
  1414. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1415. str(tool_dia),
  1416. self.units.lower(),
  1417. _('started'))
  1418. )
  1419. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1420. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1421. for k, v in tools_storage.items():
  1422. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1423. current_uid = int(k)
  1424. break
  1425. painted_area = recurse(obj.solid_geometry)
  1426. # variables to display the percentage of work done
  1427. geo_len = len(painted_area)
  1428. old_disp_number = 0
  1429. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1430. pol_nr = 0
  1431. for geo in painted_area:
  1432. try:
  1433. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1434. if not isinstance(geo, Polygon):
  1435. continue
  1436. poly_buf = geo.buffer(-paint_margin)
  1437. if paint_method == "seed":
  1438. # Type(cp) == FlatCAMRTreeStorage | None
  1439. cp = self.clear_polygon2(poly_buf,
  1440. tooldia=tool_dia,
  1441. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1442. overlap=over,
  1443. contour=cont,
  1444. connect=conn,
  1445. prog_plot=prog_plot)
  1446. elif paint_method == "lines":
  1447. # Type(cp) == FlatCAMRTreeStorage | None
  1448. cp = self.clear_polygon3(poly_buf,
  1449. tooldia=tool_dia,
  1450. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1451. overlap=over,
  1452. contour=cont,
  1453. connect=conn,
  1454. prog_plot=prog_plot)
  1455. else:
  1456. # Type(cp) == FlatCAMRTreeStorage | None
  1457. cp = self.clear_polygon(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. if cp is not None:
  1465. total_geometry += list(cp.get_objects())
  1466. except FlatCAMApp.GracefulException:
  1467. return "fail"
  1468. except Exception as e:
  1469. log.debug("Could not Paint the polygons. %s" % str(e))
  1470. self.app.inform.emit('[ERROR] %s\n%s' %
  1471. (_("Could not do Paint All. Try a different combination of parameters. "
  1472. "Or a different Method of paint"),
  1473. str(e)))
  1474. return "fail"
  1475. pol_nr += 1
  1476. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1477. # log.debug("Polygons cleared: %d" % pol_nr)
  1478. if old_disp_number < disp_number <= 100:
  1479. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1480. old_disp_number = disp_number
  1481. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1482. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1483. # dictionary and then reset the temporary list that stored that solid_geometry
  1484. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1485. tools_storage[current_uid]['data']['name'] = name
  1486. total_geometry[:] = []
  1487. # clean the progressive plotted shapes if it was used
  1488. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1489. self.temp_shapes.clear(update=True)
  1490. # delete tools with empty geometry
  1491. keys_to_delete = []
  1492. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1493. for uid in tools_storage:
  1494. # if the solid_geometry (type=list) is empty
  1495. if not tools_storage[uid]['solid_geometry']:
  1496. keys_to_delete.append(uid)
  1497. # actual delete of keys from the tools_storage dict
  1498. for k in keys_to_delete:
  1499. tools_storage.pop(k, None)
  1500. geo_obj.options["cnctooldia"] = str(tool_dia)
  1501. # this turn on the FlatCAMCNCJob plot for multiple tools
  1502. geo_obj.multigeo = True
  1503. geo_obj.multitool = True
  1504. geo_obj.tools.clear()
  1505. geo_obj.tools = dict(tools_storage)
  1506. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1507. has_solid_geo = 0
  1508. for tooluid in geo_obj.tools:
  1509. if geo_obj.tools[tooluid]['solid_geometry']:
  1510. has_solid_geo += 1
  1511. if has_solid_geo == 0:
  1512. self.app.inform.emit('[ERROR] %s' %
  1513. _("There is no Painting Geometry in the file.\n"
  1514. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1515. "Change the painting parameters and try again."))
  1516. return
  1517. # Experimental...
  1518. # print("Indexing...", end=' ')
  1519. # geo_obj.make_index()
  1520. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1521. # Initializes the new geometry object
  1522. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1523. assert isinstance(geo_obj, FlatCAMGeometry), \
  1524. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1525. log.debug("Paint Tool. Rest machining painting all task started.")
  1526. if isinstance(obj, FlatCAMGerber):
  1527. if app_obj.defaults["gerber_buffering"] == 'no':
  1528. app_obj.inform.emit('%s %s' %
  1529. (_("Paint Tool. Rest machining painting all task started."),
  1530. _("Buffering geometry...")))
  1531. else:
  1532. app_obj.inform.emit(_("Paint Tool. Rest machining painting all task started."))
  1533. else:
  1534. app_obj.inform.emit(_("Paint Tool. Rest machining painting all task started."))
  1535. tool_dia = None
  1536. sorted_tools.sort(reverse=True)
  1537. cleared_geo = []
  1538. current_uid = int(1)
  1539. geo_obj.solid_geometry = []
  1540. if isinstance(obj, FlatCAMGerber):
  1541. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1542. if isinstance(obj.solid_geometry, list):
  1543. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1544. else:
  1545. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1546. try:
  1547. a, b, c, d = obj.bounds()
  1548. geo_obj.options['xmin'] = a
  1549. geo_obj.options['ymin'] = b
  1550. geo_obj.options['xmax'] = c
  1551. geo_obj.options['ymax'] = d
  1552. except Exception as e:
  1553. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1554. return
  1555. for tool_dia in sorted_tools:
  1556. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1557. app_obj.inform.emit(
  1558. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1559. str(tool_dia),
  1560. self.units.lower(),
  1561. _('started'))
  1562. )
  1563. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1564. painted_area = recurse(obj.solid_geometry)
  1565. # variables to display the percentage of work done
  1566. geo_len = int(len(painted_area) / 100)
  1567. old_disp_number = 0
  1568. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1569. pol_nr = 0
  1570. for geo in painted_area:
  1571. try:
  1572. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1573. poly_buf = geo.buffer(-paint_margin)
  1574. cp = None
  1575. if paint_method == "standard":
  1576. # Type(cp) == FlatCAMRTreeStorage | None
  1577. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1578. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1579. overlap=over, contour=cont, connect=conn,
  1580. prog_plot=prog_plot)
  1581. elif paint_method == "seed":
  1582. # Type(cp) == FlatCAMRTreeStorage | None
  1583. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1584. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1585. overlap=over, contour=cont, connect=conn,
  1586. prog_plot=prog_plot)
  1587. elif paint_method == "lines":
  1588. # Type(cp) == FlatCAMRTreeStorage | None
  1589. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1590. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1591. overlap=over, contour=cont, connect=conn,
  1592. prog_plot=prog_plot)
  1593. if cp is not None:
  1594. cleared_geo += list(cp.get_objects())
  1595. except FlatCAMApp.GracefulException:
  1596. return "fail"
  1597. except Exception as e:
  1598. log.debug("Could not Paint the polygons. %s" % str(e))
  1599. self.app.inform.emit('[ERROR] %s\n%s' %
  1600. (_("Could not do Paint All. Try a different combination of parameters. "
  1601. "Or a different Method of paint"),
  1602. str(e)))
  1603. return "fail"
  1604. pol_nr += 1
  1605. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1606. # log.debug("Polygons cleared: %d" % pol_nr)
  1607. if old_disp_number < disp_number <= 100:
  1608. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1609. old_disp_number = disp_number
  1610. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1611. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1612. for k, v in tools_storage.items():
  1613. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1614. current_uid = int(k)
  1615. break
  1616. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1617. # then reset the temporary list that stored that solid_geometry
  1618. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1619. tools_storage[current_uid]['data']['name'] = name
  1620. cleared_geo[:] = []
  1621. geo_obj.options["cnctooldia"] = str(tool_dia)
  1622. # this turn on the FlatCAMCNCJob plot for multiple tools
  1623. geo_obj.multigeo = True
  1624. geo_obj.multitool = True
  1625. geo_obj.tools.clear()
  1626. geo_obj.tools = dict(tools_storage)
  1627. # clean the progressive plotted shapes if it was used
  1628. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1629. self.temp_shapes.clear(update=True)
  1630. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1631. has_solid_geo = 0
  1632. for tooluid in geo_obj.tools:
  1633. if geo_obj.tools[tooluid]['solid_geometry']:
  1634. has_solid_geo += 1
  1635. if has_solid_geo == 0:
  1636. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1637. _("There is no Painting Geometry in the file.\n"
  1638. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1639. "Change the painting parameters and try again."))
  1640. return
  1641. # Experimental...
  1642. # print("Indexing...", end=' ')
  1643. # geo_obj.make_index()
  1644. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1645. def job_thread(app_obj):
  1646. try:
  1647. if self.rest_cb.isChecked():
  1648. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  1649. else:
  1650. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1651. except FlatCAMApp.GracefulException:
  1652. proc.done()
  1653. return
  1654. except Exception as e:
  1655. proc.done()
  1656. traceback.print_stack()
  1657. return
  1658. proc.done()
  1659. # focus on Selected Tab
  1660. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1661. self.app.inform.emit(_("Polygon Paint started ..."))
  1662. # Promise object with the new name
  1663. self.app.collection.promise(name)
  1664. if run_threaded:
  1665. # Background
  1666. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1667. else:
  1668. job_thread(app_obj=self.app)
  1669. def paint_poly_area(self, obj, sel_obj,
  1670. tooldia=None,
  1671. overlap=None,
  1672. order=None,
  1673. margin=None,
  1674. method=None,
  1675. outname=None,
  1676. connect=None,
  1677. contour=None,
  1678. tools_storage=None,
  1679. plot=True,
  1680. run_threaded=True):
  1681. """
  1682. Paints all polygons in this object that are within the sel_obj object
  1683. :param obj: painted object
  1684. :param sel_obj: paint only what is inside this object bounds
  1685. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1686. :param overlap: value by which the paths will overlap
  1687. :param order: if the tools are ordered and how
  1688. :param margin: a border around painting area
  1689. :param outname: name of the resulting object
  1690. :param connect: Connect lines to avoid tool lifts.
  1691. :param contour: Paint around the edges.
  1692. :param method: choice out of 'seed', 'normal', 'lines'
  1693. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1694. Usage of the different one is related to when this function is called from a TcL command.
  1695. :return:
  1696. """
  1697. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1698. if margin is not None:
  1699. paint_margin = margin
  1700. else:
  1701. try:
  1702. paint_margin = float(self.paintmargin_entry.get_value())
  1703. except ValueError:
  1704. # try to convert comma to decimal point. if it's still not working error message and return
  1705. try:
  1706. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1707. except ValueError:
  1708. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1709. _("Wrong value format entered, use a number."))
  1710. return
  1711. # determine if to use the progressive plotting
  1712. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1713. prog_plot = True
  1714. else:
  1715. prog_plot = False
  1716. proc = self.app.proc_container.new(_("Painting polygons..."))
  1717. name = outname if outname is not None else self.obj_name + "_paint"
  1718. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1719. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1720. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1721. order = order if order is not None else self.order_radio.get_value()
  1722. sorted_tools = []
  1723. if tooldia is not None:
  1724. try:
  1725. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1726. except AttributeError:
  1727. if not isinstance(tooldia, list):
  1728. sorted_tools = [float(tooldia)]
  1729. else:
  1730. sorted_tools = tooldia
  1731. else:
  1732. for row in range(self.tools_table.rowCount()):
  1733. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1734. if tools_storage is not None:
  1735. tools_storage = tools_storage
  1736. else:
  1737. tools_storage = self.paint_tools
  1738. def recurse(geometry, reset=True):
  1739. """
  1740. Creates a list of non-iterable linear geometry objects.
  1741. Results are placed in self.flat_geometry
  1742. :param geometry: Shapely type or list or list of list of such.
  1743. :param reset: Clears the contents of self.flat_geometry.
  1744. """
  1745. if self.app.abort_flag:
  1746. # graceful abort requested by the user
  1747. raise FlatCAMApp.GracefulException
  1748. if geometry is None:
  1749. return
  1750. if reset:
  1751. self.flat_geometry = []
  1752. # ## If iterable, expand recursively.
  1753. try:
  1754. for geo in geometry:
  1755. if geo is not None:
  1756. recurse(geometry=geo, reset=False)
  1757. # ## Not iterable, do the actual indexing and add.
  1758. except TypeError:
  1759. if isinstance(geometry, LinearRing):
  1760. g = Polygon(geometry)
  1761. self.flat_geometry.append(g)
  1762. else:
  1763. self.flat_geometry.append(geometry)
  1764. return self.flat_geometry
  1765. # Initializes the new geometry object
  1766. def gen_paintarea(geo_obj, app_obj):
  1767. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1768. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1769. log.debug("Paint Tool. Normal painting area task started.")
  1770. if isinstance(obj, FlatCAMGerber):
  1771. if app_obj.defaults["gerber_buffering"] == 'no':
  1772. app_obj.inform.emit('%s %s' %
  1773. (_("Paint Tool. Normal painting area task started."),
  1774. _("Buffering geometry...")))
  1775. else:
  1776. app_obj.inform.emit(_("Paint Tool. Normal painting area task started."))
  1777. else:
  1778. app_obj.inform.emit(_("Paint Tool. Normal painting area task started."))
  1779. tool_dia = None
  1780. if order == 'fwd':
  1781. sorted_tools.sort(reverse=False)
  1782. elif order == 'rev':
  1783. sorted_tools.sort(reverse=True)
  1784. else:
  1785. pass
  1786. # this is were heavy lifting is done and creating the geometry to be painted
  1787. target_geo = MultiPolygon(obj.solid_geometry)
  1788. if isinstance(obj, FlatCAMGerber):
  1789. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1790. if isinstance(target_geo, list):
  1791. target_geo = MultiPolygon(target_geo).buffer(0)
  1792. else:
  1793. target_geo = target_geo.buffer(0)
  1794. geo_to_paint = target_geo.intersection(sel_obj)
  1795. painted_area = recurse(geo_to_paint)
  1796. try:
  1797. a, b, c, d = self.paint_bounds(geo_to_paint)
  1798. geo_obj.options['xmin'] = a
  1799. geo_obj.options['ymin'] = b
  1800. geo_obj.options['xmax'] = c
  1801. geo_obj.options['ymax'] = d
  1802. except Exception as e:
  1803. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1804. return
  1805. total_geometry = []
  1806. current_uid = int(1)
  1807. geo_obj.solid_geometry = []
  1808. for tool_dia in sorted_tools:
  1809. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1810. app_obj.inform.emit(
  1811. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1812. str(tool_dia),
  1813. self.units.lower(),
  1814. _('started'))
  1815. )
  1816. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1817. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1818. for k, v in tools_storage.items():
  1819. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1820. current_uid = int(k)
  1821. break
  1822. # variables to display the percentage of work done
  1823. geo_len = len(painted_area)
  1824. old_disp_number = 0
  1825. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1826. pol_nr = 0
  1827. for geo in painted_area:
  1828. try:
  1829. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1830. if not isinstance(geo, Polygon):
  1831. continue
  1832. poly_buf = geo.buffer(-paint_margin)
  1833. if paint_method == "seed":
  1834. # Type(cp) == FlatCAMRTreeStorage | None
  1835. cp = self.clear_polygon2(poly_buf,
  1836. tooldia=tool_dia,
  1837. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1838. overlap=over,
  1839. contour=cont,
  1840. connect=conn,
  1841. prog_plot=prog_plot)
  1842. elif paint_method == "lines":
  1843. # Type(cp) == FlatCAMRTreeStorage | None
  1844. cp = self.clear_polygon3(poly_buf,
  1845. tooldia=tool_dia,
  1846. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1847. overlap=over,
  1848. contour=cont,
  1849. connect=conn,
  1850. prog_plot=prog_plot)
  1851. else:
  1852. # Type(cp) == FlatCAMRTreeStorage | None
  1853. cp = self.clear_polygon(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. if cp is not None:
  1861. total_geometry += list(cp.get_objects())
  1862. except FlatCAMApp.GracefulException:
  1863. return "fail"
  1864. except Exception as e:
  1865. log.debug("Could not Paint the polygons. %s" % str(e))
  1866. self.app.inform.emit('[ERROR] %s\n%s' %
  1867. (_("Could not do Paint All. Try a different combination of parameters. "
  1868. "Or a different Method of paint"), str(e)))
  1869. return
  1870. pol_nr += 1
  1871. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1872. # log.debug("Polygons cleared: %d" % pol_nr)
  1873. if old_disp_number < disp_number <= 100:
  1874. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1875. old_disp_number = disp_number
  1876. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1877. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1878. # dictionary and then reset the temporary list that stored that solid_geometry
  1879. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1880. tools_storage[current_uid]['data']['name'] = name
  1881. total_geometry[:] = []
  1882. # clean the progressive plotted shapes if it was used
  1883. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1884. self.temp_shapes.clear(update=True)
  1885. # delete tools with empty geometry
  1886. keys_to_delete = []
  1887. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1888. for uid in tools_storage:
  1889. # if the solid_geometry (type=list) is empty
  1890. if not tools_storage[uid]['solid_geometry']:
  1891. keys_to_delete.append(uid)
  1892. # actual delete of keys from the tools_storage dict
  1893. for k in keys_to_delete:
  1894. tools_storage.pop(k, None)
  1895. geo_obj.options["cnctooldia"] = str(tool_dia)
  1896. # this turn on the FlatCAMCNCJob plot for multiple tools
  1897. geo_obj.multigeo = True
  1898. geo_obj.multitool = True
  1899. geo_obj.tools.clear()
  1900. geo_obj.tools = dict(tools_storage)
  1901. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1902. has_solid_geo = 0
  1903. for tooluid in geo_obj.tools:
  1904. if geo_obj.tools[tooluid]['solid_geometry']:
  1905. has_solid_geo += 1
  1906. if has_solid_geo == 0:
  1907. self.app.inform.emit('[ERROR] %s' %
  1908. _("There is no Painting Geometry in the file.\n"
  1909. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1910. "Change the painting parameters and try again."))
  1911. return
  1912. # Experimental...
  1913. # print("Indexing...", end=' ')
  1914. # geo_obj.make_index()
  1915. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  1916. # Initializes the new geometry object
  1917. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1918. assert isinstance(geo_obj, FlatCAMGeometry), \
  1919. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1920. log.debug("Paint Tool. Rest machining painting area task started.")
  1921. if isinstance(obj, FlatCAMGerber):
  1922. if app_obj.defaults["gerber_buffering"] == 'no':
  1923. app_obj.inform.emit('%s %s' %
  1924. (_("Paint Tool. Rest machining painting area task started."),
  1925. _("Buffering geometry...")))
  1926. else:
  1927. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  1928. else:
  1929. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  1930. tool_dia = None
  1931. sorted_tools.sort(reverse=True)
  1932. cleared_geo = []
  1933. current_uid = int(1)
  1934. geo_obj.solid_geometry = []
  1935. # this is were heavy lifting is done and creating the geometry to be painted
  1936. target_geo = obj.solid_geometry
  1937. if isinstance(obj, FlatCAMGerber):
  1938. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1939. if isinstance(target_geo, list):
  1940. target_geo = MultiPolygon(target_geo).buffer(0)
  1941. else:
  1942. target_geo = target_geo.buffer(0)
  1943. geo_to_paint = target_geo.intersection(sel_obj)
  1944. painted_area = recurse(geo_to_paint)
  1945. try:
  1946. a, b, c, d = obj.bounds()
  1947. geo_obj.options['xmin'] = a
  1948. geo_obj.options['ymin'] = b
  1949. geo_obj.options['xmax'] = c
  1950. geo_obj.options['ymax'] = d
  1951. except Exception as e:
  1952. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1953. return
  1954. for tool_dia in sorted_tools:
  1955. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1956. app_obj.inform.emit(
  1957. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1958. str(tool_dia),
  1959. self.units.lower(),
  1960. _('started'))
  1961. )
  1962. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1963. # variables to display the percentage of work done
  1964. geo_len = len(painted_area)
  1965. old_disp_number = 0
  1966. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1967. pol_nr = 0
  1968. for geo in painted_area:
  1969. try:
  1970. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1971. poly_buf = geo.buffer(-paint_margin)
  1972. cp = None
  1973. if paint_method == "standard":
  1974. # Type(cp) == FlatCAMRTreeStorage | None
  1975. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1976. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1977. overlap=over, contour=cont, connect=conn,
  1978. prog_plot=prog_plot)
  1979. elif paint_method == "seed":
  1980. # Type(cp) == FlatCAMRTreeStorage | None
  1981. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1982. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1983. overlap=over, contour=cont, connect=conn,
  1984. prog_plot=prog_plot)
  1985. elif paint_method == "lines":
  1986. # Type(cp) == FlatCAMRTreeStorage | None
  1987. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1988. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1989. overlap=over, contour=cont, connect=conn,
  1990. prog_plot=prog_plot)
  1991. if cp is not None:
  1992. cleared_geo += list(cp.get_objects())
  1993. except FlatCAMApp.GracefulException:
  1994. return "fail"
  1995. except Exception as e:
  1996. log.debug("Could not Paint the polygons. %s" % str(e))
  1997. self.app.inform.emit('[ERROR] %s\n%s' %
  1998. (_("Could not do Paint All. Try a different combination of parameters. "
  1999. "Or a different Method of paint"), str(e)))
  2000. return
  2001. pol_nr += 1
  2002. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2003. # log.debug("Polygons cleared: %d" % pol_nr)
  2004. if old_disp_number < disp_number <= 100:
  2005. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2006. old_disp_number = disp_number
  2007. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2008. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2009. for k, v in tools_storage.items():
  2010. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  2011. current_uid = int(k)
  2012. break
  2013. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2014. # then reset the temporary list that stored that solid_geometry
  2015. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2016. tools_storage[current_uid]['data']['name'] = name
  2017. cleared_geo[:] = []
  2018. geo_obj.options["cnctooldia"] = str(tool_dia)
  2019. # this turn on the FlatCAMCNCJob plot for multiple tools
  2020. geo_obj.multigeo = True
  2021. geo_obj.multitool = True
  2022. geo_obj.tools.clear()
  2023. geo_obj.tools = dict(self.paint_tools)
  2024. # clean the progressive plotted shapes if it was used
  2025. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2026. self.temp_shapes.clear(update=True)
  2027. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2028. has_solid_geo = 0
  2029. for tooluid in geo_obj.tools:
  2030. if geo_obj.tools[tooluid]['solid_geometry']:
  2031. has_solid_geo += 1
  2032. if has_solid_geo == 0:
  2033. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2034. _("There is no Painting Geometry in the file.\n"
  2035. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2036. "Change the painting parameters and try again."))
  2037. return
  2038. # Experimental...
  2039. # print("Indexing...", end=' ')
  2040. # geo_obj.make_index()
  2041. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2042. def job_thread(app_obj):
  2043. try:
  2044. if self.rest_cb.isChecked():
  2045. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2046. else:
  2047. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2048. except FlatCAMApp.GracefulException:
  2049. proc.done()
  2050. return
  2051. except Exception as e:
  2052. proc.done()
  2053. traceback.print_stack()
  2054. return
  2055. proc.done()
  2056. # focus on Selected Tab
  2057. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2058. self.app.inform.emit(_("Polygon Paint started ..."))
  2059. # Promise object with the new name
  2060. self.app.collection.promise(name)
  2061. if run_threaded:
  2062. # Background
  2063. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2064. else:
  2065. job_thread(app_obj=self.app)
  2066. def paint_poly_ref(self, obj, sel_obj,
  2067. tooldia=None,
  2068. overlap=None,
  2069. order=None,
  2070. margin=None,
  2071. method=None,
  2072. outname=None,
  2073. connect=None,
  2074. contour=None,
  2075. tools_storage=None,
  2076. plot=True,
  2077. run_threaded=True):
  2078. """
  2079. Paints all polygons in this object that are within the sel_obj object
  2080. :param obj: painted object
  2081. :param sel_obj: paint only what is inside this object bounds
  2082. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2083. :param overlap: value by which the paths will overlap
  2084. :param order: if the tools are ordered and how
  2085. :param margin: a border around painting area
  2086. :param outname: name of the resulting object
  2087. :param connect: Connect lines to avoid tool lifts.
  2088. :param contour: Paint around the edges.
  2089. :param method: choice out of 'seed', 'normal', 'lines'
  2090. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2091. Usage of the different one is related to when this function is called from a TcL command.
  2092. :return:
  2093. """
  2094. geo = sel_obj.solid_geometry
  2095. try:
  2096. if isinstance(geo, MultiPolygon):
  2097. env_obj = geo.convex_hull
  2098. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2099. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2100. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2101. else:
  2102. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2103. env_obj = env_obj.convex_hull
  2104. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2105. except Exception as e:
  2106. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  2107. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2108. return
  2109. self.paint_poly_area(obj=obj,
  2110. sel_obj=sel_rect,
  2111. tooldia=tooldia,
  2112. overlap=overlap,
  2113. order=order,
  2114. margin=margin,
  2115. method=method,
  2116. outname=outname,
  2117. connect=connect,
  2118. contour=contour,
  2119. tools_storage=tools_storage,
  2120. plot=plot,
  2121. run_threaded=run_threaded)
  2122. @staticmethod
  2123. def paint_bounds(geometry):
  2124. def bounds_rec(o):
  2125. if type(o) is list:
  2126. minx = Inf
  2127. miny = Inf
  2128. maxx = -Inf
  2129. maxy = -Inf
  2130. for k in o:
  2131. try:
  2132. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2133. except Exception as e:
  2134. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2135. return
  2136. minx = min(minx, minx_)
  2137. miny = min(miny, miny_)
  2138. maxx = max(maxx, maxx_)
  2139. maxy = max(maxy, maxy_)
  2140. return minx, miny, maxx, maxy
  2141. else:
  2142. # it's a Shapely object, return it's bounds
  2143. return o.bounds
  2144. return bounds_rec(geometry)
  2145. def reset_fields(self):
  2146. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))