ToolPaint.py 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  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. grid3.addWidget(ovlabel, 1, 0)
  182. self.paintoverlap_entry = FCEntry()
  183. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  184. # Margin
  185. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  186. marginlabel.setToolTip(
  187. _("Distance by which to avoid\n"
  188. "the edges of the polygon to\n"
  189. "be painted.")
  190. )
  191. grid3.addWidget(marginlabel, 2, 0)
  192. self.paintmargin_entry = FCEntry()
  193. grid3.addWidget(self.paintmargin_entry, 2, 1)
  194. # Method
  195. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  196. methodlabel.setToolTip(
  197. _("Algorithm for painting:\n"
  198. "- Standard: Fixed step inwards.\n"
  199. "- Seed-based: Outwards from seed.\n"
  200. "- Line-based: Parallel lines.")
  201. )
  202. grid3.addWidget(methodlabel, 3, 0)
  203. self.paintmethod_combo = RadioSet([
  204. {"label": _("Standard"), "value": "standard"},
  205. {"label": _("Seed-based"), "value": "seed"},
  206. {"label": _("Straight lines"), "value": "lines"}
  207. ], orientation='vertical', stretch=False)
  208. grid3.addWidget(self.paintmethod_combo, 3, 1)
  209. # Connect lines
  210. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  211. pathconnectlabel.setToolTip(
  212. _("Draw lines between resulting\n"
  213. "segments to minimize tool lifts.")
  214. )
  215. grid3.addWidget(pathconnectlabel, 4, 0)
  216. self.pathconnect_cb = FCCheckBox()
  217. grid3.addWidget(self.pathconnect_cb, 4, 1)
  218. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  219. contourlabel.setToolTip(
  220. _("Cut around the perimeter of the polygon\n"
  221. "to trim rough edges.")
  222. )
  223. grid3.addWidget(contourlabel, 5, 0)
  224. self.paintcontour_cb = FCCheckBox()
  225. grid3.addWidget(self.paintcontour_cb, 5, 1)
  226. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  227. restlabel.setToolTip(
  228. _("If checked, use 'rest machining'.\n"
  229. "Basically it will clear copper outside PCB features,\n"
  230. "using the biggest tool and continue with the next tools,\n"
  231. "from bigger to smaller, to clear areas of copper that\n"
  232. "could not be cleared by previous tool, until there is\n"
  233. "no more copper to clear or there are no more tools.\n\n"
  234. "If not checked, use the standard algorithm.")
  235. )
  236. grid3.addWidget(restlabel, 6, 0)
  237. self.rest_cb = FCCheckBox()
  238. grid3.addWidget(self.rest_cb, 6, 1)
  239. # Polygon selection
  240. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  241. selectlabel.setToolTip(
  242. _("How to select Polygons to be painted.\n\n"
  243. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  244. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  245. "- 'All Polygons' - the Paint will start after click.\n"
  246. "- 'Reference Object' - will do non copper clearing within the area\n"
  247. "specified by another object.")
  248. )
  249. grid3.addWidget(selectlabel, 7, 0)
  250. # grid3 = QtWidgets.QGridLayout()
  251. self.selectmethod_combo = RadioSet([
  252. {"label": _("Single Polygon"), "value": "single"},
  253. {"label": _("Area Selection"), "value": "area"},
  254. {"label": _("All Polygons"), "value": "all"},
  255. {"label": _("Reference Object"), "value": "ref"}
  256. ], orientation='vertical', stretch=False)
  257. self.selectmethod_combo.setToolTip(
  258. _("How to select Polygons to be painted.\n\n"
  259. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  260. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  261. "- 'All Polygons' - the Paint will start after click.\n"
  262. "- 'Reference Object' - will do non copper clearing within the area\n"
  263. "specified by another object.")
  264. )
  265. grid3.addWidget(self.selectmethod_combo, 7, 1)
  266. form1 = QtWidgets.QFormLayout()
  267. self.tools_box.addLayout(form1)
  268. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  269. self.box_combo_type_label.setToolTip(
  270. _("The type of FlatCAM object to be used as paint reference.\n"
  271. "It can be Gerber, Excellon or Geometry.")
  272. )
  273. self.box_combo_type = QtWidgets.QComboBox()
  274. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  275. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  276. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  277. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  278. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  279. self.box_combo_label.setToolTip(
  280. _("The FlatCAM object to be used as non copper clearing reference.")
  281. )
  282. self.box_combo = QtWidgets.QComboBox()
  283. self.box_combo.setModel(self.app.collection)
  284. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  285. self.box_combo.setCurrentIndex(1)
  286. form1.addRow(self.box_combo_label, self.box_combo)
  287. self.box_combo.hide()
  288. self.box_combo_label.hide()
  289. self.box_combo_type.hide()
  290. self.box_combo_type_label.hide()
  291. # GO Button
  292. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  293. self.generate_paint_button.setToolTip(
  294. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  295. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  296. "- 'All Polygons' - the Paint will start after click.\n"
  297. "- 'Reference Object' - will do non copper clearing within the area\n"
  298. "specified by another object.")
  299. )
  300. self.tools_box.addWidget(self.generate_paint_button)
  301. self.tools_box.addStretch()
  302. self.obj_name = ""
  303. self.paint_obj = None
  304. self.units = ''
  305. self.paint_tools = {}
  306. self.tooluid = 0
  307. self.first_click = False
  308. self.cursor_pos = None
  309. self.mouse_is_dragging = False
  310. self.sel_rect = []
  311. # store here the default data for Geometry Data
  312. self.default_data = {}
  313. self.default_data.update({
  314. "name": '_paint',
  315. "plot": self.app.defaults["geometry_plot"],
  316. "cutz": self.app.defaults["geometry_cutz"],
  317. "vtipdia": 0.1,
  318. "vtipangle": 30,
  319. "travelz": self.app.defaults["geometry_travelz"],
  320. "feedrate": self.app.defaults["geometry_feedrate"],
  321. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  322. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  323. "dwell": self.app.defaults["geometry_dwell"],
  324. "dwelltime": self.app.defaults["geometry_dwelltime"],
  325. "multidepth": self.app.defaults["geometry_multidepth"],
  326. "ppname_g": self.app.defaults["geometry_ppname_g"],
  327. "depthperpass": self.app.defaults["geometry_depthperpass"],
  328. "extracut": self.app.defaults["geometry_extracut"],
  329. "toolchange": self.app.defaults["geometry_toolchange"],
  330. "toolchangez": self.app.defaults["geometry_toolchangez"],
  331. "endz": self.app.defaults["geometry_endz"],
  332. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  333. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  334. "startz": self.app.defaults["geometry_startz"],
  335. "tooldia": self.app.defaults["tools_painttooldia"],
  336. "paintmargin": self.app.defaults["tools_paintmargin"],
  337. "paintmethod": self.app.defaults["tools_paintmethod"],
  338. "selectmethod": self.app.defaults["tools_selectmethod"],
  339. "pathconnect": self.app.defaults["tools_pathconnect"],
  340. "paintcontour": self.app.defaults["tools_paintcontour"],
  341. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  342. })
  343. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  344. # ## Signals
  345. self.addtool_btn.clicked.connect(self.on_tool_add)
  346. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  347. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  348. self.tools_table.itemChanged.connect(self.on_tool_edit)
  349. self.deltool_btn.clicked.connect(self.on_tool_delete)
  350. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  351. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  352. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  353. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  354. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  355. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  356. def on_type_obj_index_changed(self, index):
  357. obj_type = self.type_obj_combo.currentIndex()
  358. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  359. self.obj_combo.setCurrentIndex(0)
  360. def install(self, icon=None, separator=None, **kwargs):
  361. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  362. def run(self, toggle=True):
  363. self.app.report_usage("ToolPaint()")
  364. if toggle:
  365. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  366. if self.app.ui.splitter.sizes()[0] == 0:
  367. self.app.ui.splitter.setSizes([1, 1])
  368. else:
  369. try:
  370. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  371. # if tab is populated with the tool but it does not have the focus, focus on it
  372. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  373. # focus on Tool Tab
  374. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  375. else:
  376. self.app.ui.splitter.setSizes([0, 1])
  377. except AttributeError:
  378. pass
  379. else:
  380. if self.app.ui.splitter.sizes()[0] == 0:
  381. self.app.ui.splitter.setSizes([1, 1])
  382. FlatCAMTool.run(self)
  383. self.set_tool_ui()
  384. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  385. def reset_usage(self):
  386. self.obj_name = ""
  387. self.paint_obj = None
  388. self.bound_obj = None
  389. self.first_click = False
  390. self.cursor_pos = None
  391. self.mouse_is_dragging = False
  392. self.sel_rect = []
  393. def on_radio_selection(self):
  394. if self.selectmethod_combo.get_value() == "ref":
  395. self.box_combo.show()
  396. self.box_combo_label.show()
  397. self.box_combo_type.show()
  398. self.box_combo_type_label.show()
  399. else:
  400. self.box_combo.hide()
  401. self.box_combo_label.hide()
  402. self.box_combo_type.hide()
  403. self.box_combo_type_label.hide()
  404. if self.selectmethod_combo.get_value() == 'single':
  405. # disable rest-machining for single polygon painting
  406. self.rest_cb.set_value(False)
  407. self.rest_cb.setDisabled(True)
  408. # delete all tools except first row / tool for single polygon painting
  409. # list_to_del = list(range(1, self.tools_table.rowCount()))
  410. # if list_to_del:
  411. # self.on_tool_delete(rows_to_delete=list_to_del)
  412. # # disable addTool and delTool
  413. # self.addtool_entry.setDisabled(True)
  414. # self.addtool_btn.setDisabled(True)
  415. # self.deltool_btn.setDisabled(True)
  416. # self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  417. if self.selectmethod_combo.get_value() == 'area':
  418. # disable rest-machining for single polygon painting
  419. self.rest_cb.set_value(False)
  420. self.rest_cb.setDisabled(True)
  421. else:
  422. self.rest_cb.setDisabled(False)
  423. self.addtool_entry.setDisabled(False)
  424. self.addtool_btn.setDisabled(False)
  425. self.deltool_btn.setDisabled(False)
  426. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  427. def on_order_changed(self, order):
  428. if order != 'no':
  429. self.build_ui()
  430. def on_rest_machining_check(self, state):
  431. if state:
  432. self.order_radio.set_value('rev')
  433. self.order_label.setDisabled(True)
  434. self.order_radio.setDisabled(True)
  435. else:
  436. self.order_label.setDisabled(False)
  437. self.order_radio.setDisabled(False)
  438. def set_tool_ui(self):
  439. self.tools_frame.show()
  440. self.reset_fields()
  441. # ## Init the GUI interface
  442. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  443. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  444. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  445. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  446. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  447. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  448. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  449. # updated units
  450. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  451. if self.units == "IN":
  452. self.addtool_entry.set_value(0.039)
  453. else:
  454. self.addtool_entry.set_value(1)
  455. self.tools_table.setupContextMenu()
  456. self.tools_table.addContextMenu(
  457. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  458. self.tools_table.addContextMenu(
  459. "Delete", lambda:
  460. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  461. # set the working variables to a known state
  462. self.paint_tools.clear()
  463. self.tooluid = 0
  464. self.default_data.clear()
  465. self.default_data.update({
  466. "name": '_paint',
  467. "plot": self.app.defaults["geometry_plot"],
  468. "cutz": self.app.defaults["geometry_cutz"],
  469. "vtipdia": 0.1,
  470. "vtipangle": 30,
  471. "travelz": self.app.defaults["geometry_travelz"],
  472. "feedrate": self.app.defaults["geometry_feedrate"],
  473. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  474. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  475. "dwell": self.app.defaults["geometry_dwell"],
  476. "dwelltime": self.app.defaults["geometry_dwelltime"],
  477. "multidepth": self.app.defaults["geometry_multidepth"],
  478. "ppname_g": self.app.defaults["geometry_ppname_g"],
  479. "depthperpass": self.app.defaults["geometry_depthperpass"],
  480. "extracut": self.app.defaults["geometry_extracut"],
  481. "toolchange": self.app.defaults["geometry_toolchange"],
  482. "toolchangez": self.app.defaults["geometry_toolchangez"],
  483. "endz": self.app.defaults["geometry_endz"],
  484. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  485. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  486. "startz": self.app.defaults["geometry_startz"],
  487. "tooldia": self.app.defaults["tools_painttooldia"],
  488. "paintmargin": self.app.defaults["tools_paintmargin"],
  489. "paintmethod": self.app.defaults["tools_paintmethod"],
  490. "selectmethod": self.app.defaults["tools_selectmethod"],
  491. "pathconnect": self.app.defaults["tools_pathconnect"],
  492. "paintcontour": self.app.defaults["tools_paintcontour"],
  493. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  494. })
  495. # call on self.on_tool_add() counts as an call to self.build_ui()
  496. # through this, we add a initial row / tool in the tool_table
  497. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  498. # if the Paint Method is "Single" disable the tool table context menu
  499. if self.default_data["selectmethod"] == "single":
  500. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  501. def build_ui(self):
  502. try:
  503. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  504. self.tools_table.itemChanged.disconnect()
  505. except (TypeError, AttributeError):
  506. pass
  507. # updated units
  508. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  509. sorted_tools = []
  510. for k, v in self.paint_tools.items():
  511. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  512. order = self.order_radio.get_value()
  513. if order == 'fwd':
  514. sorted_tools.sort(reverse=False)
  515. elif order == 'rev':
  516. sorted_tools.sort(reverse=True)
  517. else:
  518. pass
  519. n = len(sorted_tools)
  520. self.tools_table.setRowCount(n)
  521. tool_id = 0
  522. for tool_sorted in sorted_tools:
  523. for tooluid_key, tooluid_value in self.paint_tools.items():
  524. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  525. tool_id += 1
  526. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  527. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  528. row_no = tool_id - 1
  529. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  530. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  531. # There are no drill bits in MM with more than 3 decimals diameter
  532. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  533. if self.units == 'MM':
  534. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  535. else:
  536. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  537. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  538. tool_type_item = QtWidgets.QComboBox()
  539. for item in self.tool_type_item_options:
  540. tool_type_item.addItem(item)
  541. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  542. idx = tool_type_item.findText(tooluid_value['tool_type'])
  543. tool_type_item.setCurrentIndex(idx)
  544. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  545. self.tools_table.setItem(row_no, 1, dia) # Diameter
  546. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  547. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  548. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  549. # make the diameter column editable
  550. for row in range(tool_id):
  551. self.tools_table.item(row, 1).setFlags(
  552. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  553. # all the tools are selected by default
  554. self.tools_table.selectColumn(0)
  555. #
  556. self.tools_table.resizeColumnsToContents()
  557. self.tools_table.resizeRowsToContents()
  558. vertical_header = self.tools_table.verticalHeader()
  559. vertical_header.hide()
  560. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  561. horizontal_header = self.tools_table.horizontalHeader()
  562. horizontal_header.setMinimumSectionSize(10)
  563. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  564. horizontal_header.resizeSection(0, 20)
  565. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  566. # self.tools_table.setSortingEnabled(True)
  567. # sort by tool diameter
  568. # self.tools_table.sortItems(1)
  569. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  570. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  571. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  572. self.tools_table.itemChanged.connect(self.on_tool_edit)
  573. def on_combo_box_type(self):
  574. obj_type = self.box_combo_type.currentIndex()
  575. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  576. self.box_combo.setCurrentIndex(0)
  577. def on_tool_add(self, dia=None, muted=None):
  578. try:
  579. self.tools_table.itemChanged.disconnect()
  580. except Exception as e:
  581. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  582. if dia:
  583. tool_dia = dia
  584. else:
  585. try:
  586. tool_dia = float(self.addtool_entry.get_value())
  587. except ValueError:
  588. # try to convert comma to decimal point. if it's still not working error message and return
  589. try:
  590. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  591. except ValueError:
  592. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  593. "use a number."))
  594. return
  595. if tool_dia is None:
  596. self.build_ui()
  597. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  598. return
  599. # construct a list of all 'tooluid' in the self.tools
  600. tool_uid_list = []
  601. for tooluid_key in self.paint_tools:
  602. tool_uid_item = int(tooluid_key)
  603. tool_uid_list.append(tool_uid_item)
  604. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  605. if not tool_uid_list:
  606. max_uid = 0
  607. else:
  608. max_uid = max(tool_uid_list)
  609. self.tooluid = int(max_uid + 1)
  610. tool_dias = []
  611. for k, v in self.paint_tools.items():
  612. for tool_v in v.keys():
  613. if tool_v == 'tooldia':
  614. tool_dias.append(float('%.4f' % v[tool_v]))
  615. if float('%.4f' % tool_dia) in tool_dias:
  616. if muted is None:
  617. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  618. self.tools_table.itemChanged.connect(self.on_tool_edit)
  619. return
  620. else:
  621. if muted is None:
  622. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  623. self.paint_tools.update({
  624. int(self.tooluid): {
  625. 'tooldia': float('%.4f' % tool_dia),
  626. 'offset': 'Path',
  627. 'offset_value': 0.0,
  628. 'type': 'Iso',
  629. 'tool_type': 'V',
  630. 'data': dict(self.default_data),
  631. 'solid_geometry': []
  632. }
  633. })
  634. self.build_ui()
  635. def on_tool_edit(self):
  636. old_tool_dia = ''
  637. try:
  638. self.tools_table.itemChanged.disconnect()
  639. except Exception as e:
  640. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  641. tool_dias = []
  642. for k, v in self.paint_tools.items():
  643. for tool_v in v.keys():
  644. if tool_v == 'tooldia':
  645. tool_dias.append(float('%.4f' % v[tool_v]))
  646. for row in range(self.tools_table.rowCount()):
  647. try:
  648. new_tool_dia = float(self.tools_table.item(row, 1).text())
  649. except ValueError:
  650. # try to convert comma to decimal point. if it's still not working error message and return
  651. try:
  652. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  653. except ValueError:
  654. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  655. "use a number."))
  656. return
  657. tooluid = int(self.tools_table.item(row, 3).text())
  658. # identify the tool that was edited and get it's tooluid
  659. if new_tool_dia not in tool_dias:
  660. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  661. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  662. self.build_ui()
  663. return
  664. else:
  665. # identify the old tool_dia and restore the text in tool table
  666. for k, v in self.paint_tools.items():
  667. if k == tooluid:
  668. old_tool_dia = v['tooldia']
  669. break
  670. restore_dia_item = self.tools_table.item(row, 1)
  671. restore_dia_item.setText(str(old_tool_dia))
  672. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  673. "New diameter value is already in the Tool Table."))
  674. self.build_ui()
  675. # def on_tool_copy(self, all=None):
  676. # try:
  677. # self.tools_table.itemChanged.disconnect()
  678. # except:
  679. # pass
  680. #
  681. # # find the tool_uid maximum value in the self.tools
  682. # uid_list = []
  683. # for key in self.paint_tools:
  684. # uid_list.append(int(key))
  685. # try:
  686. # max_uid = max(uid_list, key=int)
  687. # except ValueError:
  688. # max_uid = 0
  689. #
  690. # if all is None:
  691. # if self.tools_table.selectedItems():
  692. # for current_row in self.tools_table.selectedItems():
  693. # # sometime the header get selected and it has row number -1
  694. # # we don't want to do anything with the header :)
  695. # if current_row.row() < 0:
  696. # continue
  697. # try:
  698. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  699. # max_uid += 1
  700. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  701. # for td in self.paint_tools:
  702. # print("COPIED", self.paint_tools[td])
  703. # self.build_ui()
  704. # except AttributeError:
  705. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  706. # self.build_ui()
  707. # return
  708. # except Exception as e:
  709. # log.debug("on_tool_copy() --> " + str(e))
  710. # # deselect the table
  711. # # self.ui.geo_tools_table.clearSelection()
  712. # else:
  713. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  714. # self.build_ui()
  715. # return
  716. # else:
  717. # # we copy all tools in geo_tools_table
  718. # try:
  719. # temp_tools = dict(self.paint_tools)
  720. # max_uid += 1
  721. # for tooluid in temp_tools:
  722. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  723. # temp_tools.clear()
  724. # self.build_ui()
  725. # except Exception as e:
  726. # log.debug("on_tool_copy() --> " + str(e))
  727. #
  728. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  729. def on_tool_delete(self, rows_to_delete=None, all=None):
  730. try:
  731. self.tools_table.itemChanged.disconnect()
  732. except Exception as e:
  733. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  734. pass
  735. deleted_tools_list = []
  736. if all:
  737. self.paint_tools.clear()
  738. self.build_ui()
  739. return
  740. if rows_to_delete:
  741. try:
  742. for row in rows_to_delete:
  743. tooluid_del = int(self.tools_table.item(row, 3).text())
  744. deleted_tools_list.append(tooluid_del)
  745. except TypeError:
  746. deleted_tools_list.append(rows_to_delete)
  747. for t in deleted_tools_list:
  748. self.paint_tools.pop(t, None)
  749. self.build_ui()
  750. return
  751. try:
  752. if self.tools_table.selectedItems():
  753. for row_sel in self.tools_table.selectedItems():
  754. row = row_sel.row()
  755. if row < 0:
  756. continue
  757. tooluid_del = int(self.tools_table.item(row, 3).text())
  758. deleted_tools_list.append(tooluid_del)
  759. for t in deleted_tools_list:
  760. self.paint_tools.pop(t, None)
  761. except AttributeError:
  762. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  763. return
  764. except Exception as e:
  765. log.debug(str(e))
  766. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  767. self.build_ui()
  768. def on_paint_button_click(self):
  769. # init values for the next usage
  770. self.reset_usage()
  771. self.app.report_usage(_("on_paint_button_click"))
  772. # self.app.call_source = 'paint'
  773. try:
  774. overlap = float(self.paintoverlap_entry.get_value())
  775. except ValueError:
  776. # try to convert comma to decimal point. if it's still not working error message and return
  777. try:
  778. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  779. except ValueError:
  780. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  781. "use a number."))
  782. return
  783. if overlap >= 1 or overlap < 0:
  784. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  785. "0 (inclusive) and 1 (exclusive), "))
  786. return
  787. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  788. connect = self.pathconnect_cb.get_value()
  789. contour = self.paintcontour_cb.get_value()
  790. select_method = self.selectmethod_combo.get_value()
  791. self.obj_name = self.obj_combo.currentText()
  792. # Get source object.
  793. try:
  794. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  795. except Exception as e:
  796. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  797. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  798. return
  799. if self.paint_obj is None:
  800. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  801. return
  802. # test if the Geometry Object is multigeo and return Fail if True because
  803. # for now Paint don't work on MultiGeo
  804. if self.paint_obj.multigeo is True:
  805. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  806. return 'Fail'
  807. o_name = '%s_multitool_paint' % self.obj_name
  808. # use the selected tools in the tool table; get diameters
  809. tooldia_list = list()
  810. if self.tools_table.selectedItems():
  811. for x in self.tools_table.selectedItems():
  812. try:
  813. tooldia = float(self.tools_table.item(x.row(), 1).text())
  814. except ValueError:
  815. # try to convert comma to decimal point. if it's still not working error message and return
  816. try:
  817. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  818. except ValueError:
  819. self.app.inform.emit(_("[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  820. "use a number."))
  821. continue
  822. tooldia_list.append(tooldia)
  823. else:
  824. self.app.inform.emit(_("[ERROR_NOTCL] No selected tools in Tool Table."))
  825. return
  826. if select_method == "all":
  827. self.paint_poly_all(self.paint_obj,
  828. tooldia=tooldia_list,
  829. outname=o_name,
  830. overlap=overlap,
  831. connect=connect,
  832. contour=contour)
  833. elif select_method == "single":
  834. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  835. # use the first tool in the tool table; get the diameter
  836. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  837. # To be called after clicking on the plot.
  838. def doit(event):
  839. # do paint single only for left mouse clicks
  840. if event.button == 1:
  841. self.app.inform.emit(_("Painting polygon..."))
  842. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  843. pos = self.app.plotcanvas.translate_coords(event.pos)
  844. if self.app.grid_status() == True:
  845. pos = self.app.geo_editor.snap(pos[0], pos[1])
  846. self.paint_poly(self.paint_obj,
  847. inside_pt=[pos[0], pos[1]],
  848. tooldia=tooldia_list,
  849. overlap=overlap,
  850. connect=connect,
  851. contour=contour)
  852. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  853. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  854. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  855. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  856. self.app.plotcanvas.vis_connect('mouse_press', doit)
  857. elif select_method == "area":
  858. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  859. # use the first tool in the tool table; get the diameter
  860. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  861. # To be called after clicking on the plot.
  862. def on_mouse_release(event):
  863. # do paint single only for left mouse clicks
  864. if event.button == 1:
  865. if not self.first_click:
  866. self.first_click = True
  867. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  868. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  869. if self.app.grid_status() == True:
  870. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  871. else:
  872. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  873. self.app.delete_selection_shape()
  874. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  875. if self.app.grid_status() == True:
  876. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  877. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  878. x1, y1 = curr_pos[0], curr_pos[1]
  879. pt1 = (x0, y0)
  880. pt2 = (x1, y0)
  881. pt3 = (x1, y1)
  882. pt4 = (x0, y1)
  883. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  884. self.first_click = False
  885. return
  886. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  887. #
  888. # if modifiers == QtCore.Qt.ShiftModifier:
  889. # mod_key = 'Shift'
  890. # elif modifiers == QtCore.Qt.ControlModifier:
  891. # mod_key = 'Control'
  892. # else:
  893. # mod_key = None
  894. #
  895. # if mod_key == self.app.defaults["global_mselect_key"]:
  896. # self.first_click = False
  897. # return
  898. #
  899. # self.sel_rect = cascaded_union(self.sel_rect)
  900. # self.paint_poly_area(obj=self.paint_obj,
  901. # tooldia=tooldia_list,
  902. # sel_obj= self.sel_rect,
  903. # outname=o_name,
  904. # overlap=overlap,
  905. # connect=connect,
  906. # contour=contour)
  907. #
  908. # self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  909. # self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  910. #
  911. # self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  912. # self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  913. # self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  914. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  915. self.first_click = False
  916. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  917. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  918. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  919. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  920. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  921. self.sel_rect = cascaded_union(self.sel_rect)
  922. self.paint_poly_area(obj=self.paint_obj,
  923. tooldia=tooldia_list,
  924. sel_obj=self.sel_rect,
  925. outname=o_name,
  926. overlap=overlap,
  927. connect=connect,
  928. contour=contour)
  929. # called on mouse move
  930. def on_mouse_move(event):
  931. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  932. self.app.app_cursor.enabled = False
  933. if event.button == 2:
  934. if event.is_dragging is True:
  935. self.mouse_is_dragging = True
  936. else:
  937. self.mouse_is_dragging = False
  938. if self.app.grid_status() == True:
  939. self.app.app_cursor.enabled = True
  940. # Update cursor
  941. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  942. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  943. symbol='++', edge_color='black', size=20)
  944. if self.first_click:
  945. self.app.delete_selection_shape()
  946. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  947. coords=(curr_pos[0], curr_pos[1]),
  948. face_alpha=0.0)
  949. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  950. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  951. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  952. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  953. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  954. elif select_method == 'ref':
  955. self.bound_obj_name = self.box_combo.currentText()
  956. # Get source object.
  957. try:
  958. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  959. except Exception as e:
  960. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  961. return "Could not retrieve object: %s" % self.obj_name
  962. self.paint_poly_ref(obj=self.paint_obj,
  963. sel_obj=self.bound_obj,
  964. tooldia=tooldia_list,
  965. overlap=overlap,
  966. outname=o_name,
  967. connect=connect,
  968. contour=contour)
  969. def paint_poly(self, obj,
  970. inside_pt=None,
  971. tooldia=None,
  972. overlap=None,
  973. order=None,
  974. margin=None,
  975. method=None,
  976. outname=None,
  977. connect=None,
  978. contour=None,
  979. tools_storage=None):
  980. """
  981. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  982. Note:
  983. * The margin is taken directly from the form.
  984. :param obj: painted object
  985. :param inside_pt: [x, y]
  986. :param tooldia: Diameter of the painting tool
  987. :param overlap: Overlap of the tool between passes.
  988. :param order: if the tools are ordered and how
  989. :param margin: a border around painting area
  990. :param outname: Name of the resulting Geometry Object.
  991. :param connect: Connect lines to avoid tool lifts.
  992. :param contour: Paint around the edges.
  993. :param method: choice out of 'seed', 'normal', 'lines'
  994. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  995. Usage of the different one is related to when this function is called from a TcL command.
  996. :return: None
  997. """
  998. # Which polygon.
  999. # poly = find_polygon(self.solid_geometry, inside_pt)
  1000. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  1001. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1002. if margin is not None:
  1003. paint_margin = margin
  1004. else:
  1005. try:
  1006. paint_margin = float(self.paintmargin_entry.get_value())
  1007. except ValueError:
  1008. # try to convert comma to decimal point. if it's still not working error message and return
  1009. try:
  1010. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1011. except ValueError:
  1012. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1013. "use a number."))
  1014. return
  1015. # No polygon?
  1016. if poly is None:
  1017. self.app.log.warning('No polygon found.')
  1018. self.app.inform.emit(_('[WARNING] No polygon found.'))
  1019. return
  1020. proc = self.app.proc_container.new(_("Painting polygon."))
  1021. name = outname if outname is not None else self.obj_name + "_paint"
  1022. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1023. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1024. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1025. order = order if order is not None else self.order_radio.get_value()
  1026. sorted_tools = []
  1027. if tooldia is not None:
  1028. try:
  1029. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1030. except AttributeError:
  1031. if not isinstance(tooldia, list):
  1032. sorted_tools = [float(tooldia)]
  1033. else:
  1034. sorted_tools = tooldia
  1035. else:
  1036. for row in range(self.tools_table.rowCount()):
  1037. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1038. if tools_storage is not None:
  1039. tools_storage = tools_storage
  1040. else:
  1041. tools_storage = self.paint_tools
  1042. # Initializes the new geometry object
  1043. def gen_paintarea(geo_obj, app_obj):
  1044. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1045. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1046. # assert isinstance(app_obj, App)
  1047. tool_dia = None
  1048. if order == 'fwd':
  1049. sorted_tools.sort(reverse=False)
  1050. elif order == 'rev':
  1051. sorted_tools.sort(reverse=True)
  1052. else:
  1053. pass
  1054. def paint_p(polyg, tooldia):
  1055. if paint_method == "seed":
  1056. # Type(cp) == FlatCAMRTreeStorage | None
  1057. cpoly = self.clear_polygon2(polyg,
  1058. tooldia=tooldia,
  1059. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1060. overlap=over,
  1061. contour=cont,
  1062. connect=conn)
  1063. elif paint_method == "lines":
  1064. # Type(cp) == FlatCAMRTreeStorage | None
  1065. cpoly = self.clear_polygon3(polyg,
  1066. tooldia=tooldia,
  1067. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1068. overlap=over,
  1069. contour=cont,
  1070. connect=conn)
  1071. else:
  1072. # Type(cp) == FlatCAMRTreeStorage | None
  1073. cpoly = self.clear_polygon(polyg,
  1074. tooldia=tooldia,
  1075. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1076. overlap=over,
  1077. contour=cont,
  1078. connect=conn)
  1079. if cpoly is not None:
  1080. geo_obj.solid_geometry += list(cpoly.get_objects())
  1081. return cpoly
  1082. else:
  1083. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  1084. return None
  1085. try:
  1086. a, b, c, d = poly.bounds
  1087. geo_obj.options['xmin'] = a
  1088. geo_obj.options['ymin'] = b
  1089. geo_obj.options['xmax'] = c
  1090. geo_obj.options['ymax'] = d
  1091. except Exception as e:
  1092. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1093. return
  1094. total_geometry = []
  1095. current_uid = int(1)
  1096. geo_obj.solid_geometry = []
  1097. for tool_dia in sorted_tools:
  1098. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1099. for k, v in tools_storage.items():
  1100. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1101. current_uid = int(k)
  1102. break
  1103. try:
  1104. poly_buf = poly.buffer(-paint_margin)
  1105. if isinstance(poly_buf, MultiPolygon):
  1106. cp = []
  1107. for pp in poly_buf:
  1108. cp.append(paint_p(pp, tooldia=tool_dia))
  1109. else:
  1110. cp = paint_p(poly_buf, tooldia=tool_dia)
  1111. if cp is not None:
  1112. if isinstance(cp, list):
  1113. for x in cp:
  1114. total_geometry += list(x.get_objects())
  1115. else:
  1116. total_geometry = list(cp.get_objects())
  1117. except Exception as e:
  1118. log.debug("Could not Paint the polygons. %s" % str(e))
  1119. self.app.inform.emit(
  1120. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  1121. "Or a different strategy of paint\n%s") % str(e))
  1122. return
  1123. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1124. # dictionary and then reset the temporary list that stored that solid_geometry
  1125. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1126. tools_storage[current_uid]['data']['name'] = name
  1127. total_geometry[:] = []
  1128. # delete tools with empty geometry
  1129. keys_to_delete = []
  1130. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1131. for uid in tools_storage:
  1132. # if the solid_geometry (type=list) is empty
  1133. if not tools_storage[uid]['solid_geometry']:
  1134. keys_to_delete.append(uid)
  1135. # actual delete of keys from the tools_storage dict
  1136. for k in keys_to_delete:
  1137. tools_storage.pop(k, None)
  1138. geo_obj.options["cnctooldia"] = str(tool_dia)
  1139. # this turn on the FlatCAMCNCJob plot for multiple tools
  1140. geo_obj.multigeo = True
  1141. geo_obj.multitool = True
  1142. geo_obj.tools.clear()
  1143. geo_obj.tools = dict(tools_storage)
  1144. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1145. has_solid_geo = 0
  1146. for tooluid in geo_obj.tools:
  1147. if geo_obj.tools[tooluid]['solid_geometry']:
  1148. has_solid_geo += 1
  1149. if has_solid_geo == 0:
  1150. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1151. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1152. "Change the painting parameters and try again."))
  1153. return
  1154. self.app.inform.emit(_("[success] Paint Single Done."))
  1155. # Experimental...
  1156. # print("Indexing...", end=' ')
  1157. # geo_obj.make_index()
  1158. # if errors == 0:
  1159. # print("[success] Paint single polygon Done")
  1160. # self.app.inform.emit("[success] Paint single polygon Done")
  1161. # else:
  1162. # print("[WARNING] Paint single polygon done with errors")
  1163. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1164. # "%d area(s) could not be painted.\n"
  1165. # "Use different paint parameters or edit the paint geometry and correct"
  1166. # "the issue."
  1167. # % errors)
  1168. def job_thread(app_obj):
  1169. try:
  1170. app_obj.new_object("geometry", name, gen_paintarea)
  1171. except Exception as e:
  1172. proc.done()
  1173. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  1174. return
  1175. proc.done()
  1176. # focus on Selected Tab
  1177. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1178. self.app.inform.emit(_("Polygon Paint started ..."))
  1179. # Promise object with the new name
  1180. self.app.collection.promise(name)
  1181. # Background
  1182. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1183. def paint_poly_all(self, obj,
  1184. tooldia=None,
  1185. overlap=None,
  1186. order=None,
  1187. margin=None,
  1188. method=None,
  1189. outname=None,
  1190. connect=None,
  1191. contour=None,
  1192. tools_storage=None):
  1193. """
  1194. Paints all polygons in this object.
  1195. :param obj: painted object
  1196. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1197. :param overlap: value by which the paths will overlap
  1198. :param order: if the tools are ordered and how
  1199. :param margin: a border around painting area
  1200. :param outname: name of the resulting object
  1201. :param connect: Connect lines to avoid tool lifts.
  1202. :param contour: Paint around the edges.
  1203. :param method: choice out of 'seed', 'normal', 'lines'
  1204. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1205. Usage of the different one is related to when this function is called from a TcL command.
  1206. :return:
  1207. """
  1208. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1209. if margin is not None:
  1210. paint_margin = margin
  1211. else:
  1212. try:
  1213. paint_margin = float(self.paintmargin_entry.get_value())
  1214. except ValueError:
  1215. # try to convert comma to decimal point. if it's still not working error message and return
  1216. try:
  1217. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1218. except ValueError:
  1219. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1220. "use a number."))
  1221. return
  1222. proc = self.app.proc_container.new(_("Painting polygon..."))
  1223. name = outname if outname is not None else self.obj_name + "_paint"
  1224. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1225. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1226. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1227. order = order if order is not None else self.order_radio.get_value()
  1228. sorted_tools = []
  1229. if tooldia is not None:
  1230. try:
  1231. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1232. except AttributeError:
  1233. if not isinstance(tooldia, list):
  1234. sorted_tools = [float(tooldia)]
  1235. else:
  1236. sorted_tools = tooldia
  1237. else:
  1238. for row in range(self.tools_table.rowCount()):
  1239. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1240. if tools_storage is not None:
  1241. tools_storage = tools_storage
  1242. else:
  1243. tools_storage = self.paint_tools
  1244. # This is a recursive generator of individual Polygons.
  1245. # Note: Double check correct implementation. Might exit
  1246. # early if it finds something that is not a Polygon?
  1247. # def recurse(geo):
  1248. # try:
  1249. # for subg in geo:
  1250. # for subsubg in recurse(subg):
  1251. # yield subsubg
  1252. # except TypeError:
  1253. # if isinstance(geo, Polygon):
  1254. # yield geo
  1255. #
  1256. # raise StopIteration
  1257. def recurse(geometry, reset=True):
  1258. """
  1259. Creates a list of non-iterable linear geometry objects.
  1260. Results are placed in self.flat_geometry
  1261. :param geometry: Shapely type or list or list of list of such.
  1262. :param reset: Clears the contents of self.flat_geometry.
  1263. """
  1264. if geometry is None:
  1265. return
  1266. if reset:
  1267. self.flat_geometry = []
  1268. # ## If iterable, expand recursively.
  1269. try:
  1270. for geo in geometry:
  1271. if geo is not None:
  1272. recurse(geometry=geo, reset=False)
  1273. # ## Not iterable, do the actual indexing and add.
  1274. except TypeError:
  1275. if isinstance(geometry, LinearRing):
  1276. g = Polygon(geometry)
  1277. self.flat_geometry.append(g)
  1278. else:
  1279. self.flat_geometry.append(geometry)
  1280. return self.flat_geometry
  1281. # Initializes the new geometry object
  1282. def gen_paintarea(geo_obj, app_obj):
  1283. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1284. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1285. tool_dia = None
  1286. if order == 'fwd':
  1287. sorted_tools.sort(reverse=False)
  1288. elif order == 'rev':
  1289. sorted_tools.sort(reverse=True)
  1290. else:
  1291. pass
  1292. try:
  1293. a, b, c, d = obj.bounds()
  1294. geo_obj.options['xmin'] = a
  1295. geo_obj.options['ymin'] = b
  1296. geo_obj.options['xmax'] = c
  1297. geo_obj.options['ymax'] = d
  1298. except Exception as e:
  1299. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1300. return
  1301. total_geometry = []
  1302. current_uid = int(1)
  1303. geo_obj.solid_geometry = []
  1304. for tool_dia in sorted_tools:
  1305. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1306. for k, v in tools_storage.items():
  1307. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1308. current_uid = int(k)
  1309. break
  1310. for geo in recurse(obj.solid_geometry):
  1311. try:
  1312. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1313. if not isinstance(geo, Polygon):
  1314. continue
  1315. poly_buf = geo.buffer(-paint_margin)
  1316. if paint_method == "seed":
  1317. # Type(cp) == FlatCAMRTreeStorage | None
  1318. cp = self.clear_polygon2(poly_buf,
  1319. tooldia=tool_dia,
  1320. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1321. overlap=over,
  1322. contour=cont,
  1323. connect=conn)
  1324. elif paint_method == "lines":
  1325. # Type(cp) == FlatCAMRTreeStorage | None
  1326. cp = self.clear_polygon3(poly_buf,
  1327. tooldia=tool_dia,
  1328. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1329. overlap=over,
  1330. contour=cont,
  1331. connect=conn)
  1332. else:
  1333. # Type(cp) == FlatCAMRTreeStorage | None
  1334. cp = self.clear_polygon(poly_buf,
  1335. tooldia=tool_dia,
  1336. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1337. overlap=over,
  1338. contour=cont,
  1339. connect=conn)
  1340. if cp is not None:
  1341. total_geometry += list(cp.get_objects())
  1342. except Exception as e:
  1343. log.debug("Could not Paint the polygons. %s" % str(e))
  1344. self.app.inform.emit(
  1345. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1346. "Or a different Method of paint\n%s") % str(e))
  1347. return
  1348. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1349. # dictionary and then reset the temporary list that stored that solid_geometry
  1350. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1351. tools_storage[current_uid]['data']['name'] = name
  1352. total_geometry[:] = []
  1353. # delete tools with empty geometry
  1354. keys_to_delete = []
  1355. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1356. for uid in tools_storage:
  1357. # if the solid_geometry (type=list) is empty
  1358. if not tools_storage[uid]['solid_geometry']:
  1359. keys_to_delete.append(uid)
  1360. # actual delete of keys from the tools_storage dict
  1361. for k in keys_to_delete:
  1362. tools_storage.pop(k, None)
  1363. geo_obj.options["cnctooldia"] = str(tool_dia)
  1364. # this turn on the FlatCAMCNCJob plot for multiple tools
  1365. geo_obj.multigeo = True
  1366. geo_obj.multitool = True
  1367. geo_obj.tools.clear()
  1368. geo_obj.tools = dict(tools_storage)
  1369. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1370. has_solid_geo = 0
  1371. for tooluid in geo_obj.tools:
  1372. if geo_obj.tools[tooluid]['solid_geometry']:
  1373. has_solid_geo += 1
  1374. if has_solid_geo == 0:
  1375. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1376. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1377. "Change the painting parameters and try again."))
  1378. return
  1379. # Experimental...
  1380. # print("Indexing...", end=' ')
  1381. # geo_obj.make_index()
  1382. self.app.inform.emit(_("[success] Paint All Done."))
  1383. # Initializes the new geometry object
  1384. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1385. assert isinstance(geo_obj, FlatCAMGeometry), \
  1386. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1387. tool_dia = None
  1388. sorted_tools.sort(reverse=True)
  1389. cleared_geo = []
  1390. current_uid = int(1)
  1391. geo_obj.solid_geometry = []
  1392. try:
  1393. a, b, c, d = obj.bounds()
  1394. geo_obj.options['xmin'] = a
  1395. geo_obj.options['ymin'] = b
  1396. geo_obj.options['xmax'] = c
  1397. geo_obj.options['ymax'] = d
  1398. except Exception as e:
  1399. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1400. return
  1401. for tool_dia in sorted_tools:
  1402. for geo in recurse(obj.solid_geometry):
  1403. try:
  1404. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1405. poly_buf = geo.buffer(-paint_margin)
  1406. cp = None
  1407. if paint_method == "standard":
  1408. # Type(cp) == FlatCAMRTreeStorage | None
  1409. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1410. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1411. overlap=over, contour=cont, connect=conn)
  1412. elif paint_method == "seed":
  1413. # Type(cp) == FlatCAMRTreeStorage | None
  1414. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1415. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1416. overlap=over, contour=cont, connect=conn)
  1417. elif paint_method == "lines":
  1418. # Type(cp) == FlatCAMRTreeStorage | None
  1419. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1420. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1421. overlap=over, contour=cont, connect=conn)
  1422. if cp is not None:
  1423. cleared_geo += list(cp.get_objects())
  1424. except Exception as e:
  1425. log.debug("Could not Paint the polygons. %s" % str(e))
  1426. self.app.inform.emit(
  1427. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1428. "Or a different Method of paint\n%s") % str(e))
  1429. return
  1430. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1431. for k, v in tools_storage.items():
  1432. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1433. current_uid = int(k)
  1434. break
  1435. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1436. # then reset the temporary list that stored that solid_geometry
  1437. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1438. tools_storage[current_uid]['data']['name'] = name
  1439. cleared_geo[:] = []
  1440. geo_obj.options["cnctooldia"] = str(tool_dia)
  1441. # this turn on the FlatCAMCNCJob plot for multiple tools
  1442. geo_obj.multigeo = True
  1443. geo_obj.multitool = True
  1444. geo_obj.tools.clear()
  1445. geo_obj.tools = dict(tools_storage)
  1446. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1447. has_solid_geo = 0
  1448. for tooluid in geo_obj.tools:
  1449. if geo_obj.tools[tooluid]['solid_geometry']:
  1450. has_solid_geo += 1
  1451. if has_solid_geo == 0:
  1452. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1453. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1454. "Change the painting parameters and try again."))
  1455. return
  1456. # Experimental...
  1457. # print("Indexing...", end=' ')
  1458. # geo_obj.make_index()
  1459. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1460. def job_thread(app_obj):
  1461. try:
  1462. if self.rest_cb.isChecked():
  1463. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1464. else:
  1465. app_obj.new_object("geometry", name, gen_paintarea)
  1466. except Exception as e:
  1467. proc.done()
  1468. traceback.print_stack()
  1469. return
  1470. proc.done()
  1471. # focus on Selected Tab
  1472. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1473. self.app.inform.emit(_("Polygon Paint started ..."))
  1474. # Promise object with the new name
  1475. self.app.collection.promise(name)
  1476. # Background
  1477. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1478. def paint_poly_area(self, obj, sel_obj,
  1479. tooldia=None,
  1480. overlap=None,
  1481. order=None,
  1482. margin=None,
  1483. method=None,
  1484. outname=None,
  1485. connect=None,
  1486. contour=None,
  1487. tools_storage=None):
  1488. """
  1489. Paints all polygons in this object that are within the sel_obj object
  1490. :param obj: painted object
  1491. :param sel_obj: paint only what is inside this object bounds
  1492. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1493. :param overlap: value by which the paths will overlap
  1494. :param order: if the tools are ordered and how
  1495. :param margin: a border around painting area
  1496. :param outname: name of the resulting object
  1497. :param connect: Connect lines to avoid tool lifts.
  1498. :param contour: Paint around the edges.
  1499. :param method: choice out of 'seed', 'normal', 'lines'
  1500. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1501. Usage of the different one is related to when this function is called from a TcL command.
  1502. :return:
  1503. """
  1504. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1505. if margin is not None:
  1506. paint_margin = margin
  1507. else:
  1508. try:
  1509. paint_margin = float(self.paintmargin_entry.get_value())
  1510. except ValueError:
  1511. # try to convert comma to decimal point. if it's still not working error message and return
  1512. try:
  1513. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1514. except ValueError:
  1515. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1516. "use a number."))
  1517. return
  1518. proc = self.app.proc_container.new(_("Painting polygon..."))
  1519. name = outname if outname is not None else self.obj_name + "_paint"
  1520. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1521. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1522. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1523. order = order if order is not None else self.order_radio.get_value()
  1524. sorted_tools = []
  1525. if tooldia is not None:
  1526. try:
  1527. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1528. except AttributeError:
  1529. if not isinstance(tooldia, list):
  1530. sorted_tools = [float(tooldia)]
  1531. else:
  1532. sorted_tools = tooldia
  1533. else:
  1534. for row in range(self.tools_table.rowCount()):
  1535. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1536. if tools_storage is not None:
  1537. tools_storage = tools_storage
  1538. else:
  1539. tools_storage = self.paint_tools
  1540. def recurse(geometry, reset=True):
  1541. """
  1542. Creates a list of non-iterable linear geometry objects.
  1543. Results are placed in self.flat_geometry
  1544. :param geometry: Shapely type or list or list of list of such.
  1545. :param reset: Clears the contents of self.flat_geometry.
  1546. """
  1547. if geometry is None:
  1548. return
  1549. if reset:
  1550. self.flat_geometry = []
  1551. # ## If iterable, expand recursively.
  1552. try:
  1553. for geo in geometry:
  1554. if geo is not None:
  1555. recurse(geometry=geo, reset=False)
  1556. # ## Not iterable, do the actual indexing and add.
  1557. except TypeError:
  1558. if isinstance(geometry, LinearRing):
  1559. g = Polygon(geometry)
  1560. self.flat_geometry.append(g)
  1561. else:
  1562. self.flat_geometry.append(geometry)
  1563. return self.flat_geometry
  1564. # Initializes the new geometry object
  1565. def gen_paintarea(geo_obj, app_obj):
  1566. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1567. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1568. tool_dia = None
  1569. if order == 'fwd':
  1570. sorted_tools.sort(reverse=False)
  1571. elif order == 'rev':
  1572. sorted_tools.sort(reverse=True)
  1573. else:
  1574. pass
  1575. # this is were heavy lifting is done and creating the geometry to be painted
  1576. geo_to_paint = []
  1577. if not isinstance(obj.solid_geometry, list):
  1578. target_geo = [obj.solid_geometry]
  1579. else:
  1580. target_geo = obj.solid_geometry
  1581. for poly in target_geo:
  1582. new_pol = poly.intersection(sel_obj)
  1583. geo_to_paint.append(new_pol)
  1584. try:
  1585. a, b, c, d = self.paint_bounds(geo_to_paint)
  1586. geo_obj.options['xmin'] = a
  1587. geo_obj.options['ymin'] = b
  1588. geo_obj.options['xmax'] = c
  1589. geo_obj.options['ymax'] = d
  1590. except Exception as e:
  1591. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1592. return
  1593. total_geometry = []
  1594. current_uid = int(1)
  1595. geo_obj.solid_geometry = []
  1596. for tool_dia in sorted_tools:
  1597. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1598. for k, v in tools_storage.items():
  1599. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1600. current_uid = int(k)
  1601. break
  1602. for geo in recurse(geo_to_paint):
  1603. try:
  1604. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1605. if not isinstance(geo, Polygon):
  1606. continue
  1607. poly_buf = geo.buffer(-paint_margin)
  1608. if paint_method == "seed":
  1609. # Type(cp) == FlatCAMRTreeStorage | None
  1610. cp = self.clear_polygon2(poly_buf,
  1611. tooldia=tool_dia,
  1612. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1613. overlap=over,
  1614. contour=cont,
  1615. connect=conn)
  1616. elif paint_method == "lines":
  1617. # Type(cp) == FlatCAMRTreeStorage | None
  1618. cp = self.clear_polygon3(poly_buf,
  1619. tooldia=tool_dia,
  1620. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1621. overlap=over,
  1622. contour=cont,
  1623. connect=conn)
  1624. else:
  1625. # Type(cp) == FlatCAMRTreeStorage | None
  1626. cp = self.clear_polygon(poly_buf,
  1627. tooldia=tool_dia,
  1628. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1629. overlap=over,
  1630. contour=cont,
  1631. connect=conn)
  1632. if cp is not None:
  1633. total_geometry += list(cp.get_objects())
  1634. except Exception as e:
  1635. log.debug("Could not Paint the polygons. %s" % str(e))
  1636. self.app.inform.emit(
  1637. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1638. "Or a different Method of paint\n%s") % str(e))
  1639. return
  1640. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1641. # dictionary and then reset the temporary list that stored that solid_geometry
  1642. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1643. tools_storage[current_uid]['data']['name'] = name
  1644. total_geometry[:] = []
  1645. # delete tools with empty geometry
  1646. keys_to_delete = []
  1647. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1648. for uid in tools_storage:
  1649. # if the solid_geometry (type=list) is empty
  1650. if not tools_storage[uid]['solid_geometry']:
  1651. keys_to_delete.append(uid)
  1652. # actual delete of keys from the tools_storage dict
  1653. for k in keys_to_delete:
  1654. tools_storage.pop(k, None)
  1655. geo_obj.options["cnctooldia"] = str(tool_dia)
  1656. # this turn on the FlatCAMCNCJob plot for multiple tools
  1657. geo_obj.multigeo = True
  1658. geo_obj.multitool = True
  1659. geo_obj.tools.clear()
  1660. geo_obj.tools = dict(tools_storage)
  1661. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1662. has_solid_geo = 0
  1663. for tooluid in geo_obj.tools:
  1664. if geo_obj.tools[tooluid]['solid_geometry']:
  1665. has_solid_geo += 1
  1666. if has_solid_geo == 0:
  1667. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1668. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1669. "Change the painting parameters and try again."))
  1670. return
  1671. # Experimental...
  1672. # print("Indexing...", end=' ')
  1673. # geo_obj.make_index()
  1674. self.app.inform.emit(_("[success] Paint Area Done."))
  1675. # Initializes the new geometry object
  1676. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1677. assert isinstance(geo_obj, FlatCAMGeometry), \
  1678. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1679. tool_dia = None
  1680. sorted_tools.sort(reverse=True)
  1681. cleared_geo = []
  1682. current_uid = int(1)
  1683. geo_obj.solid_geometry = []
  1684. try:
  1685. a, b, c, d = obj.bounds()
  1686. geo_obj.options['xmin'] = a
  1687. geo_obj.options['ymin'] = b
  1688. geo_obj.options['xmax'] = c
  1689. geo_obj.options['ymax'] = d
  1690. except Exception as e:
  1691. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1692. return
  1693. for tool_dia in sorted_tools:
  1694. for geo in recurse(obj.solid_geometry):
  1695. try:
  1696. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1697. poly_buf = geo.buffer(-paint_margin)
  1698. cp = None
  1699. if paint_method == "standard":
  1700. # Type(cp) == FlatCAMRTreeStorage | None
  1701. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1702. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1703. overlap=over, contour=cont, connect=conn)
  1704. elif paint_method == "seed":
  1705. # Type(cp) == FlatCAMRTreeStorage | None
  1706. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1707. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1708. overlap=over, contour=cont, connect=conn)
  1709. elif paint_method == "lines":
  1710. # Type(cp) == FlatCAMRTreeStorage | None
  1711. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1712. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1713. overlap=over, contour=cont, connect=conn)
  1714. if cp is not None:
  1715. cleared_geo += list(cp.get_objects())
  1716. except Exception as e:
  1717. log.debug("Could not Paint the polygons. %s" % str(e))
  1718. self.app.inform.emit(
  1719. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1720. "Or a different Method of paint\n%s") % str(e))
  1721. return
  1722. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1723. for k, v in tools_storage.items():
  1724. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1725. current_uid = int(k)
  1726. break
  1727. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1728. # then reset the temporary list that stored that solid_geometry
  1729. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1730. tools_storage[current_uid]['data']['name'] = name
  1731. cleared_geo[:] = []
  1732. geo_obj.options["cnctooldia"] = str(tool_dia)
  1733. # this turn on the FlatCAMCNCJob plot for multiple tools
  1734. geo_obj.multigeo = True
  1735. geo_obj.multitool = True
  1736. geo_obj.tools.clear()
  1737. geo_obj.tools = dict(self.paint_tools)
  1738. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1739. has_solid_geo = 0
  1740. for tooluid in geo_obj.tools:
  1741. if geo_obj.tools[tooluid]['solid_geometry']:
  1742. has_solid_geo += 1
  1743. if has_solid_geo == 0:
  1744. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1745. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1746. "Change the painting parameters and try again."))
  1747. return
  1748. # Experimental...
  1749. # print("Indexing...", end=' ')
  1750. # geo_obj.make_index()
  1751. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1752. def job_thread(app_obj):
  1753. try:
  1754. if self.rest_cb.isChecked():
  1755. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1756. else:
  1757. app_obj.new_object("geometry", name, gen_paintarea)
  1758. except Exception as e:
  1759. proc.done()
  1760. traceback.print_stack()
  1761. return
  1762. proc.done()
  1763. # focus on Selected Tab
  1764. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1765. self.app.inform.emit(_("Polygon Paint started ..."))
  1766. # Promise object with the new name
  1767. self.app.collection.promise(name)
  1768. # Background
  1769. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1770. def paint_poly_ref(self, obj, sel_obj,
  1771. tooldia=None,
  1772. overlap=None,
  1773. order=None,
  1774. margin=None,
  1775. method=None,
  1776. outname=None,
  1777. connect=None,
  1778. contour=None,
  1779. tools_storage=None):
  1780. """
  1781. Paints all polygons in this object that are within the sel_obj object
  1782. :param obj: painted object
  1783. :param sel_obj: paint only what is inside this object bounds
  1784. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1785. :param overlap: value by which the paths will overlap
  1786. :param order: if the tools are ordered and how
  1787. :param margin: a border around painting area
  1788. :param outname: name of the resulting object
  1789. :param connect: Connect lines to avoid tool lifts.
  1790. :param contour: Paint around the edges.
  1791. :param method: choice out of 'seed', 'normal', 'lines'
  1792. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1793. Usage of the different one is related to when this function is called from a TcL command.
  1794. :return:
  1795. """
  1796. geo = sel_obj.solid_geometry
  1797. try:
  1798. if isinstance(geo, MultiPolygon):
  1799. env_obj = geo.convex_hull
  1800. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  1801. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  1802. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1803. else:
  1804. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1805. env_obj = env_obj.convex_hull
  1806. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  1807. except Exception as e:
  1808. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1809. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1810. return
  1811. self.paint_poly_area(obj=obj,
  1812. sel_obj=sel_rect,
  1813. tooldia=tooldia,
  1814. overlap=overlap,
  1815. order=order,
  1816. margin=margin,
  1817. method=method,
  1818. outname=outname,
  1819. connect=connect,
  1820. contour=contour,
  1821. tools_storage=tools_storage)
  1822. @staticmethod
  1823. def paint_bounds(geometry):
  1824. def bounds_rec(o):
  1825. if type(o) is list:
  1826. minx = Inf
  1827. miny = Inf
  1828. maxx = -Inf
  1829. maxy = -Inf
  1830. for k in o:
  1831. try:
  1832. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1833. except Exception as e:
  1834. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1835. return
  1836. minx = min(minx, minx_)
  1837. miny = min(miny, miny_)
  1838. maxx = max(maxx, maxx_)
  1839. maxy = max(maxy, maxy_)
  1840. return minx, miny, maxx, maxy
  1841. else:
  1842. # it's a Shapely object, return it's bounds
  1843. return o.bounds
  1844. return bounds_rec(geometry)
  1845. def reset_fields(self):
  1846. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))