ToolPaint.py 114 KB

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