ToolPaint.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  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. import gettext
  12. import FlatCAMTranslation as fcTranslate
  13. import builtins
  14. fcTranslate.apply_language('strings')
  15. if '_' not in builtins.__dict__:
  16. _ = gettext.gettext
  17. class ToolPaint(FlatCAMTool, Gerber):
  18. toolName = _("Paint Area")
  19. def __init__(self, app):
  20. self.app = app
  21. FlatCAMTool.__init__(self, app)
  22. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  23. # ## Title
  24. title_label = QtWidgets.QLabel("%s" % self.toolName)
  25. title_label.setStyleSheet("""
  26. QLabel
  27. {
  28. font-size: 16px;
  29. font-weight: bold;
  30. }
  31. """)
  32. self.layout.addWidget(title_label)
  33. self.tools_frame = QtWidgets.QFrame()
  34. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  35. self.layout.addWidget(self.tools_frame)
  36. self.tools_box = QtWidgets.QVBoxLayout()
  37. self.tools_box.setContentsMargins(0, 0, 0, 0)
  38. self.tools_frame.setLayout(self.tools_box)
  39. # ## Form Layout
  40. form_layout = QtWidgets.QFormLayout()
  41. self.tools_box.addLayout(form_layout)
  42. # ## Object
  43. self.object_combo = QtWidgets.QComboBox()
  44. self.object_combo.setModel(self.app.collection)
  45. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  46. self.object_combo.setCurrentIndex(1)
  47. self.object_label = QtWidgets.QLabel(_("Geometry:"))
  48. self.object_label.setToolTip(
  49. _("Geometry object to be painted. ")
  50. )
  51. e_lab_0 = QtWidgets.QLabel('')
  52. form_layout.addRow(self.object_label, self.object_combo)
  53. form_layout.addRow(e_lab_0)
  54. # ### Tools ## ##
  55. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  56. self.tools_table_label.setToolTip(
  57. _("Tools pool from which the algorithm\n"
  58. "will pick the ones used for painting.")
  59. )
  60. self.tools_box.addWidget(self.tools_table_label)
  61. self.tools_table = FCTable()
  62. self.tools_box.addWidget(self.tools_table)
  63. self.tools_table.setColumnCount(4)
  64. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  65. self.tools_table.setColumnHidden(3, True)
  66. # self.tools_table.setSortingEnabled(False)
  67. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  68. self.tools_table.horizontalHeaderItem(0).setToolTip(
  69. _("This is the Tool Number.\n"
  70. "Painting will start with the tool with the biggest diameter,\n"
  71. "continuing until there are no more tools.\n"
  72. "Only tools that create painting geometry will still be present\n"
  73. "in the resulting geometry. This is because with some tools\n"
  74. "this function will not be able to create painting geometry.")
  75. )
  76. self.tools_table.horizontalHeaderItem(1).setToolTip(
  77. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  78. "is the cut width into the material."))
  79. self.tools_table.horizontalHeaderItem(2).setToolTip(
  80. _("The Tool Type (TT) can be:<BR>"
  81. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  82. "the cut width in material is exactly the tool diameter.<BR>"
  83. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  84. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  85. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  86. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  87. "as the cut width into material will be equal with the value in the Tool Diameter "
  88. "column of this table.<BR>"
  89. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  90. "in the resulting geometry as Isolation."))
  91. self.empty_label = QtWidgets.QLabel('')
  92. self.tools_box.addWidget(self.empty_label)
  93. # ### Add a new Tool ## ##
  94. hlay = QtWidgets.QHBoxLayout()
  95. self.tools_box.addLayout(hlay)
  96. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  97. self.addtool_entry_lbl.setToolTip(
  98. _("Diameter for the new tool.")
  99. )
  100. self.addtool_entry = FCEntry2()
  101. # hlay.addWidget(self.addtool_label)
  102. # hlay.addStretch()
  103. hlay.addWidget(self.addtool_entry_lbl)
  104. hlay.addWidget(self.addtool_entry)
  105. grid2 = QtWidgets.QGridLayout()
  106. self.tools_box.addLayout(grid2)
  107. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  108. self.addtool_btn.setToolTip(
  109. _("Add a new tool to the Tool Table\n"
  110. "with the diameter specified above.")
  111. )
  112. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  113. # self.copytool_btn.setToolTip(
  114. # "Copy a selection of tools in the Tool Table\n"
  115. # "by first selecting a row in the Tool Table."
  116. # )
  117. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  118. self.deltool_btn.setToolTip(
  119. _("Delete a selection of tools in the Tool Table\n"
  120. "by first selecting a row(s) in the Tool Table.")
  121. )
  122. grid2.addWidget(self.addtool_btn, 0, 0)
  123. # grid2.addWidget(self.copytool_btn, 0, 1)
  124. grid2.addWidget(self.deltool_btn, 0, 2)
  125. self.empty_label_0 = QtWidgets.QLabel('')
  126. self.tools_box.addWidget(self.empty_label_0)
  127. grid3 = QtWidgets.QGridLayout()
  128. self.tools_box.addLayout(grid3)
  129. # Overlap
  130. ovlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  131. ovlabel.setToolTip(
  132. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  133. "Example:\n"
  134. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  135. "Adjust the value starting with lower values\n"
  136. "and increasing it if areas that should be painted are still \n"
  137. "not painted.\n"
  138. "Lower values = faster processing, faster execution on PCB.\n"
  139. "Higher values = slow processing and slow execution on CNC\n"
  140. "due of too many paths.")
  141. )
  142. grid3.addWidget(ovlabel, 1, 0)
  143. self.paintoverlap_entry = FCEntry()
  144. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  145. # Margin
  146. marginlabel = QtWidgets.QLabel(_('Margin:'))
  147. marginlabel.setToolTip(
  148. _("Distance by which to avoid\n"
  149. "the edges of the polygon to\n"
  150. "be painted.")
  151. )
  152. grid3.addWidget(marginlabel, 2, 0)
  153. self.paintmargin_entry = FCEntry()
  154. grid3.addWidget(self.paintmargin_entry, 2, 1)
  155. # Method
  156. methodlabel = QtWidgets.QLabel(_('Method:'))
  157. methodlabel.setToolTip(
  158. _("Algorithm for non-copper clearing:<BR>"
  159. "<B>Standard</B>: Fixed step inwards.<BR>"
  160. "<B>Seed-based</B>: Outwards from seed.<BR>"
  161. "<B>Line-based</B>: Parallel lines.")
  162. )
  163. grid3.addWidget(methodlabel, 3, 0)
  164. self.paintmethod_combo = RadioSet([
  165. {"label": _("Standard"), "value": "standard"},
  166. {"label": _("Seed-based"), "value": "seed"},
  167. {"label": _("Straight lines"), "value": "lines"}
  168. ], orientation='vertical', stretch=False)
  169. grid3.addWidget(self.paintmethod_combo, 3, 1)
  170. # Connect lines
  171. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  172. pathconnectlabel.setToolTip(
  173. _("Draw lines between resulting\n"
  174. "segments to minimize tool lifts.")
  175. )
  176. grid3.addWidget(pathconnectlabel, 4, 0)
  177. self.pathconnect_cb = FCCheckBox()
  178. grid3.addWidget(self.pathconnect_cb, 4, 1)
  179. contourlabel = QtWidgets.QLabel(_("Contour:"))
  180. contourlabel.setToolTip(
  181. _("Cut around the perimeter of the polygon\n"
  182. "to trim rough edges.")
  183. )
  184. grid3.addWidget(contourlabel, 5, 0)
  185. self.paintcontour_cb = FCCheckBox()
  186. grid3.addWidget(self.paintcontour_cb, 5, 1)
  187. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  188. restlabel.setToolTip(
  189. _("If checked, use 'rest machining'.\n"
  190. "Basically it will clear copper outside PCB features,\n"
  191. "using the biggest tool and continue with the next tools,\n"
  192. "from bigger to smaller, to clear areas of copper that\n"
  193. "could not be cleared by previous tool, until there is\n"
  194. "no more copper to clear or there are no more tools.\n\n"
  195. "If not checked, use the standard algorithm.")
  196. )
  197. grid3.addWidget(restlabel, 6, 0)
  198. self.rest_cb = FCCheckBox()
  199. grid3.addWidget(self.rest_cb, 6, 1)
  200. # Polygon selection
  201. selectlabel = QtWidgets.QLabel(_('Selection:'))
  202. selectlabel.setToolTip(
  203. _("How to select the polygons to paint.<BR>"
  204. "Options:<BR>"
  205. "- <B>Single</B>: left mouse click on the polygon to be painted.<BR>"
  206. "- <B>Area</B>: left mouse click to start selection of the area to be painted.<BR>"
  207. "- <B>All</B>: paint all polygons.<BR>"
  208. "- <B>Ref</B>: paint an area described by an external reference object.")
  209. )
  210. grid3.addWidget(selectlabel, 7, 0)
  211. # grid3 = QtWidgets.QGridLayout()
  212. self.selectmethod_combo = RadioSet([
  213. {"label": _("Single"), "value": "single"},
  214. {"label": _("Area"), "value": "area"},
  215. {"label": _("All"), "value": "all"},
  216. {"label": _("Ref."), "value": "ref"}
  217. ])
  218. grid3.addWidget(self.selectmethod_combo, 7, 1)
  219. grid4 = QtWidgets.QGridLayout()
  220. self.tools_box.addLayout(grid4)
  221. self.box_combo_type_label = QtWidgets.QLabel(_("Ref. Type:"))
  222. self.box_combo_type_label.setToolTip(
  223. _("The type of FlatCAM object to be used as paint reference.\n"
  224. "It can be Gerber, Excellon or Geometry.")
  225. )
  226. self.box_combo_type = QtWidgets.QComboBox()
  227. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  228. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  229. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  230. grid4.addWidget(self.box_combo_type_label, 0, 0)
  231. grid4.addWidget(self.box_combo_type, 0, 1)
  232. self.box_combo_label = QtWidgets.QLabel(_("Ref. Object:"))
  233. self.box_combo_label.setToolTip(
  234. _("The FlatCAM object to be used as non copper clearing reference.")
  235. )
  236. self.box_combo = QtWidgets.QComboBox()
  237. self.box_combo.setModel(self.app.collection)
  238. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  239. self.box_combo.setCurrentIndex(1)
  240. grid4.addWidget(self.box_combo_label, 1, 0)
  241. grid4.addWidget(self.box_combo, 1, 1)
  242. self.box_combo.hide()
  243. self.box_combo_label.hide()
  244. self.box_combo_type.hide()
  245. self.box_combo_type_label.hide()
  246. # GO Button
  247. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  248. self.generate_paint_button.setToolTip(
  249. _("After clicking here, click inside<BR>"
  250. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  251. "If <B>Area</B> is selected, then the selection of the area to be painted<BR>"
  252. "will be initiated by a first click and finished by the second mouse click.<BR>"
  253. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  254. "If <B>Ref</B> is selected then the Paint will start after click,<BR>"
  255. "and the painted area will be described by a selected object.<BR>"
  256. "A new Geometry object with the tool paths will be created.")
  257. )
  258. self.tools_box.addWidget(self.generate_paint_button)
  259. self.tools_box.addStretch()
  260. self.obj_name = ""
  261. self.paint_obj = None
  262. self.units = ''
  263. self.paint_tools = {}
  264. self.tooluid = 0
  265. self.first_click = False
  266. self.cursor_pos = None
  267. # store here the default data for Geometry Data
  268. self.default_data = {}
  269. self.default_data.update({
  270. "name": '_paint',
  271. "plot": self.app.defaults["geometry_plot"],
  272. "cutz": self.app.defaults["geometry_cutz"],
  273. "vtipdia": 0.1,
  274. "vtipangle": 30,
  275. "travelz": self.app.defaults["geometry_travelz"],
  276. "feedrate": self.app.defaults["geometry_feedrate"],
  277. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  278. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  279. "dwell": self.app.defaults["geometry_dwell"],
  280. "dwelltime": self.app.defaults["geometry_dwelltime"],
  281. "multidepth": self.app.defaults["geometry_multidepth"],
  282. "ppname_g": self.app.defaults["geometry_ppname_g"],
  283. "depthperpass": self.app.defaults["geometry_depthperpass"],
  284. "extracut": self.app.defaults["geometry_extracut"],
  285. "toolchange": self.app.defaults["geometry_toolchange"],
  286. "toolchangez": self.app.defaults["geometry_toolchangez"],
  287. "endz": self.app.defaults["geometry_endz"],
  288. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  289. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  290. "startz": self.app.defaults["geometry_startz"],
  291. "tooldia": self.app.defaults["tools_painttooldia"],
  292. "paintmargin": self.app.defaults["tools_paintmargin"],
  293. "paintmethod": self.app.defaults["tools_paintmethod"],
  294. "selectmethod": self.app.defaults["tools_selectmethod"],
  295. "pathconnect": self.app.defaults["tools_pathconnect"],
  296. "paintcontour": self.app.defaults["tools_paintcontour"],
  297. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  298. })
  299. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  300. # ## Signals
  301. self.addtool_btn.clicked.connect(self.on_tool_add)
  302. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  303. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  304. self.tools_table.itemChanged.connect(self.on_tool_edit)
  305. self.deltool_btn.clicked.connect(self.on_tool_delete)
  306. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  307. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  308. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  309. def install(self, icon=None, separator=None, **kwargs):
  310. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  311. def run(self, toggle=True):
  312. self.app.report_usage("ToolPaint()")
  313. if toggle:
  314. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  315. if self.app.ui.splitter.sizes()[0] == 0:
  316. self.app.ui.splitter.setSizes([1, 1])
  317. else:
  318. try:
  319. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  320. self.app.ui.splitter.setSizes([0, 1])
  321. except AttributeError:
  322. pass
  323. else:
  324. if self.app.ui.splitter.sizes()[0] == 0:
  325. self.app.ui.splitter.setSizes([1, 1])
  326. FlatCAMTool.run(self)
  327. self.set_tool_ui()
  328. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  329. def on_radio_selection(self):
  330. if self.selectmethod_combo.get_value() == "ref":
  331. self.box_combo.show()
  332. self.box_combo_label.show()
  333. self.box_combo_type.show()
  334. self.box_combo_type_label.show()
  335. else:
  336. self.box_combo.hide()
  337. self.box_combo_label.hide()
  338. self.box_combo_type.hide()
  339. self.box_combo_type_label.hide()
  340. if self.selectmethod_combo.get_value() == 'single':
  341. # disable rest-machining for single polygon painting
  342. self.rest_cb.set_value(False)
  343. self.rest_cb.setDisabled(True)
  344. # delete all tools except first row / tool for single polygon painting
  345. list_to_del = list(range(1, self.tools_table.rowCount()))
  346. if list_to_del:
  347. self.on_tool_delete(rows_to_delete=list_to_del)
  348. # disable addTool and delTool
  349. self.addtool_entry.setDisabled(True)
  350. self.addtool_btn.setDisabled(True)
  351. self.deltool_btn.setDisabled(True)
  352. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  353. if self.selectmethod_combo.get_value() == 'area':
  354. # disable rest-machining for single polygon painting
  355. self.rest_cb.set_value(False)
  356. self.rest_cb.setDisabled(True)
  357. else:
  358. self.rest_cb.setDisabled(False)
  359. self.addtool_entry.setDisabled(False)
  360. self.addtool_btn.setDisabled(False)
  361. self.deltool_btn.setDisabled(False)
  362. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  363. def set_tool_ui(self):
  364. self.tools_frame.show()
  365. self.reset_fields()
  366. # ## Init the GUI interface
  367. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  368. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  369. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  370. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  371. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  372. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  373. # updated units
  374. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  375. if self.units == "IN":
  376. self.addtool_entry.set_value(0.039)
  377. else:
  378. self.addtool_entry.set_value(1)
  379. self.tools_table.setupContextMenu()
  380. self.tools_table.addContextMenu(
  381. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  382. self.tools_table.addContextMenu(
  383. "Delete", lambda:
  384. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  385. # set the working variables to a known state
  386. self.paint_tools.clear()
  387. self.tooluid = 0
  388. self.default_data.clear()
  389. self.default_data.update({
  390. "name": '_paint',
  391. "plot": self.app.defaults["geometry_plot"],
  392. "cutz": self.app.defaults["geometry_cutz"],
  393. "vtipdia": 0.1,
  394. "vtipangle": 30,
  395. "travelz": self.app.defaults["geometry_travelz"],
  396. "feedrate": self.app.defaults["geometry_feedrate"],
  397. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  398. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  399. "dwell": self.app.defaults["geometry_dwell"],
  400. "dwelltime": self.app.defaults["geometry_dwelltime"],
  401. "multidepth": self.app.defaults["geometry_multidepth"],
  402. "ppname_g": self.app.defaults["geometry_ppname_g"],
  403. "depthperpass": self.app.defaults["geometry_depthperpass"],
  404. "extracut": self.app.defaults["geometry_extracut"],
  405. "toolchange": self.app.defaults["geometry_toolchange"],
  406. "toolchangez": self.app.defaults["geometry_toolchangez"],
  407. "endz": self.app.defaults["geometry_endz"],
  408. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  409. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  410. "startz": self.app.defaults["geometry_startz"],
  411. "tooldia": self.app.defaults["tools_painttooldia"],
  412. "paintmargin": self.app.defaults["tools_paintmargin"],
  413. "paintmethod": self.app.defaults["tools_paintmethod"],
  414. "selectmethod": self.app.defaults["tools_selectmethod"],
  415. "pathconnect": self.app.defaults["tools_pathconnect"],
  416. "paintcontour": self.app.defaults["tools_paintcontour"],
  417. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  418. })
  419. # call on self.on_tool_add() counts as an call to self.build_ui()
  420. # through this, we add a initial row / tool in the tool_table
  421. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  422. # if the Paint Method is "Single" disable the tool table context menu
  423. if self.default_data["selectmethod"] == "single":
  424. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  425. def build_ui(self):
  426. try:
  427. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  428. self.tools_table.itemChanged.disconnect()
  429. except (TypeError, AttributeError):
  430. pass
  431. # updated units
  432. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  433. sorted_tools = []
  434. for k, v in self.paint_tools.items():
  435. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  436. sorted_tools.sort()
  437. n = len(sorted_tools)
  438. self.tools_table.setRowCount(n)
  439. tool_id = 0
  440. for tool_sorted in sorted_tools:
  441. for tooluid_key, tooluid_value in self.paint_tools.items():
  442. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  443. tool_id += 1
  444. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  445. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  446. row_no = tool_id - 1
  447. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  448. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  449. # There are no drill bits in MM with more than 3 decimals diameter
  450. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  451. if self.units == 'MM':
  452. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  453. else:
  454. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  455. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  456. tool_type_item = QtWidgets.QComboBox()
  457. for item in self.tool_type_item_options:
  458. tool_type_item.addItem(item)
  459. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  460. idx = tool_type_item.findText(tooluid_value['tool_type'])
  461. tool_type_item.setCurrentIndex(idx)
  462. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  463. self.tools_table.setItem(row_no, 1, dia) # Diameter
  464. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  465. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  466. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  467. # make the diameter column editable
  468. for row in range(tool_id):
  469. self.tools_table.item(row, 1).setFlags(
  470. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  471. # all the tools are selected by default
  472. self.tools_table.selectColumn(0)
  473. #
  474. self.tools_table.resizeColumnsToContents()
  475. self.tools_table.resizeRowsToContents()
  476. vertical_header = self.tools_table.verticalHeader()
  477. vertical_header.hide()
  478. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  479. horizontal_header = self.tools_table.horizontalHeader()
  480. horizontal_header.setMinimumSectionSize(10)
  481. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  482. horizontal_header.resizeSection(0, 20)
  483. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  484. # self.tools_table.setSortingEnabled(True)
  485. # sort by tool diameter
  486. # self.tools_table.sortItems(1)
  487. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  488. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  489. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  490. self.tools_table.itemChanged.connect(self.on_tool_edit)
  491. def on_combo_box_type(self):
  492. obj_type = self.box_combo_type.currentIndex()
  493. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  494. self.box_combo.setCurrentIndex(0)
  495. def on_tool_add(self, dia=None, muted=None):
  496. try:
  497. self.tools_table.itemChanged.disconnect()
  498. except Exception as e:
  499. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  500. if dia:
  501. tool_dia = dia
  502. else:
  503. try:
  504. tool_dia = float(self.addtool_entry.get_value())
  505. except ValueError:
  506. # try to convert comma to decimal point. if it's still not working error message and return
  507. try:
  508. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  509. except ValueError:
  510. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  511. "use a number."))
  512. return
  513. if tool_dia is None:
  514. self.build_ui()
  515. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  516. return
  517. # construct a list of all 'tooluid' in the self.tools
  518. tool_uid_list = []
  519. for tooluid_key in self.paint_tools:
  520. tool_uid_item = int(tooluid_key)
  521. tool_uid_list.append(tool_uid_item)
  522. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  523. if not tool_uid_list:
  524. max_uid = 0
  525. else:
  526. max_uid = max(tool_uid_list)
  527. self.tooluid = int(max_uid + 1)
  528. tool_dias = []
  529. for k, v in self.paint_tools.items():
  530. for tool_v in v.keys():
  531. if tool_v == 'tooldia':
  532. tool_dias.append(float('%.4f' % v[tool_v]))
  533. if float('%.4f' % tool_dia) in tool_dias:
  534. if muted is None:
  535. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  536. self.tools_table.itemChanged.connect(self.on_tool_edit)
  537. return
  538. else:
  539. if muted is None:
  540. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  541. self.paint_tools.update({
  542. int(self.tooluid): {
  543. 'tooldia': float('%.4f' % tool_dia),
  544. 'offset': 'Path',
  545. 'offset_value': 0.0,
  546. 'type': 'Iso',
  547. 'tool_type': 'V',
  548. 'data': dict(self.default_data),
  549. 'solid_geometry': []
  550. }
  551. })
  552. self.build_ui()
  553. def on_tool_edit(self):
  554. old_tool_dia = ''
  555. try:
  556. self.tools_table.itemChanged.disconnect()
  557. except Exception as e:
  558. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  559. tool_dias = []
  560. for k, v in self.paint_tools.items():
  561. for tool_v in v.keys():
  562. if tool_v == 'tooldia':
  563. tool_dias.append(float('%.4f' % v[tool_v]))
  564. for row in range(self.tools_table.rowCount()):
  565. try:
  566. new_tool_dia = float(self.tools_table.item(row, 1).text())
  567. except ValueError:
  568. # try to convert comma to decimal point. if it's still not working error message and return
  569. try:
  570. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  571. except ValueError:
  572. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  573. "use a number."))
  574. return
  575. tooluid = int(self.tools_table.item(row, 3).text())
  576. # identify the tool that was edited and get it's tooluid
  577. if new_tool_dia not in tool_dias:
  578. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  579. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  580. self.build_ui()
  581. return
  582. else:
  583. # identify the old tool_dia and restore the text in tool table
  584. for k, v in self.paint_tools.items():
  585. if k == tooluid:
  586. old_tool_dia = v['tooldia']
  587. break
  588. restore_dia_item = self.tools_table.item(row, 1)
  589. restore_dia_item.setText(str(old_tool_dia))
  590. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  591. "New diameter value is already in the Tool Table."))
  592. self.build_ui()
  593. # def on_tool_copy(self, all=None):
  594. # try:
  595. # self.tools_table.itemChanged.disconnect()
  596. # except:
  597. # pass
  598. #
  599. # # find the tool_uid maximum value in the self.tools
  600. # uid_list = []
  601. # for key in self.paint_tools:
  602. # uid_list.append(int(key))
  603. # try:
  604. # max_uid = max(uid_list, key=int)
  605. # except ValueError:
  606. # max_uid = 0
  607. #
  608. # if all is None:
  609. # if self.tools_table.selectedItems():
  610. # for current_row in self.tools_table.selectedItems():
  611. # # sometime the header get selected and it has row number -1
  612. # # we don't want to do anything with the header :)
  613. # if current_row.row() < 0:
  614. # continue
  615. # try:
  616. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  617. # max_uid += 1
  618. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  619. # for td in self.paint_tools:
  620. # print("COPIED", self.paint_tools[td])
  621. # self.build_ui()
  622. # except AttributeError:
  623. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  624. # self.build_ui()
  625. # return
  626. # except Exception as e:
  627. # log.debug("on_tool_copy() --> " + str(e))
  628. # # deselect the table
  629. # # self.ui.geo_tools_table.clearSelection()
  630. # else:
  631. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  632. # self.build_ui()
  633. # return
  634. # else:
  635. # # we copy all tools in geo_tools_table
  636. # try:
  637. # temp_tools = dict(self.paint_tools)
  638. # max_uid += 1
  639. # for tooluid in temp_tools:
  640. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  641. # temp_tools.clear()
  642. # self.build_ui()
  643. # except Exception as e:
  644. # log.debug("on_tool_copy() --> " + str(e))
  645. #
  646. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  647. def on_tool_delete(self, rows_to_delete=None, all=None):
  648. try:
  649. self.tools_table.itemChanged.disconnect()
  650. except Exception as e:
  651. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  652. pass
  653. deleted_tools_list = []
  654. if all:
  655. self.paint_tools.clear()
  656. self.build_ui()
  657. return
  658. if rows_to_delete:
  659. try:
  660. for row in rows_to_delete:
  661. tooluid_del = int(self.tools_table.item(row, 3).text())
  662. deleted_tools_list.append(tooluid_del)
  663. except TypeError:
  664. deleted_tools_list.append(rows_to_delete)
  665. for t in deleted_tools_list:
  666. self.paint_tools.pop(t, None)
  667. self.build_ui()
  668. return
  669. try:
  670. if self.tools_table.selectedItems():
  671. for row_sel in self.tools_table.selectedItems():
  672. row = row_sel.row()
  673. if row < 0:
  674. continue
  675. tooluid_del = int(self.tools_table.item(row, 3).text())
  676. deleted_tools_list.append(tooluid_del)
  677. for t in deleted_tools_list:
  678. self.paint_tools.pop(t, None)
  679. except AttributeError:
  680. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  681. return
  682. except Exception as e:
  683. log.debug(str(e))
  684. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  685. self.build_ui()
  686. def on_paint_button_click(self):
  687. self.app.report_usage(_("geometry_on_paint_button"))
  688. # self.app.call_source = 'paint'
  689. try:
  690. overlap = float(self.paintoverlap_entry.get_value())
  691. except ValueError:
  692. # try to convert comma to decimal point. if it's still not working error message and return
  693. try:
  694. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  695. except ValueError:
  696. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  697. "use a number."))
  698. return
  699. if overlap >= 1 or overlap < 0:
  700. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  701. "0 (inclusive) and 1 (exclusive), "))
  702. return
  703. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  704. connect = self.pathconnect_cb.get_value()
  705. contour = self.paintcontour_cb.get_value()
  706. select_method = self.selectmethod_combo.get_value()
  707. self.obj_name = self.object_combo.currentText()
  708. # Get source object.
  709. try:
  710. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  711. except Exception as e:
  712. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  713. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  714. return
  715. if self.paint_obj is None:
  716. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  717. return
  718. # test if the Geometry Object is multigeo and return Fail if True because
  719. # for now Paint don't work on MultiGeo
  720. if self.paint_obj.multigeo is True:
  721. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  722. return 'Fail'
  723. o_name = '%s_multitool_paint' % self.obj_name
  724. if select_method == "all":
  725. self.paint_poly_all(self.paint_obj,
  726. outname=o_name,
  727. overlap=overlap,
  728. connect=connect,
  729. contour=contour)
  730. elif select_method == "single":
  731. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  732. # use the first tool in the tool table; get the diameter
  733. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  734. # To be called after clicking on the plot.
  735. def doit(event):
  736. # do paint single only for left mouse clicks
  737. if event.button == 1:
  738. self.app.inform.emit(_("Painting polygon..."))
  739. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  740. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  741. if self.app.grid_status() == True:
  742. pos = self.app.geo_editor.snap(pos[0], pos[1])
  743. self.paint_poly(self.paint_obj,
  744. inside_pt=[pos[0], pos[1]],
  745. tooldia=tooldia,
  746. overlap=overlap,
  747. connect=connect,
  748. contour=contour)
  749. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  750. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  751. self.app.plotcanvas.vis_connect('mouse_press', doit)
  752. elif select_method == "area":
  753. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  754. # use the first tool in the tool table; get the diameter
  755. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  756. # To be called after clicking on the plot.
  757. def on_mouse_press(event):
  758. # do paint single only for left mouse clicks
  759. if event.button == 1:
  760. if not self.first_click:
  761. self.first_click = True
  762. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  763. self.cursor_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  764. if self.app.grid_status() == True:
  765. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  766. else:
  767. self.app.inform.emit(_("Done."))
  768. self.first_click = False
  769. self.app.delete_selection_shape()
  770. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  771. if self.app.grid_status() == True:
  772. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  773. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  774. x1, y1 = curr_pos[0], curr_pos[1]
  775. pt1 = (x0, y0)
  776. pt2 = (x1, y0)
  777. pt3 = (x1, y1)
  778. pt4 = (x0, y1)
  779. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  780. self.paint_poly_area(obj=self.paint_obj,
  781. sel_obj= sel_rect,
  782. outname=o_name,
  783. overlap=overlap,
  784. connect=connect,
  785. contour=contour)
  786. self.app.plotcanvas.vis_disconnect('mouse_press', on_mouse_press)
  787. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  788. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  789. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  790. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  791. # called on mouse move
  792. def on_mouse_move(event):
  793. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  794. self.app.app_cursor.enabled = False
  795. if self.app.grid_status() == True:
  796. self.app.app_cursor.enabled = True
  797. # Update cursor
  798. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  799. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  800. symbol='++', edge_color='black', size=20)
  801. if self.first_click:
  802. self.app.delete_selection_shape()
  803. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  804. coords=(curr_pos[0], curr_pos[1]),
  805. face_alpha=0.0)
  806. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  807. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  808. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  809. self.app.plotcanvas.vis_connect('mouse_press', on_mouse_press)
  810. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  811. def paint_poly(self, obj, inside_pt, tooldia, overlap, outname=None, connect=True, contour=True):
  812. """
  813. Paints a polygon selected by clicking on its interior.
  814. Note:
  815. * The margin is taken directly from the form.
  816. :param obj: painted object
  817. :param inside_pt: [x, y]
  818. :param tooldia: Diameter of the painting tool
  819. :param overlap: Overlap of the tool between passes.
  820. :param outname: Name of the resulting Geometry Object.
  821. :param connect: Connect lines to avoid tool lifts.
  822. :param contour: Paint around the edges.
  823. :return: None
  824. """
  825. # Which polygon.
  826. # poly = find_polygon(self.solid_geometry, inside_pt)
  827. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  828. paint_method = self.paintmethod_combo.get_value()
  829. try:
  830. paint_margin = float(self.paintmargin_entry.get_value())
  831. except ValueError:
  832. # try to convert comma to decimal point. if it's still not working error message and return
  833. try:
  834. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  835. except ValueError:
  836. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  837. "use a number."))
  838. return
  839. # No polygon?
  840. if poly is None:
  841. self.app.log.warning('No polygon found.')
  842. self.app.inform.emit(_('[WARNING] No polygon found.'))
  843. return
  844. proc = self.app.proc_container.new(_("Painting polygon."))
  845. name = outname if outname else self.obj_name + "_paint"
  846. # Initializes the new geometry object
  847. def gen_paintarea(geo_obj, app_obj):
  848. assert isinstance(geo_obj, FlatCAMGeometry), \
  849. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  850. # assert isinstance(app_obj, App)
  851. def paint_p(polyg):
  852. if paint_method == "seed":
  853. # Type(cp) == FlatCAMRTreeStorage | None
  854. cpoly = self.clear_polygon2(polyg,
  855. tooldia=tooldia,
  856. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  857. overlap=overlap,
  858. contour=contour,
  859. connect=connect)
  860. elif paint_method == "lines":
  861. # Type(cp) == FlatCAMRTreeStorage | None
  862. cpoly = self.clear_polygon3(polyg,
  863. tooldia=tooldia,
  864. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  865. overlap=overlap,
  866. contour=contour,
  867. connect=connect)
  868. else:
  869. # Type(cp) == FlatCAMRTreeStorage | None
  870. cpoly = self.clear_polygon(polyg,
  871. tooldia=tooldia,
  872. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  873. overlap=overlap,
  874. contour=contour,
  875. connect=connect)
  876. if cpoly is not None:
  877. geo_obj.solid_geometry += list(cpoly.get_objects())
  878. return cpoly
  879. else:
  880. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  881. return None
  882. geo_obj.solid_geometry = []
  883. try:
  884. a, b, c, d = poly.bounds
  885. geo_obj.options['xmin'] = a
  886. geo_obj.options['ymin'] = b
  887. geo_obj.options['xmax'] = c
  888. geo_obj.options['ymax'] = d
  889. except Exception as e:
  890. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  891. return
  892. try:
  893. poly_buf = poly.buffer(-paint_margin)
  894. if isinstance(poly_buf, MultiPolygon):
  895. cp = []
  896. for pp in poly_buf:
  897. cp.append(paint_p(pp))
  898. else:
  899. cp = paint_p(poly_buf)
  900. except Exception as e:
  901. log.debug("Could not Paint the polygons. %s" % str(e))
  902. self.app.inform.emit(
  903. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  904. "Or a different strategy of paint\n%s") % str(e))
  905. return
  906. if cp is not None:
  907. if isinstance(cp, list):
  908. for x in cp:
  909. geo_obj.solid_geometry += list(x.get_objects())
  910. else:
  911. geo_obj.solid_geometry = list(cp.get_objects())
  912. geo_obj.options["cnctooldia"] = str(tooldia)
  913. # this turn on the FlatCAMCNCJob plot for multiple tools
  914. geo_obj.multigeo = False
  915. geo_obj.multitool = True
  916. current_uid = int(self.tools_table.item(0, 3).text())
  917. for k, v in self.paint_tools.items():
  918. if k == current_uid:
  919. v['data']['name'] = name
  920. geo_obj.tools = dict(self.paint_tools)
  921. # Experimental...
  922. # print("Indexing...", end=' ')
  923. # geo_obj.make_index()
  924. # if errors == 0:
  925. # print("[success] Paint single polygon Done")
  926. # self.app.inform.emit("[success] Paint single polygon Done")
  927. # else:
  928. # print("[WARNING] Paint single polygon done with errors")
  929. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  930. # "%d area(s) could not be painted.\n"
  931. # "Use different paint parameters or edit the paint geometry and correct"
  932. # "the issue."
  933. # % errors)
  934. def job_thread(app_obj):
  935. try:
  936. app_obj.new_object("geometry", name, gen_paintarea)
  937. except Exception as e:
  938. proc.done()
  939. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  940. return
  941. proc.done()
  942. # focus on Selected Tab
  943. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  944. self.app.inform.emit(_("Polygon Paint started ..."))
  945. # Promise object with the new name
  946. self.app.collection.promise(name)
  947. # Background
  948. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  949. def paint_poly_all(self, obj, overlap, outname=None, connect=True, contour=True):
  950. """
  951. Paints all polygons in this object.
  952. :param obj: painted object
  953. :param overlap:
  954. :param outname:
  955. :param connect: Connect lines to avoid tool lifts.
  956. :param contour: Paint around the edges.
  957. :return:
  958. """
  959. paint_method = self.paintmethod_combo.get_value()
  960. try:
  961. paint_margin = float(self.paintmargin_entry.get_value())
  962. except ValueError:
  963. # try to convert comma to decimal point. if it's still not working error message and return
  964. try:
  965. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  966. except ValueError:
  967. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  968. "use a number."))
  969. return
  970. proc = self.app.proc_container.new(_("Painting polygon..."))
  971. name = outname if outname else self.obj_name + "_paint"
  972. over = overlap
  973. conn = connect
  974. cont = contour
  975. # This is a recursive generator of individual Polygons.
  976. # Note: Double check correct implementation. Might exit
  977. # early if it finds something that is not a Polygon?
  978. # def recurse(geo):
  979. # try:
  980. # for subg in geo:
  981. # for subsubg in recurse(subg):
  982. # yield subsubg
  983. # except TypeError:
  984. # if isinstance(geo, Polygon):
  985. # yield geo
  986. #
  987. # raise StopIteration
  988. def recurse(geometry, reset=True):
  989. """
  990. Creates a list of non-iterable linear geometry objects.
  991. Results are placed in self.flat_geometry
  992. :param geometry: Shapely type or list or list of list of such.
  993. :param reset: Clears the contents of self.flat_geometry.
  994. """
  995. if geometry is None:
  996. return
  997. if reset:
  998. self.flat_geometry = []
  999. # ## If iterable, expand recursively.
  1000. try:
  1001. for geo in geometry:
  1002. if geo is not None:
  1003. recurse(geometry=geo, reset=False)
  1004. # ## Not iterable, do the actual indexing and add.
  1005. except TypeError:
  1006. if isinstance(geometry, LinearRing):
  1007. g = Polygon(geometry)
  1008. self.flat_geometry.append(g)
  1009. else:
  1010. self.flat_geometry.append(geometry)
  1011. return self.flat_geometry
  1012. # Initializes the new geometry object
  1013. def gen_paintarea(geo_obj, app_obj):
  1014. assert isinstance(geo_obj, FlatCAMGeometry), \
  1015. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1016. tool_dia = None
  1017. sorted_tools = []
  1018. for row in range(self.tools_table.rowCount()):
  1019. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1020. sorted_tools.sort(reverse=True)
  1021. try:
  1022. a, b, c, d = obj.bounds()
  1023. geo_obj.options['xmin'] = a
  1024. geo_obj.options['ymin'] = b
  1025. geo_obj.options['xmax'] = c
  1026. geo_obj.options['ymax'] = d
  1027. except Exception as e:
  1028. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1029. return
  1030. total_geometry = []
  1031. current_uid = int(1)
  1032. geo_obj.solid_geometry = []
  1033. for tool_dia in sorted_tools:
  1034. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1035. for k, v in self.paint_tools.items():
  1036. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1037. current_uid = int(k)
  1038. break
  1039. for geo in recurse(obj.solid_geometry):
  1040. try:
  1041. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1042. if not isinstance(geo, Polygon):
  1043. continue
  1044. poly_buf = geo.buffer(-paint_margin)
  1045. if paint_method == "seed":
  1046. # Type(cp) == FlatCAMRTreeStorage | None
  1047. cp = self.clear_polygon2(poly_buf,
  1048. tooldia=tool_dia,
  1049. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1050. overlap=over,
  1051. contour=cont,
  1052. connect=conn)
  1053. elif paint_method == "lines":
  1054. # Type(cp) == FlatCAMRTreeStorage | None
  1055. cp = self.clear_polygon3(poly_buf,
  1056. tooldia=tool_dia,
  1057. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1058. overlap=over,
  1059. contour=cont,
  1060. connect=conn)
  1061. else:
  1062. # Type(cp) == FlatCAMRTreeStorage | None
  1063. cp = self.clear_polygon(poly_buf,
  1064. tooldia=tool_dia,
  1065. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1066. overlap=over,
  1067. contour=cont,
  1068. connect=conn)
  1069. if cp is not None:
  1070. total_geometry += list(cp.get_objects())
  1071. except Exception as e:
  1072. log.debug("Could not Paint the polygons. %s" % str(e))
  1073. self.app.inform.emit(
  1074. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1075. "Or a different Method of paint\n%s") % str(e))
  1076. return
  1077. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1078. # temporary list that stored that solid_geometry
  1079. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1080. self.paint_tools[current_uid]['data']['name'] = name
  1081. total_geometry[:] = []
  1082. geo_obj.options["cnctooldia"] = str(tool_dia)
  1083. # this turn on the FlatCAMCNCJob plot for multiple tools
  1084. geo_obj.multigeo = True
  1085. geo_obj.multitool = True
  1086. geo_obj.tools.clear()
  1087. geo_obj.tools = dict(self.paint_tools)
  1088. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1089. has_solid_geo = 0
  1090. for tooluid in geo_obj.tools:
  1091. if geo_obj.tools[tooluid]['solid_geometry']:
  1092. has_solid_geo += 1
  1093. if has_solid_geo == 0:
  1094. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1095. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1096. "Change the painting parameters and try again."))
  1097. return
  1098. # Experimental...
  1099. # print("Indexing...", end=' ')
  1100. # geo_obj.make_index()
  1101. self.app.inform.emit(_("[success] Paint All Done."))
  1102. # Initializes the new geometry object
  1103. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1104. assert isinstance(geo_obj, FlatCAMGeometry), \
  1105. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1106. tool_dia = None
  1107. sorted_tools = []
  1108. for row in range(self.tools_table.rowCount()):
  1109. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1110. sorted_tools.sort(reverse=True)
  1111. cleared_geo = []
  1112. current_uid = int(1)
  1113. geo_obj.solid_geometry = []
  1114. try:
  1115. a, b, c, d = obj.bounds()
  1116. geo_obj.options['xmin'] = a
  1117. geo_obj.options['ymin'] = b
  1118. geo_obj.options['xmax'] = c
  1119. geo_obj.options['ymax'] = d
  1120. except Exception as e:
  1121. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1122. return
  1123. for tool_dia in sorted_tools:
  1124. for geo in recurse(obj.solid_geometry):
  1125. try:
  1126. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1127. poly_buf = geo.buffer(-paint_margin)
  1128. cp = None
  1129. if paint_method == "standard":
  1130. # Type(cp) == FlatCAMRTreeStorage | None
  1131. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1132. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1133. overlap=over, contour=cont, connect=conn)
  1134. elif paint_method == "seed":
  1135. # Type(cp) == FlatCAMRTreeStorage | None
  1136. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1137. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1138. overlap=over, contour=cont, connect=conn)
  1139. elif paint_method == "lines":
  1140. # Type(cp) == FlatCAMRTreeStorage | None
  1141. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1142. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1143. overlap=over, contour=cont, connect=conn)
  1144. if cp is not None:
  1145. cleared_geo += list(cp.get_objects())
  1146. except Exception as e:
  1147. log.debug("Could not Paint the polygons. %s" % str(e))
  1148. self.app.inform.emit(
  1149. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1150. "Or a different Method of paint\n%s") % str(e))
  1151. return
  1152. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1153. for k, v in self.paint_tools.items():
  1154. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1155. current_uid = int(k)
  1156. break
  1157. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1158. # temporary list that stored that solid_geometry
  1159. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1160. self.paint_tools[current_uid]['data']['name'] = name
  1161. cleared_geo[:] = []
  1162. geo_obj.options["cnctooldia"] = str(tool_dia)
  1163. # this turn on the FlatCAMCNCJob plot for multiple tools
  1164. geo_obj.multigeo = True
  1165. geo_obj.multitool = True
  1166. geo_obj.tools.clear()
  1167. geo_obj.tools = dict(self.paint_tools)
  1168. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1169. has_solid_geo = 0
  1170. for tooluid in geo_obj.tools:
  1171. if geo_obj.tools[tooluid]['solid_geometry']:
  1172. has_solid_geo += 1
  1173. if has_solid_geo == 0:
  1174. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1175. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1176. "Change the painting parameters and try again."))
  1177. return
  1178. # Experimental...
  1179. # print("Indexing...", end=' ')
  1180. # geo_obj.make_index()
  1181. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1182. def job_thread(app_obj):
  1183. try:
  1184. if self.rest_cb.isChecked():
  1185. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1186. else:
  1187. app_obj.new_object("geometry", name, gen_paintarea)
  1188. except Exception as e:
  1189. proc.done()
  1190. traceback.print_stack()
  1191. return
  1192. proc.done()
  1193. # focus on Selected Tab
  1194. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1195. self.app.inform.emit(_("Polygon Paint started ..."))
  1196. # Promise object with the new name
  1197. self.app.collection.promise(name)
  1198. # Background
  1199. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1200. def paint_poly_area(self, obj, sel_obj, overlap, outname=None, connect=True, contour=True):
  1201. """
  1202. Paints all polygons in this object that are within the sel_obj object
  1203. :param obj: painted object
  1204. :param sel_obj: paint only what is inside this object bounds
  1205. :param overlap:
  1206. :param outname:
  1207. :param connect: Connect lines to avoid tool lifts.
  1208. :param contour: Paint around the edges.
  1209. :return:
  1210. """
  1211. paint_method = self.paintmethod_combo.get_value()
  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 else self.obj_name + "_paint"
  1224. over = overlap
  1225. conn = connect
  1226. cont = contour
  1227. def recurse(geometry, reset=True):
  1228. """
  1229. Creates a list of non-iterable linear geometry objects.
  1230. Results are placed in self.flat_geometry
  1231. :param geometry: Shapely type or list or list of list of such.
  1232. :param reset: Clears the contents of self.flat_geometry.
  1233. """
  1234. if geometry is None:
  1235. return
  1236. if reset:
  1237. self.flat_geometry = []
  1238. # ## If iterable, expand recursively.
  1239. try:
  1240. for geo in geometry:
  1241. if geo is not None:
  1242. recurse(geometry=geo, reset=False)
  1243. # ## Not iterable, do the actual indexing and add.
  1244. except TypeError:
  1245. if isinstance(geometry, LinearRing):
  1246. g = Polygon(geometry)
  1247. self.flat_geometry.append(g)
  1248. else:
  1249. self.flat_geometry.append(geometry)
  1250. return self.flat_geometry
  1251. # Initializes the new geometry object
  1252. def gen_paintarea(geo_obj, app_obj):
  1253. assert isinstance(geo_obj, FlatCAMGeometry), \
  1254. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1255. tool_dia = None
  1256. sorted_tools = []
  1257. for row in range(self.tools_table.rowCount()):
  1258. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1259. sorted_tools.sort(reverse=True)
  1260. geo_to_paint = []
  1261. for poly in obj.solid_geometry:
  1262. new_pol = poly.intersection(sel_obj)
  1263. geo_to_paint.append(new_pol)
  1264. try:
  1265. a, b, c, d = self.paint_bounds(geo_to_paint)
  1266. geo_obj.options['xmin'] = a
  1267. geo_obj.options['ymin'] = b
  1268. geo_obj.options['xmax'] = c
  1269. geo_obj.options['ymax'] = d
  1270. except Exception as e:
  1271. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1272. return
  1273. total_geometry = []
  1274. current_uid = int(1)
  1275. geo_obj.solid_geometry = []
  1276. for tool_dia in sorted_tools:
  1277. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1278. for k, v in self.paint_tools.items():
  1279. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1280. current_uid = int(k)
  1281. break
  1282. for geo in recurse(geo_to_paint):
  1283. try:
  1284. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1285. if not isinstance(geo, Polygon):
  1286. continue
  1287. poly_buf = geo.buffer(-paint_margin)
  1288. if paint_method == "seed":
  1289. # Type(cp) == FlatCAMRTreeStorage | None
  1290. cp = self.clear_polygon2(poly_buf,
  1291. tooldia=tool_dia,
  1292. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1293. overlap=over,
  1294. contour=cont,
  1295. connect=conn)
  1296. elif paint_method == "lines":
  1297. # Type(cp) == FlatCAMRTreeStorage | None
  1298. cp = self.clear_polygon3(poly_buf,
  1299. tooldia=tool_dia,
  1300. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1301. overlap=over,
  1302. contour=cont,
  1303. connect=conn)
  1304. else:
  1305. # Type(cp) == FlatCAMRTreeStorage | None
  1306. cp = self.clear_polygon(poly_buf,
  1307. tooldia=tool_dia,
  1308. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1309. overlap=over,
  1310. contour=cont,
  1311. connect=conn)
  1312. if cp is not None:
  1313. total_geometry += list(cp.get_objects())
  1314. except Exception as e:
  1315. log.debug("Could not Paint the polygons. %s" % str(e))
  1316. self.app.inform.emit(
  1317. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1318. "Or a different Method of paint\n%s") % str(e))
  1319. return
  1320. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1321. # temporary list that stored that solid_geometry
  1322. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1323. self.paint_tools[current_uid]['data']['name'] = name
  1324. total_geometry[:] = []
  1325. geo_obj.options["cnctooldia"] = str(tool_dia)
  1326. # this turn on the FlatCAMCNCJob plot for multiple tools
  1327. geo_obj.multigeo = True
  1328. geo_obj.multitool = True
  1329. geo_obj.tools.clear()
  1330. geo_obj.tools = dict(self.paint_tools)
  1331. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1332. has_solid_geo = 0
  1333. for tooluid in geo_obj.tools:
  1334. if geo_obj.tools[tooluid]['solid_geometry']:
  1335. has_solid_geo += 1
  1336. if has_solid_geo == 0:
  1337. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1338. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1339. "Change the painting parameters and try again."))
  1340. return
  1341. # Experimental...
  1342. # print("Indexing...", end=' ')
  1343. # geo_obj.make_index()
  1344. self.app.inform.emit(_("[success] Paint All Done."))
  1345. # Initializes the new geometry object
  1346. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1347. assert isinstance(geo_obj, FlatCAMGeometry), \
  1348. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1349. tool_dia = None
  1350. sorted_tools = []
  1351. for row in range(self.tools_table.rowCount()):
  1352. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1353. sorted_tools.sort(reverse=True)
  1354. cleared_geo = []
  1355. current_uid = int(1)
  1356. geo_obj.solid_geometry = []
  1357. try:
  1358. a, b, c, d = obj.bounds()
  1359. geo_obj.options['xmin'] = a
  1360. geo_obj.options['ymin'] = b
  1361. geo_obj.options['xmax'] = c
  1362. geo_obj.options['ymax'] = d
  1363. except Exception as e:
  1364. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1365. return
  1366. for tool_dia in sorted_tools:
  1367. for geo in recurse(obj.solid_geometry):
  1368. try:
  1369. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1370. poly_buf = geo.buffer(-paint_margin)
  1371. cp = None
  1372. if paint_method == "standard":
  1373. # Type(cp) == FlatCAMRTreeStorage | None
  1374. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1375. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1376. overlap=over, contour=cont, connect=conn)
  1377. elif paint_method == "seed":
  1378. # Type(cp) == FlatCAMRTreeStorage | None
  1379. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1380. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1381. overlap=over, contour=cont, connect=conn)
  1382. elif paint_method == "lines":
  1383. # Type(cp) == FlatCAMRTreeStorage | None
  1384. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1385. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1386. overlap=over, contour=cont, connect=conn)
  1387. if cp is not None:
  1388. cleared_geo += list(cp.get_objects())
  1389. except Exception as e:
  1390. log.debug("Could not Paint the polygons. %s" % str(e))
  1391. self.app.inform.emit(
  1392. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1393. "Or a different Method of paint\n%s") % str(e))
  1394. return
  1395. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1396. for k, v in self.paint_tools.items():
  1397. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1398. current_uid = int(k)
  1399. break
  1400. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1401. # temporary list that stored that solid_geometry
  1402. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1403. self.paint_tools[current_uid]['data']['name'] = name
  1404. cleared_geo[:] = []
  1405. geo_obj.options["cnctooldia"] = str(tool_dia)
  1406. # this turn on the FlatCAMCNCJob plot for multiple tools
  1407. geo_obj.multigeo = True
  1408. geo_obj.multitool = True
  1409. geo_obj.tools.clear()
  1410. geo_obj.tools = dict(self.paint_tools)
  1411. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1412. has_solid_geo = 0
  1413. for tooluid in geo_obj.tools:
  1414. if geo_obj.tools[tooluid]['solid_geometry']:
  1415. has_solid_geo += 1
  1416. if has_solid_geo == 0:
  1417. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1418. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1419. "Change the painting parameters and try again."))
  1420. return
  1421. # Experimental...
  1422. # print("Indexing...", end=' ')
  1423. # geo_obj.make_index()
  1424. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1425. def job_thread(app_obj):
  1426. try:
  1427. if self.rest_cb.isChecked():
  1428. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1429. else:
  1430. app_obj.new_object("geometry", name, gen_paintarea)
  1431. except Exception as e:
  1432. proc.done()
  1433. traceback.print_stack()
  1434. return
  1435. proc.done()
  1436. # focus on Selected Tab
  1437. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1438. self.app.inform.emit(_("Polygon Paint started ..."))
  1439. # Promise object with the new name
  1440. self.app.collection.promise(name)
  1441. # Background
  1442. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1443. @staticmethod
  1444. def paint_bounds(geometry):
  1445. def bounds_rec(o):
  1446. if type(o) is list:
  1447. minx = Inf
  1448. miny = Inf
  1449. maxx = -Inf
  1450. maxy = -Inf
  1451. for k in o:
  1452. try:
  1453. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1454. except Exception as e:
  1455. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1456. return
  1457. minx = min(minx, minx_)
  1458. miny = min(miny, miny_)
  1459. maxx = max(maxx, maxx_)
  1460. maxy = max(maxy, maxy_)
  1461. return minx, miny, maxx, maxy
  1462. else:
  1463. # it's a Shapely object, return it's bounds
  1464. return o.bounds
  1465. return bounds_rec(geometry)
  1466. def reset_fields(self):
  1467. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))