ToolPaint.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. from FlatCAMTool import FlatCAMTool
  2. from copy import copy,deepcopy
  3. from ObjectCollection import *
  4. class ToolPaint(FlatCAMTool, Gerber):
  5. toolName = "Paint Area Tool"
  6. def __init__(self, app):
  7. self.app = app
  8. FlatCAMTool.__init__(self, app)
  9. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  10. ## Title
  11. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % self.toolName)
  12. self.layout.addWidget(title_label)
  13. self.tools_frame = QtWidgets.QFrame()
  14. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  15. self.layout.addWidget(self.tools_frame)
  16. self.tools_box = QtWidgets.QVBoxLayout()
  17. self.tools_box.setContentsMargins(0, 0, 0, 0)
  18. self.tools_frame.setLayout(self.tools_box)
  19. ## Form Layout
  20. form_layout = QtWidgets.QFormLayout()
  21. self.tools_box.addLayout(form_layout)
  22. ## Object
  23. self.object_combo = QtWidgets.QComboBox()
  24. self.object_combo.setModel(self.app.collection)
  25. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  26. self.object_combo.setCurrentIndex(1)
  27. self.object_label = QtWidgets.QLabel("Geometry:")
  28. self.object_label.setToolTip(
  29. "Geometry object to be painted. "
  30. )
  31. e_lab_0 = QtWidgets.QLabel('')
  32. form_layout.addRow(self.object_label, self.object_combo)
  33. form_layout.addRow(e_lab_0)
  34. #### Tools ####
  35. self.tools_table_label = QtWidgets.QLabel('<b>Tools Table</b>')
  36. self.tools_table_label.setToolTip(
  37. "Tools pool from which the algorithm\n"
  38. "will pick the ones used for painting."
  39. )
  40. self.tools_box.addWidget(self.tools_table_label)
  41. self.tools_table = FCTable()
  42. self.tools_box.addWidget(self.tools_table)
  43. self.tools_table.setColumnCount(4)
  44. self.tools_table.setHorizontalHeaderLabels(['#', 'Diameter', 'TT', ''])
  45. self.tools_table.setColumnHidden(3, True)
  46. # self.tools_table.setSortingEnabled(False)
  47. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  48. self.tools_table.horizontalHeaderItem(0).setToolTip(
  49. "This is the Tool Number.\n"
  50. "Painting will start with the tool with the biggest diameter,\n"
  51. "continuing until there are no more tools.\n"
  52. "Only tools that create painting geometry will still be present\n"
  53. "in the resulting geometry. This is because with some tools\n"
  54. "this function will not be able to create painting geometry."
  55. )
  56. self.tools_table.horizontalHeaderItem(1).setToolTip(
  57. "Tool Diameter. It's value (in current FlatCAM units) \n"
  58. "is the cut width into the material.")
  59. self.tools_table.horizontalHeaderItem(2).setToolTip(
  60. "The Tool Type (TT) can be:<BR>"
  61. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  62. "the cut width in material is exactly the tool diameter.<BR>"
  63. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  64. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  65. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  66. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  67. "as the cut width into material will be equal with the value in the Tool Diameter "
  68. "column of this table.<BR>"
  69. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  70. "in the resulting geometry as Isolation.")
  71. self.empty_label = QtWidgets.QLabel('')
  72. self.tools_box.addWidget(self.empty_label)
  73. #### Add a new Tool ####
  74. hlay = QtWidgets.QHBoxLayout()
  75. self.tools_box.addLayout(hlay)
  76. self.addtool_entry_lbl = QtWidgets.QLabel('<b>Tool Dia:</b>')
  77. self.addtool_entry_lbl.setToolTip(
  78. "Diameter for the new tool."
  79. )
  80. self.addtool_entry = FloatEntry()
  81. # hlay.addWidget(self.addtool_label)
  82. # hlay.addStretch()
  83. hlay.addWidget(self.addtool_entry_lbl)
  84. hlay.addWidget(self.addtool_entry)
  85. grid2 = QtWidgets.QGridLayout()
  86. self.tools_box.addLayout(grid2)
  87. self.addtool_btn = QtWidgets.QPushButton('Add')
  88. self.addtool_btn.setToolTip(
  89. "Add a new tool to the Tool Table\n"
  90. "with the diameter specified above."
  91. )
  92. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  93. # self.copytool_btn.setToolTip(
  94. # "Copy a selection of tools in the Tool Table\n"
  95. # "by first selecting a row in the Tool Table."
  96. # )
  97. self.deltool_btn = QtWidgets.QPushButton('Delete')
  98. self.deltool_btn.setToolTip(
  99. "Delete a selection of tools in the Tool Table\n"
  100. "by first selecting a row(s) in the Tool Table."
  101. )
  102. grid2.addWidget(self.addtool_btn, 0, 0)
  103. # grid2.addWidget(self.copytool_btn, 0, 1)
  104. grid2.addWidget(self.deltool_btn, 0,2)
  105. self.empty_label_0 = QtWidgets.QLabel('')
  106. self.tools_box.addWidget(self.empty_label_0)
  107. grid3 = QtWidgets.QGridLayout()
  108. self.tools_box.addLayout(grid3)
  109. # Overlap
  110. ovlabel = QtWidgets.QLabel('Overlap:')
  111. ovlabel.setToolTip(
  112. "How much (fraction) of the tool width to overlap each tool pass.\n"
  113. "Example:\n"
  114. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  115. "Adjust the value starting with lower values\n"
  116. "and increasing it if areas that should be painted are still \n"
  117. "not painted.\n"
  118. "Lower values = faster processing, faster execution on PCB.\n"
  119. "Higher values = slow processing and slow execution on CNC\n"
  120. "due of too many paths."
  121. )
  122. grid3.addWidget(ovlabel, 1, 0)
  123. self.paintoverlap_entry = LengthEntry()
  124. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  125. # Margin
  126. marginlabel = QtWidgets.QLabel('Margin:')
  127. marginlabel.setToolTip(
  128. "Distance by which to avoid\n"
  129. "the edges of the polygon to\n"
  130. "be painted."
  131. )
  132. grid3.addWidget(marginlabel, 2, 0)
  133. self.paintmargin_entry = LengthEntry()
  134. grid3.addWidget(self.paintmargin_entry, 2, 1)
  135. # Method
  136. methodlabel = QtWidgets.QLabel('Method:')
  137. methodlabel.setToolTip(
  138. "Algorithm for non-copper clearing:<BR>"
  139. "<B>Standard</B>: Fixed step inwards.<BR>"
  140. "<B>Seed-based</B>: Outwards from seed.<BR>"
  141. "<B>Line-based</B>: Parallel lines."
  142. )
  143. grid3.addWidget(methodlabel, 3, 0)
  144. self.paintmethod_combo = RadioSet([
  145. {"label": "Standard", "value": "standard"},
  146. {"label": "Seed-based", "value": "seed"},
  147. {"label": "Straight lines", "value": "lines"}
  148. ], orientation='vertical', stretch=False)
  149. grid3.addWidget(self.paintmethod_combo, 3, 1)
  150. # Connect lines
  151. pathconnectlabel = QtWidgets.QLabel("Connect:")
  152. pathconnectlabel.setToolTip(
  153. "Draw lines between resulting\n"
  154. "segments to minimize tool lifts."
  155. )
  156. grid3.addWidget(pathconnectlabel, 4, 0)
  157. self.pathconnect_cb = FCCheckBox()
  158. grid3.addWidget(self.pathconnect_cb, 4, 1)
  159. contourlabel = QtWidgets.QLabel("Contour:")
  160. contourlabel.setToolTip(
  161. "Cut around the perimeter of the polygon\n"
  162. "to trim rough edges."
  163. )
  164. grid3.addWidget(contourlabel, 5, 0)
  165. self.paintcontour_cb = FCCheckBox()
  166. grid3.addWidget(self.paintcontour_cb, 5, 1)
  167. restlabel = QtWidgets.QLabel("Rest M.:")
  168. restlabel.setToolTip(
  169. "If checked, use 'rest machining'.\n"
  170. "Basically it will clear copper outside PCB features,\n"
  171. "using the biggest tool and continue with the next tools,\n"
  172. "from bigger to smaller, to clear areas of copper that\n"
  173. "could not be cleared by previous tool, until there is\n"
  174. "no more copper to clear or there are no more tools.\n\n"
  175. "If not checked, use the standard algorithm."
  176. )
  177. grid3.addWidget(restlabel, 6, 0)
  178. self.rest_cb = FCCheckBox()
  179. grid3.addWidget(self.rest_cb, 6, 1)
  180. # Polygon selection
  181. selectlabel = QtWidgets.QLabel('Selection:')
  182. selectlabel.setToolTip(
  183. "How to select the polygons to paint.<BR>"
  184. "Options:<BR>"
  185. "- <B>Single</B>: left mouse click on the polygon to be painted.<BR>"
  186. "- <B>All</B>: paint all polygons."
  187. )
  188. grid3.addWidget(selectlabel, 7, 0)
  189. # grid3 = QtWidgets.QGridLayout()
  190. self.selectmethod_combo = RadioSet([
  191. {"label": "Single", "value": "single"},
  192. {"label": "All", "value": "all"},
  193. # {"label": "Rectangle", "value": "rectangle"}
  194. ])
  195. grid3.addWidget(self.selectmethod_combo, 7, 1)
  196. # GO Button
  197. self.generate_paint_button = QtWidgets.QPushButton('Create Paint Geometry')
  198. self.generate_paint_button.setToolTip(
  199. "After clicking here, click inside<BR>"
  200. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  201. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  202. "A new Geometry object with the tool<BR>"
  203. "paths will be created."
  204. )
  205. self.tools_box.addWidget(self.generate_paint_button)
  206. self.tools_box.addStretch()
  207. self.obj_name = ""
  208. self.paint_obj = None
  209. self.units = ''
  210. self.paint_tools = {}
  211. self.tooluid = 0
  212. # store here the default data for Geometry Data
  213. self.default_data = {}
  214. self.default_data.update({
  215. "name": '_paint',
  216. "plot": self.app.defaults["geometry_plot"],
  217. "tooldia": self.app.defaults["geometry_painttooldia"],
  218. "cutz": self.app.defaults["geometry_cutz"],
  219. "vtipdia": 0.1,
  220. "vtipangle": 30,
  221. "travelz": self.app.defaults["geometry_travelz"],
  222. "feedrate": self.app.defaults["geometry_feedrate"],
  223. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  224. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  225. "dwell": self.app.defaults["geometry_dwell"],
  226. "dwelltime": self.app.defaults["geometry_dwelltime"],
  227. "multidepth": self.app.defaults["geometry_multidepth"],
  228. "ppname_g": self.app.defaults["geometry_ppname_g"],
  229. "depthperpass": self.app.defaults["geometry_depthperpass"],
  230. "extracut": self.app.defaults["geometry_extracut"],
  231. "toolchange": self.app.defaults["geometry_toolchange"],
  232. "toolchangez": self.app.defaults["geometry_toolchangez"],
  233. "endz": self.app.defaults["geometry_endz"],
  234. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  235. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  236. "startz": self.app.defaults["geometry_startz"],
  237. "paintmargin": self.app.defaults["geometry_paintmargin"],
  238. "paintmethod": self.app.defaults["geometry_paintmethod"],
  239. "selectmethod": self.app.defaults["geometry_selectmethod"],
  240. "pathconnect": self.app.defaults["geometry_pathconnect"],
  241. "paintcontour": self.app.defaults["geometry_paintcontour"],
  242. "paintoverlap": self.app.defaults["geometry_paintoverlap"]
  243. })
  244. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  245. ## Signals
  246. self.addtool_btn.clicked.connect(self.on_tool_add)
  247. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  248. self.tools_table.itemChanged.connect(self.on_tool_edit)
  249. self.deltool_btn.clicked.connect(self.on_tool_delete)
  250. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  251. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  252. def install(self, icon=None, separator=None, **kwargs):
  253. FlatCAMTool.install(self, icon, separator, **kwargs)
  254. def run(self):
  255. FlatCAMTool.run(self)
  256. self.tools_frame.show()
  257. self.set_ui()
  258. self.app.ui.notebook.setTabText(2, "Paint Tool")
  259. def on_radio_selection(self):
  260. if self.selectmethod_combo.get_value() == 'single':
  261. # disable rest-machining for single polygon painting
  262. self.rest_cb.set_value(False)
  263. self.rest_cb.setDisabled(True)
  264. # delete all tools except first row / tool for single polygon painting
  265. list_to_del = list(range(1, self.tools_table.rowCount()))
  266. if list_to_del:
  267. self.on_tool_delete(rows_to_delete=list_to_del)
  268. # disable addTool and delTool
  269. self.addtool_entry.setDisabled(True)
  270. self.addtool_btn.setDisabled(True)
  271. self.deltool_btn.setDisabled(True)
  272. else:
  273. self.rest_cb.setDisabled(False)
  274. self.addtool_entry.setDisabled(False)
  275. self.addtool_btn.setDisabled(False)
  276. self.deltool_btn.setDisabled(False)
  277. def set_ui(self):
  278. ## Init the GUI interface
  279. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  280. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  281. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  282. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  283. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  284. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  285. # updated units
  286. self.units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  287. if self.units == "IN":
  288. self.addtool_entry.set_value(0.039)
  289. else:
  290. self.addtool_entry.set_value(1)
  291. self.tools_table.setupContextMenu()
  292. self.tools_table.addContextMenu(
  293. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  294. self.tools_table.addContextMenu(
  295. "Delete", lambda:
  296. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  297. # set the working variables to a known state
  298. self.paint_tools.clear()
  299. self.tooluid = 0
  300. self.default_data.clear()
  301. self.default_data.update({
  302. "name": '_paint',
  303. "plot": self.app.defaults["geometry_plot"],
  304. "tooldia": self.app.defaults["geometry_painttooldia"],
  305. "cutz": self.app.defaults["geometry_cutz"],
  306. "vtipdia": 0.1,
  307. "vtipangle": 30,
  308. "travelz": self.app.defaults["geometry_travelz"],
  309. "feedrate": self.app.defaults["geometry_feedrate"],
  310. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  311. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  312. "dwell": self.app.defaults["geometry_dwell"],
  313. "dwelltime": self.app.defaults["geometry_dwelltime"],
  314. "multidepth": self.app.defaults["geometry_multidepth"],
  315. "ppname_g": self.app.defaults["geometry_ppname_g"],
  316. "depthperpass": self.app.defaults["geometry_depthperpass"],
  317. "extracut": self.app.defaults["geometry_extracut"],
  318. "toolchange": self.app.defaults["geometry_toolchange"],
  319. "toolchangez": self.app.defaults["geometry_toolchangez"],
  320. "endz": self.app.defaults["geometry_endz"],
  321. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  322. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  323. "startz": self.app.defaults["geometry_startz"],
  324. "paintmargin": self.app.defaults["geometry_paintmargin"],
  325. "paintmethod": self.app.defaults["geometry_paintmethod"],
  326. "selectmethod": self.app.defaults["geometry_selectmethod"],
  327. "pathconnect": self.app.defaults["geometry_pathconnect"],
  328. "paintcontour": self.app.defaults["geometry_paintcontour"],
  329. "paintoverlap": self.app.defaults["geometry_paintoverlap"]
  330. })
  331. # call on self.on_tool_add() counts as an call to self.build_ui()
  332. # through this, we add a initial row / tool in the tool_table
  333. self.on_tool_add(self.app.defaults["geometry_painttooldia"], muted=True)
  334. def build_ui(self):
  335. try:
  336. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  337. self.tools_table.itemChanged.disconnect()
  338. except:
  339. pass
  340. # updated units
  341. self.units = self.app.general_options_form.general_group.units_radio.get_value().upper()
  342. sorted_tools = []
  343. for k, v in self.paint_tools.items():
  344. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  345. sorted_tools.sort()
  346. n = len(sorted_tools)
  347. self.tools_table.setRowCount(n)
  348. tool_id = 0
  349. for tool_sorted in sorted_tools:
  350. for tooluid_key, tooluid_value in self.paint_tools.items():
  351. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  352. tool_id += 1
  353. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  354. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  355. row_no = tool_id - 1
  356. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  357. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  358. # There are no drill bits in MM with more than 3 decimals diameter
  359. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  360. if self.units == 'MM':
  361. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  362. else:
  363. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  364. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  365. tool_type_item = QtWidgets.QComboBox()
  366. for item in self.tool_type_item_options:
  367. tool_type_item.addItem(item)
  368. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  369. idx = tool_type_item.findText(tooluid_value['tool_type'])
  370. tool_type_item.setCurrentIndex(idx)
  371. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  372. self.tools_table.setItem(row_no, 1, dia) # Diameter
  373. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  374. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  375. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  376. # make the diameter column editable
  377. for row in range(tool_id):
  378. self.tools_table.item(row, 1).setFlags(
  379. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  380. # all the tools are selected by default
  381. self.tools_table.selectColumn(0)
  382. #
  383. self.tools_table.resizeColumnsToContents()
  384. self.tools_table.resizeRowsToContents()
  385. vertical_header = self.tools_table.verticalHeader()
  386. vertical_header.hide()
  387. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  388. horizontal_header = self.tools_table.horizontalHeader()
  389. horizontal_header.setMinimumSectionSize(10)
  390. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  391. horizontal_header.resizeSection(0, 20)
  392. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  393. # self.tools_table.setSortingEnabled(True)
  394. # sort by tool diameter
  395. # self.tools_table.sortItems(1)
  396. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  397. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  398. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  399. self.tools_table.itemChanged.connect(self.on_tool_edit)
  400. def on_tool_add(self, dia=None, muted=None):
  401. try:
  402. self.tools_table.itemChanged.disconnect()
  403. except:
  404. pass
  405. if dia:
  406. tool_dia = dia
  407. else:
  408. tool_dia = self.addtool_entry.get_value()
  409. if tool_dia is None:
  410. self.build_ui()
  411. self.app.inform.emit("[warning_notcl] Please enter a tool diameter to add, in Float format.")
  412. return
  413. # construct a list of all 'tooluid' in the self.tools
  414. tool_uid_list = []
  415. for tooluid_key in self.paint_tools:
  416. tool_uid_item = int(tooluid_key)
  417. tool_uid_list.append(tool_uid_item)
  418. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  419. if not tool_uid_list:
  420. max_uid = 0
  421. else:
  422. max_uid = max(tool_uid_list)
  423. self.tooluid = int(max_uid + 1)
  424. tool_dias = []
  425. for k, v in self.paint_tools.items():
  426. for tool_v in v.keys():
  427. if tool_v == 'tooldia':
  428. tool_dias.append(float('%.4f' % v[tool_v]))
  429. if float('%.4f' % tool_dia) in tool_dias:
  430. if muted is None:
  431. self.app.inform.emit("[warning_notcl]Adding tool cancelled. Tool already in Tool Table.")
  432. self.tools_table.itemChanged.connect(self.on_tool_edit)
  433. return
  434. else:
  435. if muted is None:
  436. self.app.inform.emit("[success] New tool added to Tool Table.")
  437. self.paint_tools.update({
  438. int(self.tooluid): {
  439. 'tooldia': float('%.4f' % tool_dia),
  440. 'offset': 'Path',
  441. 'offset_value': 0.0,
  442. 'type': 'Iso',
  443. 'tool_type': 'V',
  444. 'data': dict(self.default_data),
  445. 'solid_geometry': []
  446. }
  447. })
  448. self.build_ui()
  449. def on_tool_edit(self):
  450. try:
  451. self.tools_table.itemChanged.disconnect()
  452. except:
  453. pass
  454. tool_dias = []
  455. for k, v in self.paint_tools.items():
  456. for tool_v in v.keys():
  457. if tool_v == 'tooldia':
  458. tool_dias.append(float('%.4f' % v[tool_v]))
  459. for row in range(self.tools_table.rowCount()):
  460. new_tool_dia = float(self.tools_table.item(row, 1).text())
  461. tooluid = int(self.tools_table.item(row, 3).text())
  462. # identify the tool that was edited and get it's tooluid
  463. if new_tool_dia not in tool_dias:
  464. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  465. self.app.inform.emit("[success] Tool from Tool Table was edited.")
  466. self.build_ui()
  467. return
  468. else:
  469. # identify the old tool_dia and restore the text in tool table
  470. for k, v in self.paint_tools.items():
  471. if k == tooluid:
  472. old_tool_dia = v['tooldia']
  473. break
  474. restore_dia_item = self.tools_table.item(row, 1)
  475. restore_dia_item.setText(str(old_tool_dia))
  476. self.app.inform.emit("[warning_notcl] Edit cancelled. New diameter value is already in the Tool Table.")
  477. self.build_ui()
  478. # def on_tool_copy(self, all=None):
  479. # try:
  480. # self.tools_table.itemChanged.disconnect()
  481. # except:
  482. # pass
  483. #
  484. # # find the tool_uid maximum value in the self.tools
  485. # uid_list = []
  486. # for key in self.paint_tools:
  487. # uid_list.append(int(key))
  488. # try:
  489. # max_uid = max(uid_list, key=int)
  490. # except ValueError:
  491. # max_uid = 0
  492. #
  493. # if all is None:
  494. # if self.tools_table.selectedItems():
  495. # for current_row in self.tools_table.selectedItems():
  496. # # sometime the header get selected and it has row number -1
  497. # # we don't want to do anything with the header :)
  498. # if current_row.row() < 0:
  499. # continue
  500. # try:
  501. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  502. # max_uid += 1
  503. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  504. # for td in self.paint_tools:
  505. # print("COPIED", self.paint_tools[td])
  506. # self.build_ui()
  507. # except AttributeError:
  508. # self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  509. # self.build_ui()
  510. # return
  511. # except Exception as e:
  512. # log.debug("on_tool_copy() --> " + str(e))
  513. # # deselect the table
  514. # # self.ui.geo_tools_table.clearSelection()
  515. # else:
  516. # self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  517. # self.build_ui()
  518. # return
  519. # else:
  520. # # we copy all tools in geo_tools_table
  521. # try:
  522. # temp_tools = dict(self.paint_tools)
  523. # max_uid += 1
  524. # for tooluid in temp_tools:
  525. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  526. # temp_tools.clear()
  527. # self.build_ui()
  528. # except Exception as e:
  529. # log.debug("on_tool_copy() --> " + str(e))
  530. #
  531. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  532. def on_tool_delete(self, rows_to_delete=None, all=None):
  533. try:
  534. self.tools_table.itemChanged.disconnect()
  535. except:
  536. pass
  537. deleted_tools_list = []
  538. if all:
  539. self.paint_tools.clear()
  540. self.build_ui()
  541. return
  542. if rows_to_delete:
  543. try:
  544. for row in rows_to_delete:
  545. tooluid_del = int(self.tools_table.item(row, 3).text())
  546. deleted_tools_list.append(tooluid_del)
  547. except TypeError:
  548. deleted_tools_list.append(rows_to_delete)
  549. for t in deleted_tools_list:
  550. self.paint_tools.pop(t, None)
  551. self.build_ui()
  552. return
  553. try:
  554. if self.tools_table.selectedItems():
  555. for row_sel in self.tools_table.selectedItems():
  556. row = row_sel.row()
  557. if row < 0:
  558. continue
  559. tooluid_del = int(self.tools_table.item(row, 3).text())
  560. deleted_tools_list.append(tooluid_del)
  561. for t in deleted_tools_list:
  562. self.paint_tools.pop(t, None)
  563. except AttributeError:
  564. self.app.inform.emit("[warning_notcl]Delete failed. Select a tool to delete.")
  565. return
  566. except Exception as e:
  567. log.debug(str(e))
  568. self.app.inform.emit("[success] Tool(s) deleted from Tool Table.")
  569. self.build_ui()
  570. def on_paint_button_click(self):
  571. self.app.report_usage("geometry_on_paint_button")
  572. self.app.inform.emit("[warning_notcl]Click inside the desired polygon.")
  573. overlap = self.paintoverlap_entry.get_value()
  574. connect = self.pathconnect_cb.get_value()
  575. contour = self.paintcontour_cb.get_value()
  576. select_method = self.selectmethod_combo.get_value()
  577. self.obj_name = self.object_combo.currentText()
  578. # Get source object.
  579. try:
  580. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  581. except:
  582. self.app.inform.emit("[error_notcl]Could not retrieve object: %s" % self.obj_name)
  583. return
  584. if self.paint_obj is None:
  585. self.app.inform.emit("[error_notcl]Object not found: %s" % self.paint_obj)
  586. return
  587. o_name = '%s_multitool_paint' % (self.obj_name)
  588. if select_method == "all":
  589. self.paint_poly_all(self.paint_obj,
  590. outname=o_name,
  591. overlap=overlap,
  592. connect=connect,
  593. contour=contour)
  594. if select_method == "single":
  595. self.app.inform.emit("[warning_notcl]Click inside the desired polygon.")
  596. # use the first tool in the tool table; get the diameter
  597. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  598. # To be called after clicking on the plot.
  599. def doit(event):
  600. # do paint single only for left mouse clicks
  601. if event.button == 1:
  602. self.app.inform.emit("Painting polygon...")
  603. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  604. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  605. self.paint_poly(self.paint_obj,
  606. inside_pt=[pos[0], pos[1]],
  607. tooldia=tooldia,
  608. overlap=overlap,
  609. connect=connect,
  610. contour=contour)
  611. self.app.plotcanvas.vis_connect('mouse_press', doit)
  612. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  613. outname=None, connect=True,
  614. contour=True):
  615. """
  616. Paints a polygon selected by clicking on its interior.
  617. Note:
  618. * The margin is taken directly from the form.
  619. :param inside_pt: [x, y]
  620. :param tooldia: Diameter of the painting tool
  621. :param overlap: Overlap of the tool between passes.
  622. :param outname: Name of the resulting Geometry Object.
  623. :param connect: Connect lines to avoid tool lifts.
  624. :param contour: Paint around the edges.
  625. :return: None
  626. """
  627. # Which polygon.
  628. # poly = find_polygon(self.solid_geometry, inside_pt)
  629. poly = obj.find_polygon(inside_pt)
  630. paint_method = self.paintmethod_combo.get_value()
  631. paint_margin = self.paintmargin_entry.get_value()
  632. # No polygon?
  633. if poly is None:
  634. self.app.log.warning('No polygon found.')
  635. self.app.inform.emit('[warning] No polygon found.')
  636. return
  637. proc = self.app.proc_container.new("Painting polygon.")
  638. name = outname if outname else self.obj_name + "_paint"
  639. # Initializes the new geometry object
  640. def gen_paintarea(geo_obj, app_obj):
  641. assert isinstance(geo_obj, FlatCAMGeometry), \
  642. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  643. #assert isinstance(app_obj, App)
  644. geo_obj.solid_geometry = []
  645. try:
  646. poly_buf = poly.buffer(-paint_margin)
  647. if paint_method == "seed":
  648. # Type(cp) == FlatCAMRTreeStorage | None
  649. cp = self.clear_polygon2(poly_buf,
  650. tooldia=tooldia,
  651. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  652. overlap=overlap,
  653. contour=contour,
  654. connect=connect)
  655. elif paint_method == "lines":
  656. # Type(cp) == FlatCAMRTreeStorage | None
  657. cp = self.clear_polygon3(poly_buf,
  658. tooldia=tooldia,
  659. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  660. overlap=overlap,
  661. contour=contour,
  662. connect=connect)
  663. else:
  664. # Type(cp) == FlatCAMRTreeStorage | None
  665. cp = self.clear_polygon(poly_buf,
  666. tooldia=tooldia,
  667. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  668. overlap=overlap,
  669. contour=contour,
  670. connect=connect)
  671. if cp is not None:
  672. geo_obj.solid_geometry += list(cp.get_objects())
  673. else:
  674. self.app.inform.emit('[error_notcl] Geometry could not be painted completely')
  675. return
  676. except Exception as e:
  677. log.debug("Could not Paint the polygons. %s" % str(e))
  678. self.app.inform.emit(
  679. "[error] Could not do Paint. Try a different combination of parameters. "
  680. "Or a different strategy of paint\n%s" % str(e))
  681. return
  682. if cp is not None:
  683. geo_obj.solid_geometry = list(cp.get_objects())
  684. geo_obj.options["cnctooldia"] = tooldia
  685. # this turn on the FlatCAMCNCJob plot for multiple tools
  686. geo_obj.multigeo = False
  687. geo_obj.multitool = True
  688. current_uid = int(self.tools_table.item(0, 3).text())
  689. for k, v in self.paint_tools.items():
  690. if k == current_uid:
  691. v['data']['name'] = name
  692. geo_obj.tools = dict(self.paint_tools)
  693. # Experimental...
  694. # print("Indexing...", end=' ')
  695. # geo_obj.make_index()
  696. # if errors == 0:
  697. # print("[success] Paint single polygon Done")
  698. # self.app.inform.emit("[success] Paint single polygon Done")
  699. # else:
  700. # print("[WARNING] Paint single polygon done with errors")
  701. # self.app.inform.emit("[warning] Paint single polygon done with errors. "
  702. # "%d area(s) could not be painted.\n"
  703. # "Use different paint parameters or edit the paint geometry and correct"
  704. # "the issue."
  705. # % errors)
  706. def job_thread(app_obj):
  707. try:
  708. app_obj.new_object("geometry", name, gen_paintarea)
  709. except Exception as e:
  710. proc.done()
  711. self.app.inform.emit('[error_notcl] PaintTool.paint_poly() --> %s' % str(e))
  712. return
  713. proc.done()
  714. # focus on Selected Tab
  715. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  716. self.app.inform.emit("Polygon Paint started ...")
  717. # Promise object with the new name
  718. self.app.collection.promise(name)
  719. # Background
  720. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  721. def paint_poly_all(self, obj, overlap, outname=None,
  722. connect=True, contour=True):
  723. """
  724. Paints all polygons in this object.
  725. :param tooldia:
  726. :param overlap:
  727. :param outname:
  728. :param connect: Connect lines to avoid tool lifts.
  729. :param contour: Paint around the edges.
  730. :return:
  731. """
  732. paint_method = self.paintmethod_combo.get_value()
  733. paint_margin = self.paintmargin_entry.get_value()
  734. proc = self.app.proc_container.new("Painting polygon.")
  735. name = outname if outname else self.obj_name + "_paint"
  736. over = overlap
  737. conn = connect
  738. cont = contour
  739. # This is a recursive generator of individual Polygons.
  740. # Note: Double check correct implementation. Might exit
  741. # early if it finds something that is not a Polygon?
  742. # def recurse(geo):
  743. # try:
  744. # for subg in geo:
  745. # for subsubg in recurse(subg):
  746. # yield subsubg
  747. # except TypeError:
  748. # if isinstance(geo, Polygon):
  749. # yield geo
  750. #
  751. # raise StopIteration
  752. def recurse(geometry, reset=True):
  753. """
  754. Creates a list of non-iterable linear geometry objects.
  755. Results are placed in self.flat_geometry
  756. :param geometry: Shapely type or list or list of list of such.
  757. :param reset: Clears the contents of self.flat_geometry.
  758. """
  759. if geometry is None:
  760. return
  761. if reset:
  762. self.flat_geometry = []
  763. ## If iterable, expand recursively.
  764. try:
  765. for geo in geometry:
  766. if geo is not None:
  767. recurse(geometry=geo, reset=False)
  768. ## Not iterable, do the actual indexing and add.
  769. except TypeError:
  770. self.flat_geometry.append(geometry)
  771. return self.flat_geometry
  772. # Initializes the new geometry object
  773. def gen_paintarea(geo_obj, app_obj):
  774. assert isinstance(geo_obj, FlatCAMGeometry), \
  775. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  776. sorted_tools = []
  777. for row in range(self.tools_table.rowCount()):
  778. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  779. sorted_tools.sort(reverse=True)
  780. total_geometry = []
  781. current_uid = int(1)
  782. geo_obj.solid_geometry = []
  783. for tool_dia in sorted_tools:
  784. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  785. for k, v in self.paint_tools.items():
  786. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  787. current_uid = int(k)
  788. break
  789. for geo in recurse(obj.solid_geometry):
  790. try:
  791. if not isinstance(geo, Polygon):
  792. geo = Polygon(geo)
  793. poly_buf = geo.buffer(-paint_margin)
  794. if paint_method == "seed":
  795. # Type(cp) == FlatCAMRTreeStorage | None
  796. cp = self.clear_polygon2(poly_buf,
  797. tooldia=tool_dia,
  798. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  799. overlap=over,
  800. contour=cont,
  801. connect=conn)
  802. elif paint_method == "lines":
  803. # Type(cp) == FlatCAMRTreeStorage | None
  804. cp = self.clear_polygon3(poly_buf,
  805. tooldia=tool_dia,
  806. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  807. overlap=over,
  808. contour=cont,
  809. connect=conn)
  810. else:
  811. # Type(cp) == FlatCAMRTreeStorage | None
  812. cp = self.clear_polygon(poly_buf,
  813. tooldia=tool_dia,
  814. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  815. overlap=over,
  816. contour=cont,
  817. connect=conn)
  818. if cp is not None:
  819. total_geometry += list(cp.get_objects())
  820. except Exception as e:
  821. log.debug("Could not Paint the polygons. %s" % str(e))
  822. self.app.inform.emit(
  823. "[error] Could not do Paint All. Try a different combination of parameters. "
  824. "Or a different Method of paint\n%s" % str(e))
  825. return
  826. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  827. # temporary list that stored that solid_geometry
  828. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  829. self.paint_tools[current_uid]['data']['name'] = name
  830. total_geometry[:] = []
  831. geo_obj.options["cnctooldia"] = tool_dia
  832. # this turn on the FlatCAMCNCJob plot for multiple tools
  833. geo_obj.multigeo = True
  834. geo_obj.multitool = True
  835. geo_obj.tools.clear()
  836. geo_obj.tools = dict(self.paint_tools)
  837. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  838. has_solid_geo = 0
  839. for tooluid in geo_obj.tools:
  840. if geo_obj.tools[tooluid]['solid_geometry']:
  841. has_solid_geo += 1
  842. if has_solid_geo == 0:
  843. self.app.inform.emit("[error] There is no Painting Geometry in the file.\n"
  844. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  845. "Change the painting parameters and try again.")
  846. return
  847. # Experimental...
  848. # print("Indexing...", end=' ')
  849. # geo_obj.make_index()
  850. self.app.inform.emit("[success] Paint All Done.")
  851. # Initializes the new geometry object
  852. def gen_paintarea_rest_machining(geo_obj, app_obj):
  853. assert isinstance(geo_obj, FlatCAMGeometry), \
  854. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  855. sorted_tools = []
  856. for row in range(self.tools_table.rowCount()):
  857. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  858. sorted_tools.sort(reverse=True)
  859. cleared_geo = []
  860. current_uid = int(1)
  861. geo_obj.solid_geometry = []
  862. for tool_dia in sorted_tools:
  863. for geo in recurse(obj.solid_geometry):
  864. try:
  865. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  866. poly_buf = geo.buffer(-paint_margin)
  867. if paint_method == "standard":
  868. # Type(cp) == FlatCAMRTreeStorage | None
  869. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  870. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  871. overlap=over, contour=cont, connect=conn)
  872. elif paint_method == "seed":
  873. # Type(cp) == FlatCAMRTreeStorage | None
  874. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  875. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  876. overlap=over, contour=cont, connect=conn)
  877. elif paint_method == "lines":
  878. # Type(cp) == FlatCAMRTreeStorage | None
  879. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  880. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  881. overlap=over, contour=cont, connect=conn)
  882. if cp is not None:
  883. cleared_geo += list(cp.get_objects())
  884. except Exception as e:
  885. log.debug("Could not Paint the polygons. %s" % str(e))
  886. self.app.inform.emit(
  887. "[error] Could not do Paint All. Try a different combination of parameters. "
  888. "Or a different Method of paint\n%s" % str(e))
  889. return
  890. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  891. for k, v in self.paint_tools.items():
  892. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  893. current_uid = int(k)
  894. break
  895. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  896. # temporary list that stored that solid_geometry
  897. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  898. self.paint_tools[current_uid]['data']['name'] = name
  899. cleared_geo[:] = []
  900. geo_obj.options["cnctooldia"] = tool_dia
  901. # this turn on the FlatCAMCNCJob plot for multiple tools
  902. geo_obj.multigeo = True
  903. geo_obj.multitool = True
  904. geo_obj.tools.clear()
  905. geo_obj.tools = dict(self.paint_tools)
  906. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  907. has_solid_geo = 0
  908. for tooluid in geo_obj.tools:
  909. if geo_obj.tools[tooluid]['solid_geometry']:
  910. has_solid_geo += 1
  911. if has_solid_geo == 0:
  912. self.app.inform.emit("[error_notcl] There is no Painting Geometry in the file.\n"
  913. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  914. "Change the painting parameters and try again.")
  915. return
  916. # Experimental...
  917. # print("Indexing...", end=' ')
  918. # geo_obj.make_index()
  919. self.app.inform.emit("[success] Paint All with Rest-Machining Done.")
  920. def job_thread(app_obj):
  921. try:
  922. if self.rest_cb.isChecked():
  923. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  924. else:
  925. app_obj.new_object("geometry", name, gen_paintarea)
  926. except Exception as e:
  927. proc.done()
  928. traceback.print_stack()
  929. return
  930. proc.done()
  931. # focus on Selected Tab
  932. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  933. self.app.inform.emit("Polygon Paint started ...")
  934. # Promise object with the new name
  935. self.app.collection.promise(name)
  936. # Background
  937. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})