ToolPaint.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. fcTranslate.apply_language('strings')
  14. import builtins
  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 = FCEntry()
  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:'))
  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>All</B>: paint all polygons.")
  207. )
  208. grid3.addWidget(selectlabel, 7, 0)
  209. # grid3 = QtWidgets.QGridLayout()
  210. self.selectmethod_combo = RadioSet([
  211. {"label": "Single", "value": "single"},
  212. {"label": "All", "value": "all"},
  213. # {"label": "Rectangle", "value": "rectangle"}
  214. ])
  215. grid3.addWidget(self.selectmethod_combo, 7, 1)
  216. # GO Button
  217. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  218. self.generate_paint_button.setToolTip(
  219. _("After clicking here, click inside<BR>"
  220. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  221. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  222. "A new Geometry object with the tool<BR>"
  223. "paths will be created.")
  224. )
  225. self.tools_box.addWidget(self.generate_paint_button)
  226. self.tools_box.addStretch()
  227. self.obj_name = ""
  228. self.paint_obj = None
  229. self.units = ''
  230. self.paint_tools = {}
  231. self.tooluid = 0
  232. # store here the default data for Geometry Data
  233. self.default_data = {}
  234. self.default_data.update({
  235. "name": '_paint',
  236. "plot": self.app.defaults["geometry_plot"],
  237. "cutz": self.app.defaults["geometry_cutz"],
  238. "vtipdia": 0.1,
  239. "vtipangle": 30,
  240. "travelz": self.app.defaults["geometry_travelz"],
  241. "feedrate": self.app.defaults["geometry_feedrate"],
  242. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  243. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  244. "dwell": self.app.defaults["geometry_dwell"],
  245. "dwelltime": self.app.defaults["geometry_dwelltime"],
  246. "multidepth": self.app.defaults["geometry_multidepth"],
  247. "ppname_g": self.app.defaults["geometry_ppname_g"],
  248. "depthperpass": self.app.defaults["geometry_depthperpass"],
  249. "extracut": self.app.defaults["geometry_extracut"],
  250. "toolchange": self.app.defaults["geometry_toolchange"],
  251. "toolchangez": self.app.defaults["geometry_toolchangez"],
  252. "endz": self.app.defaults["geometry_endz"],
  253. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  254. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  255. "startz": self.app.defaults["geometry_startz"],
  256. "tooldia": self.app.defaults["tools_painttooldia"],
  257. "paintmargin": self.app.defaults["tools_paintmargin"],
  258. "paintmethod": self.app.defaults["tools_paintmethod"],
  259. "selectmethod": self.app.defaults["tools_selectmethod"],
  260. "pathconnect": self.app.defaults["tools_pathconnect"],
  261. "paintcontour": self.app.defaults["tools_paintcontour"],
  262. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  263. })
  264. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  265. ## Signals
  266. self.addtool_btn.clicked.connect(self.on_tool_add)
  267. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  268. self.tools_table.itemChanged.connect(self.on_tool_edit)
  269. self.deltool_btn.clicked.connect(self.on_tool_delete)
  270. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  271. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  272. def install(self, icon=None, separator=None, **kwargs):
  273. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  274. def run(self, toggle=True):
  275. self.app.report_usage("ToolPaint()")
  276. if toggle:
  277. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  278. if self.app.ui.splitter.sizes()[0] == 0:
  279. self.app.ui.splitter.setSizes([1, 1])
  280. else:
  281. try:
  282. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  283. self.app.ui.splitter.setSizes([0, 1])
  284. except AttributeError:
  285. pass
  286. else:
  287. if self.app.ui.splitter.sizes()[0] == 0:
  288. self.app.ui.splitter.setSizes([1, 1])
  289. FlatCAMTool.run(self)
  290. self.set_tool_ui()
  291. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  292. def on_radio_selection(self):
  293. if self.selectmethod_combo.get_value() == 'single':
  294. # disable rest-machining for single polygon painting
  295. self.rest_cb.set_value(False)
  296. self.rest_cb.setDisabled(True)
  297. # delete all tools except first row / tool for single polygon painting
  298. list_to_del = list(range(1, self.tools_table.rowCount()))
  299. if list_to_del:
  300. self.on_tool_delete(rows_to_delete=list_to_del)
  301. # disable addTool and delTool
  302. self.addtool_entry.setDisabled(True)
  303. self.addtool_btn.setDisabled(True)
  304. self.deltool_btn.setDisabled(True)
  305. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  306. else:
  307. self.rest_cb.setDisabled(False)
  308. self.addtool_entry.setDisabled(False)
  309. self.addtool_btn.setDisabled(False)
  310. self.deltool_btn.setDisabled(False)
  311. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  312. def set_tool_ui(self):
  313. self.tools_frame.show()
  314. self.reset_fields()
  315. ## Init the GUI interface
  316. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  317. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  318. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  319. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  320. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  321. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  322. # updated units
  323. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  324. if self.units == "IN":
  325. self.addtool_entry.set_value(0.039)
  326. else:
  327. self.addtool_entry.set_value(1)
  328. self.tools_table.setupContextMenu()
  329. self.tools_table.addContextMenu(
  330. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  331. self.tools_table.addContextMenu(
  332. "Delete", lambda:
  333. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  334. # set the working variables to a known state
  335. self.paint_tools.clear()
  336. self.tooluid = 0
  337. self.default_data.clear()
  338. self.default_data.update({
  339. "name": '_paint',
  340. "plot": self.app.defaults["geometry_plot"],
  341. "cutz": self.app.defaults["geometry_cutz"],
  342. "vtipdia": 0.1,
  343. "vtipangle": 30,
  344. "travelz": self.app.defaults["geometry_travelz"],
  345. "feedrate": self.app.defaults["geometry_feedrate"],
  346. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  347. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  348. "dwell": self.app.defaults["geometry_dwell"],
  349. "dwelltime": self.app.defaults["geometry_dwelltime"],
  350. "multidepth": self.app.defaults["geometry_multidepth"],
  351. "ppname_g": self.app.defaults["geometry_ppname_g"],
  352. "depthperpass": self.app.defaults["geometry_depthperpass"],
  353. "extracut": self.app.defaults["geometry_extracut"],
  354. "toolchange": self.app.defaults["geometry_toolchange"],
  355. "toolchangez": self.app.defaults["geometry_toolchangez"],
  356. "endz": self.app.defaults["geometry_endz"],
  357. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  358. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  359. "startz": self.app.defaults["geometry_startz"],
  360. "tooldia": self.app.defaults["tools_painttooldia"],
  361. "paintmargin": self.app.defaults["tools_paintmargin"],
  362. "paintmethod": self.app.defaults["tools_paintmethod"],
  363. "selectmethod": self.app.defaults["tools_selectmethod"],
  364. "pathconnect": self.app.defaults["tools_pathconnect"],
  365. "paintcontour": self.app.defaults["tools_paintcontour"],
  366. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  367. })
  368. # call on self.on_tool_add() counts as an call to self.build_ui()
  369. # through this, we add a initial row / tool in the tool_table
  370. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  371. # if the Paint Method is "Single" disable the tool table context menu
  372. if self.default_data["selectmethod"] == "single":
  373. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  374. def build_ui(self):
  375. try:
  376. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  377. self.tools_table.itemChanged.disconnect()
  378. except:
  379. pass
  380. # updated units
  381. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  382. sorted_tools = []
  383. for k, v in self.paint_tools.items():
  384. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  385. sorted_tools.sort()
  386. n = len(sorted_tools)
  387. self.tools_table.setRowCount(n)
  388. tool_id = 0
  389. for tool_sorted in sorted_tools:
  390. for tooluid_key, tooluid_value in self.paint_tools.items():
  391. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  392. tool_id += 1
  393. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  394. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  395. row_no = tool_id - 1
  396. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  397. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  398. # There are no drill bits in MM with more than 3 decimals diameter
  399. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  400. if self.units == 'MM':
  401. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  402. else:
  403. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  404. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  405. tool_type_item = QtWidgets.QComboBox()
  406. for item in self.tool_type_item_options:
  407. tool_type_item.addItem(item)
  408. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  409. idx = tool_type_item.findText(tooluid_value['tool_type'])
  410. tool_type_item.setCurrentIndex(idx)
  411. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  412. self.tools_table.setItem(row_no, 1, dia) # Diameter
  413. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  414. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  415. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  416. # make the diameter column editable
  417. for row in range(tool_id):
  418. self.tools_table.item(row, 1).setFlags(
  419. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  420. # all the tools are selected by default
  421. self.tools_table.selectColumn(0)
  422. #
  423. self.tools_table.resizeColumnsToContents()
  424. self.tools_table.resizeRowsToContents()
  425. vertical_header = self.tools_table.verticalHeader()
  426. vertical_header.hide()
  427. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  428. horizontal_header = self.tools_table.horizontalHeader()
  429. horizontal_header.setMinimumSectionSize(10)
  430. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  431. horizontal_header.resizeSection(0, 20)
  432. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  433. # self.tools_table.setSortingEnabled(True)
  434. # sort by tool diameter
  435. # self.tools_table.sortItems(1)
  436. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  437. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  438. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  439. self.tools_table.itemChanged.connect(self.on_tool_edit)
  440. def on_tool_add(self, dia=None, muted=None):
  441. try:
  442. self.tools_table.itemChanged.disconnect()
  443. except:
  444. pass
  445. if dia:
  446. tool_dia = dia
  447. else:
  448. try:
  449. tool_dia = float(self.addtool_entry.get_value())
  450. except ValueError:
  451. # try to convert comma to decimal point. if it's still not working error message and return
  452. try:
  453. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  454. except ValueError:
  455. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  456. "use a number."))
  457. return
  458. if tool_dia is None:
  459. self.build_ui()
  460. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  461. return
  462. # construct a list of all 'tooluid' in the self.tools
  463. tool_uid_list = []
  464. for tooluid_key in self.paint_tools:
  465. tool_uid_item = int(tooluid_key)
  466. tool_uid_list.append(tool_uid_item)
  467. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  468. if not tool_uid_list:
  469. max_uid = 0
  470. else:
  471. max_uid = max(tool_uid_list)
  472. self.tooluid = int(max_uid + 1)
  473. tool_dias = []
  474. for k, v in self.paint_tools.items():
  475. for tool_v in v.keys():
  476. if tool_v == 'tooldia':
  477. tool_dias.append(float('%.4f' % v[tool_v]))
  478. if float('%.4f' % tool_dia) in tool_dias:
  479. if muted is None:
  480. self.app.inform.emit(_("[WARNING_NOTCL]Adding tool cancelled. Tool already in Tool Table."))
  481. self.tools_table.itemChanged.connect(self.on_tool_edit)
  482. return
  483. else:
  484. if muted is None:
  485. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  486. self.paint_tools.update({
  487. int(self.tooluid): {
  488. 'tooldia': float('%.4f' % tool_dia),
  489. 'offset': 'Path',
  490. 'offset_value': 0.0,
  491. 'type': 'Iso',
  492. 'tool_type': 'V',
  493. 'data': dict(self.default_data),
  494. 'solid_geometry': []
  495. }
  496. })
  497. self.build_ui()
  498. def on_tool_edit(self):
  499. try:
  500. self.tools_table.itemChanged.disconnect()
  501. except:
  502. pass
  503. tool_dias = []
  504. for k, v in self.paint_tools.items():
  505. for tool_v in v.keys():
  506. if tool_v == 'tooldia':
  507. tool_dias.append(float('%.4f' % v[tool_v]))
  508. for row in range(self.tools_table.rowCount()):
  509. try:
  510. new_tool_dia = float(self.tools_table.item(row, 1).text())
  511. except ValueError:
  512. # try to convert comma to decimal point. if it's still not working error message and return
  513. try:
  514. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  515. except ValueError:
  516. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  517. "use a number."))
  518. return
  519. tooluid = int(self.tools_table.item(row, 3).text())
  520. # identify the tool that was edited and get it's tooluid
  521. if new_tool_dia not in tool_dias:
  522. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  523. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  524. self.build_ui()
  525. return
  526. else:
  527. # identify the old tool_dia and restore the text in tool table
  528. for k, v in self.paint_tools.items():
  529. if k == tooluid:
  530. old_tool_dia = v['tooldia']
  531. break
  532. restore_dia_item = self.tools_table.item(row, 1)
  533. restore_dia_item.setText(str(old_tool_dia))
  534. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table."))
  535. self.build_ui()
  536. # def on_tool_copy(self, all=None):
  537. # try:
  538. # self.tools_table.itemChanged.disconnect()
  539. # except:
  540. # pass
  541. #
  542. # # find the tool_uid maximum value in the self.tools
  543. # uid_list = []
  544. # for key in self.paint_tools:
  545. # uid_list.append(int(key))
  546. # try:
  547. # max_uid = max(uid_list, key=int)
  548. # except ValueError:
  549. # max_uid = 0
  550. #
  551. # if all is None:
  552. # if self.tools_table.selectedItems():
  553. # for current_row in self.tools_table.selectedItems():
  554. # # sometime the header get selected and it has row number -1
  555. # # we don't want to do anything with the header :)
  556. # if current_row.row() < 0:
  557. # continue
  558. # try:
  559. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  560. # max_uid += 1
  561. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  562. # for td in self.paint_tools:
  563. # print("COPIED", self.paint_tools[td])
  564. # self.build_ui()
  565. # except AttributeError:
  566. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  567. # self.build_ui()
  568. # return
  569. # except Exception as e:
  570. # log.debug("on_tool_copy() --> " + str(e))
  571. # # deselect the table
  572. # # self.ui.geo_tools_table.clearSelection()
  573. # else:
  574. # self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  575. # self.build_ui()
  576. # return
  577. # else:
  578. # # we copy all tools in geo_tools_table
  579. # try:
  580. # temp_tools = dict(self.paint_tools)
  581. # max_uid += 1
  582. # for tooluid in temp_tools:
  583. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  584. # temp_tools.clear()
  585. # self.build_ui()
  586. # except Exception as e:
  587. # log.debug("on_tool_copy() --> " + str(e))
  588. #
  589. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  590. def on_tool_delete(self, rows_to_delete=None, all=None):
  591. try:
  592. self.tools_table.itemChanged.disconnect()
  593. except:
  594. pass
  595. deleted_tools_list = []
  596. if all:
  597. self.paint_tools.clear()
  598. self.build_ui()
  599. return
  600. if rows_to_delete:
  601. try:
  602. for row in rows_to_delete:
  603. tooluid_del = int(self.tools_table.item(row, 3).text())
  604. deleted_tools_list.append(tooluid_del)
  605. except TypeError:
  606. deleted_tools_list.append(rows_to_delete)
  607. for t in deleted_tools_list:
  608. self.paint_tools.pop(t, None)
  609. self.build_ui()
  610. return
  611. try:
  612. if self.tools_table.selectedItems():
  613. for row_sel in self.tools_table.selectedItems():
  614. row = row_sel.row()
  615. if row < 0:
  616. continue
  617. tooluid_del = int(self.tools_table.item(row, 3).text())
  618. deleted_tools_list.append(tooluid_del)
  619. for t in deleted_tools_list:
  620. self.paint_tools.pop(t, None)
  621. except AttributeError:
  622. self.app.inform.emit(_("[WARNING_NOTCL]Delete failed. Select a tool to delete."))
  623. return
  624. except Exception as e:
  625. log.debug(str(e))
  626. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  627. self.build_ui()
  628. def on_paint_button_click(self):
  629. self.app.report_usage(_("geometry_on_paint_button"))
  630. # self.app.call_source = 'paint'
  631. self.app.inform.emit(_("[WARNING_NOTCL]Click inside the desired polygon."))
  632. try:
  633. overlap = float(self.paintoverlap_entry.get_value())
  634. except ValueError:
  635. # try to convert comma to decimal point. if it's still not working error message and return
  636. try:
  637. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  638. except ValueError:
  639. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  640. "use a number."))
  641. return
  642. connect = self.pathconnect_cb.get_value()
  643. contour = self.paintcontour_cb.get_value()
  644. select_method = self.selectmethod_combo.get_value()
  645. self.obj_name = self.object_combo.currentText()
  646. # Get source object.
  647. try:
  648. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  649. except:
  650. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % self.obj_name)
  651. return
  652. if self.paint_obj is None:
  653. self.app.inform.emit(_("[ERROR_NOTCL]Object not found: %s") % self.paint_obj)
  654. return
  655. # test if the Geometry Object is multigeo and return Fail if True because
  656. # for now Paint don't work on MultiGeo
  657. if self.paint_obj.multigeo is True:
  658. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  659. return 'Fail'
  660. o_name = '%s_multitool_paint' % (self.obj_name)
  661. if select_method == "all":
  662. self.paint_poly_all(self.paint_obj,
  663. outname=o_name,
  664. overlap=overlap,
  665. connect=connect,
  666. contour=contour)
  667. if select_method == "single":
  668. self.app.inform.emit(_("[WARNING_NOTCL]Click inside the desired polygon."))
  669. # use the first tool in the tool table; get the diameter
  670. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  671. # To be called after clicking on the plot.
  672. def doit(event):
  673. # do paint single only for left mouse clicks
  674. if event.button == 1:
  675. self.app.inform.emit(_("Painting polygon..."))
  676. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  677. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  678. self.paint_poly(self.paint_obj,
  679. inside_pt=[pos[0], pos[1]],
  680. tooldia=tooldia,
  681. overlap=overlap,
  682. connect=connect,
  683. contour=contour)
  684. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  685. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  686. self.app.plotcanvas.vis_connect('mouse_press', doit)
  687. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  688. outname=None, connect=True,
  689. contour=True):
  690. """
  691. Paints a polygon selected by clicking on its interior.
  692. Note:
  693. * The margin is taken directly from the form.
  694. :param inside_pt: [x, y]
  695. :param tooldia: Diameter of the painting tool
  696. :param overlap: Overlap of the tool between passes.
  697. :param outname: Name of the resulting Geometry Object.
  698. :param connect: Connect lines to avoid tool lifts.
  699. :param contour: Paint around the edges.
  700. :return: None
  701. """
  702. # Which polygon.
  703. # poly = find_polygon(self.solid_geometry, inside_pt)
  704. poly = obj.find_polygon(inside_pt)
  705. paint_method = self.paintmethod_combo.get_value()
  706. try:
  707. paint_margin = float(self.paintmargin_entry.get_value())
  708. except ValueError:
  709. # try to convert comma to decimal point. if it's still not working error message and return
  710. try:
  711. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  712. except ValueError:
  713. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  714. "use a number."))
  715. return
  716. # No polygon?
  717. if poly is None:
  718. self.app.log.warning('No polygon found.')
  719. self.app.inform.emit(_('[WARNING] No polygon found.'))
  720. return
  721. proc = self.app.proc_container.new(_("Painting polygon."))
  722. name = outname if outname else self.obj_name + "_paint"
  723. # Initializes the new geometry object
  724. def gen_paintarea(geo_obj, app_obj):
  725. assert isinstance(geo_obj, FlatCAMGeometry), \
  726. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  727. # assert isinstance(app_obj, App)
  728. def paint_p(polyg):
  729. if paint_method == "seed":
  730. # Type(cp) == FlatCAMRTreeStorage | None
  731. cp = self.clear_polygon2(polyg,
  732. tooldia=tooldia,
  733. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  734. overlap=overlap,
  735. contour=contour,
  736. connect=connect)
  737. elif paint_method == "lines":
  738. # Type(cp) == FlatCAMRTreeStorage | None
  739. cp = self.clear_polygon3(polyg,
  740. tooldia=tooldia,
  741. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  742. overlap=overlap,
  743. contour=contour,
  744. connect=connect)
  745. else:
  746. # Type(cp) == FlatCAMRTreeStorage | None
  747. cp = self.clear_polygon(polyg,
  748. tooldia=tooldia,
  749. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  750. overlap=overlap,
  751. contour=contour,
  752. connect=connect)
  753. if cp is not None:
  754. geo_obj.solid_geometry += list(cp.get_objects())
  755. return cp
  756. else:
  757. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  758. return None
  759. geo_obj.solid_geometry = []
  760. try:
  761. a, b, c, d = poly.bounds
  762. geo_obj.options['xmin'] = a
  763. geo_obj.options['ymin'] = b
  764. geo_obj.options['xmax'] = c
  765. geo_obj.options['ymax'] = d
  766. except Exception as e:
  767. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  768. return
  769. try:
  770. poly_buf = poly.buffer(-paint_margin)
  771. if isinstance(poly_buf, MultiPolygon):
  772. cp = []
  773. for pp in poly_buf:
  774. cp.append(paint_p(pp))
  775. else:
  776. cp = paint_p(poly_buf)
  777. except Exception as e:
  778. log.debug("Could not Paint the polygons. %s" % str(e))
  779. self.app.inform.emit(
  780. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  781. "Or a different strategy of paint\n%s") % str(e))
  782. return
  783. if cp is not None:
  784. if isinstance(cp, list):
  785. for x in cp:
  786. geo_obj.solid_geometry += list(x.get_objects())
  787. else:
  788. geo_obj.solid_geometry = list(cp.get_objects())
  789. geo_obj.options["cnctooldia"] = tooldia
  790. # this turn on the FlatCAMCNCJob plot for multiple tools
  791. geo_obj.multigeo = False
  792. geo_obj.multitool = True
  793. current_uid = int(self.tools_table.item(0, 3).text())
  794. for k, v in self.paint_tools.items():
  795. if k == current_uid:
  796. v['data']['name'] = name
  797. geo_obj.tools = dict(self.paint_tools)
  798. # Experimental...
  799. # print("Indexing...", end=' ')
  800. # geo_obj.make_index()
  801. # if errors == 0:
  802. # print("[success] Paint single polygon Done")
  803. # self.app.inform.emit("[success] Paint single polygon Done")
  804. # else:
  805. # print("[WARNING] Paint single polygon done with errors")
  806. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  807. # "%d area(s) could not be painted.\n"
  808. # "Use different paint parameters or edit the paint geometry and correct"
  809. # "the issue."
  810. # % errors)
  811. def job_thread(app_obj):
  812. try:
  813. app_obj.new_object("geometry", name, gen_paintarea)
  814. except Exception as e:
  815. proc.done()
  816. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  817. return
  818. proc.done()
  819. # focus on Selected Tab
  820. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  821. self.app.inform.emit(_("Polygon Paint started ..."))
  822. # Promise object with the new name
  823. self.app.collection.promise(name)
  824. # Background
  825. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  826. def paint_poly_all(self, obj, overlap, outname=None,
  827. connect=True, contour=True):
  828. """
  829. Paints all polygons in this object.
  830. :param tooldia:
  831. :param overlap:
  832. :param outname:
  833. :param connect: Connect lines to avoid tool lifts.
  834. :param contour: Paint around the edges.
  835. :return:
  836. """
  837. paint_method = self.paintmethod_combo.get_value()
  838. try:
  839. paint_margin = float(self.paintmargin_entry.get_value())
  840. except ValueError:
  841. # try to convert comma to decimal point. if it's still not working error message and return
  842. try:
  843. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  844. except ValueError:
  845. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  846. "use a number."))
  847. return
  848. proc = self.app.proc_container.new(_("Painting polygon..."))
  849. name = outname if outname else self.obj_name + "_paint"
  850. over = overlap
  851. conn = connect
  852. cont = contour
  853. # This is a recursive generator of individual Polygons.
  854. # Note: Double check correct implementation. Might exit
  855. # early if it finds something that is not a Polygon?
  856. # def recurse(geo):
  857. # try:
  858. # for subg in geo:
  859. # for subsubg in recurse(subg):
  860. # yield subsubg
  861. # except TypeError:
  862. # if isinstance(geo, Polygon):
  863. # yield geo
  864. #
  865. # raise StopIteration
  866. def recurse(geometry, reset=True):
  867. """
  868. Creates a list of non-iterable linear geometry objects.
  869. Results are placed in self.flat_geometry
  870. :param geometry: Shapely type or list or list of list of such.
  871. :param reset: Clears the contents of self.flat_geometry.
  872. """
  873. if geometry is None:
  874. return
  875. if reset:
  876. self.flat_geometry = []
  877. ## If iterable, expand recursively.
  878. try:
  879. for geo in geometry:
  880. if geo is not None:
  881. recurse(geometry=geo, reset=False)
  882. ## Not iterable, do the actual indexing and add.
  883. except TypeError:
  884. self.flat_geometry.append(geometry)
  885. return self.flat_geometry
  886. # Initializes the new geometry object
  887. def gen_paintarea(geo_obj, app_obj):
  888. assert isinstance(geo_obj, FlatCAMGeometry), \
  889. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  890. sorted_tools = []
  891. for row in range(self.tools_table.rowCount()):
  892. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  893. sorted_tools.sort(reverse=True)
  894. try:
  895. a, b, c, d = obj.bounds()
  896. geo_obj.options['xmin'] = a
  897. geo_obj.options['ymin'] = b
  898. geo_obj.options['xmax'] = c
  899. geo_obj.options['ymax'] = d
  900. except Exception as e:
  901. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  902. return
  903. total_geometry = []
  904. current_uid = int(1)
  905. geo_obj.solid_geometry = []
  906. for tool_dia in sorted_tools:
  907. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  908. for k, v in self.paint_tools.items():
  909. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  910. current_uid = int(k)
  911. break
  912. for geo in recurse(obj.solid_geometry):
  913. try:
  914. if not isinstance(geo, Polygon):
  915. geo = Polygon(geo)
  916. poly_buf = geo.buffer(-paint_margin)
  917. if paint_method == "seed":
  918. # Type(cp) == FlatCAMRTreeStorage | None
  919. cp = self.clear_polygon2(poly_buf,
  920. tooldia=tool_dia,
  921. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  922. overlap=over,
  923. contour=cont,
  924. connect=conn)
  925. elif paint_method == "lines":
  926. # Type(cp) == FlatCAMRTreeStorage | None
  927. cp = self.clear_polygon3(poly_buf,
  928. tooldia=tool_dia,
  929. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  930. overlap=over,
  931. contour=cont,
  932. connect=conn)
  933. else:
  934. # Type(cp) == FlatCAMRTreeStorage | None
  935. cp = self.clear_polygon(poly_buf,
  936. tooldia=tool_dia,
  937. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  938. overlap=over,
  939. contour=cont,
  940. connect=conn)
  941. if cp is not None:
  942. total_geometry += list(cp.get_objects())
  943. except Exception as e:
  944. log.debug("Could not Paint the polygons. %s" % str(e))
  945. self.app.inform.emit(
  946. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  947. "Or a different Method of paint\n%s") % str(e))
  948. return
  949. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  950. # temporary list that stored that solid_geometry
  951. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  952. self.paint_tools[current_uid]['data']['name'] = name
  953. total_geometry[:] = []
  954. geo_obj.options["cnctooldia"] = tool_dia
  955. # this turn on the FlatCAMCNCJob plot for multiple tools
  956. geo_obj.multigeo = True
  957. geo_obj.multitool = True
  958. geo_obj.tools.clear()
  959. geo_obj.tools = dict(self.paint_tools)
  960. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  961. has_solid_geo = 0
  962. for tooluid in geo_obj.tools:
  963. if geo_obj.tools[tooluid]['solid_geometry']:
  964. has_solid_geo += 1
  965. if has_solid_geo == 0:
  966. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  967. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  968. "Change the painting parameters and try again."))
  969. return
  970. # Experimental...
  971. # print("Indexing...", end=' ')
  972. # geo_obj.make_index()
  973. self.app.inform.emit(_("[success] Paint All Done."))
  974. # Initializes the new geometry object
  975. def gen_paintarea_rest_machining(geo_obj, app_obj):
  976. assert isinstance(geo_obj, FlatCAMGeometry), \
  977. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  978. sorted_tools = []
  979. for row in range(self.tools_table.rowCount()):
  980. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  981. sorted_tools.sort(reverse=True)
  982. cleared_geo = []
  983. current_uid = int(1)
  984. geo_obj.solid_geometry = []
  985. try:
  986. a, b, c, d = obj.bounds()
  987. geo_obj.options['xmin'] = a
  988. geo_obj.options['ymin'] = b
  989. geo_obj.options['xmax'] = c
  990. geo_obj.options['ymax'] = d
  991. except Exception as e:
  992. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  993. return
  994. for tool_dia in sorted_tools:
  995. for geo in recurse(obj.solid_geometry):
  996. try:
  997. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  998. poly_buf = geo.buffer(-paint_margin)
  999. if paint_method == "standard":
  1000. # Type(cp) == FlatCAMRTreeStorage | None
  1001. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1002. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1003. overlap=over, contour=cont, connect=conn)
  1004. elif paint_method == "seed":
  1005. # Type(cp) == FlatCAMRTreeStorage | None
  1006. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1007. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1008. overlap=over, contour=cont, connect=conn)
  1009. elif paint_method == "lines":
  1010. # Type(cp) == FlatCAMRTreeStorage | None
  1011. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1012. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1013. overlap=over, contour=cont, connect=conn)
  1014. if cp is not None:
  1015. cleared_geo += list(cp.get_objects())
  1016. except Exception as e:
  1017. log.debug("Could not Paint the polygons. %s" % str(e))
  1018. self.app.inform.emit(
  1019. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1020. "Or a different Method of paint\n%s") % str(e))
  1021. return
  1022. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1023. for k, v in self.paint_tools.items():
  1024. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1025. current_uid = int(k)
  1026. break
  1027. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1028. # temporary list that stored that solid_geometry
  1029. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1030. self.paint_tools[current_uid]['data']['name'] = name
  1031. cleared_geo[:] = []
  1032. geo_obj.options["cnctooldia"] = tool_dia
  1033. # this turn on the FlatCAMCNCJob plot for multiple tools
  1034. geo_obj.multigeo = True
  1035. geo_obj.multitool = True
  1036. geo_obj.tools.clear()
  1037. geo_obj.tools = dict(self.paint_tools)
  1038. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1039. has_solid_geo = 0
  1040. for tooluid in geo_obj.tools:
  1041. if geo_obj.tools[tooluid]['solid_geometry']:
  1042. has_solid_geo += 1
  1043. if has_solid_geo == 0:
  1044. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1045. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1046. "Change the painting parameters and try again."))
  1047. return
  1048. # Experimental...
  1049. # print("Indexing...", end=' ')
  1050. # geo_obj.make_index()
  1051. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1052. def job_thread(app_obj):
  1053. try:
  1054. if self.rest_cb.isChecked():
  1055. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1056. else:
  1057. app_obj.new_object("geometry", name, gen_paintarea)
  1058. except Exception as e:
  1059. proc.done()
  1060. traceback.print_stack()
  1061. return
  1062. proc.done()
  1063. # focus on Selected Tab
  1064. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1065. self.app.inform.emit(_("Polygon Paint started ..."))
  1066. # Promise object with the new name
  1067. self.app.collection.promise(name)
  1068. # Background
  1069. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1070. def reset_fields(self):
  1071. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))