ToolPaint.py 53 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.inform.emit(_("[WARNING_NOTCL]Click inside the desired polygon."))
  631. try:
  632. overlap = float(self.paintoverlap_entry.get_value())
  633. except ValueError:
  634. # try to convert comma to decimal point. if it's still not working error message and return
  635. try:
  636. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  637. except ValueError:
  638. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  639. "use a number."))
  640. return
  641. connect = self.pathconnect_cb.get_value()
  642. contour = self.paintcontour_cb.get_value()
  643. select_method = self.selectmethod_combo.get_value()
  644. self.obj_name = self.object_combo.currentText()
  645. # Get source object.
  646. try:
  647. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  648. except:
  649. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % self.obj_name)
  650. return
  651. if self.paint_obj is None:
  652. self.app.inform.emit(_("[ERROR_NOTCL]Object not found: %s") % self.paint_obj)
  653. return
  654. # test if the Geometry Object is multigeo and return Fail if True because
  655. # for now Paint don't work on MultiGeo
  656. if self.paint_obj.multigeo is True:
  657. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  658. return 'Fail'
  659. o_name = '%s_multitool_paint' % (self.obj_name)
  660. if select_method == "all":
  661. self.paint_poly_all(self.paint_obj,
  662. outname=o_name,
  663. overlap=overlap,
  664. connect=connect,
  665. contour=contour)
  666. if select_method == "single":
  667. self.app.inform.emit(_("[WARNING_NOTCL]Click inside the desired polygon."))
  668. # use the first tool in the tool table; get the diameter
  669. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  670. # To be called after clicking on the plot.
  671. def doit(event):
  672. # do paint single only for left mouse clicks
  673. if event.button == 1:
  674. self.app.inform.emit(_("Painting polygon..."))
  675. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  676. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  677. self.paint_poly(self.paint_obj,
  678. inside_pt=[pos[0], pos[1]],
  679. tooldia=tooldia,
  680. overlap=overlap,
  681. connect=connect,
  682. contour=contour)
  683. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  684. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  685. self.app.plotcanvas.vis_connect('mouse_press', doit)
  686. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  687. outname=None, connect=True,
  688. contour=True):
  689. """
  690. Paints a polygon selected by clicking on its interior.
  691. Note:
  692. * The margin is taken directly from the form.
  693. :param inside_pt: [x, y]
  694. :param tooldia: Diameter of the painting tool
  695. :param overlap: Overlap of the tool between passes.
  696. :param outname: Name of the resulting Geometry Object.
  697. :param connect: Connect lines to avoid tool lifts.
  698. :param contour: Paint around the edges.
  699. :return: None
  700. """
  701. # Which polygon.
  702. # poly = find_polygon(self.solid_geometry, inside_pt)
  703. poly = obj.find_polygon(inside_pt)
  704. paint_method = self.paintmethod_combo.get_value()
  705. try:
  706. paint_margin = float(self.paintmargin_entry.get_value())
  707. except ValueError:
  708. # try to convert comma to decimal point. if it's still not working error message and return
  709. try:
  710. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  711. except ValueError:
  712. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  713. "use a number."))
  714. return
  715. # No polygon?
  716. if poly is None:
  717. self.app.log.warning('No polygon found.')
  718. self.app.inform.emit(_('[WARNING] No polygon found.'))
  719. return
  720. proc = self.app.proc_container.new(_("Painting polygon."))
  721. name = outname if outname else self.obj_name + "_paint"
  722. # Initializes the new geometry object
  723. def gen_paintarea(geo_obj, app_obj):
  724. assert isinstance(geo_obj, FlatCAMGeometry), \
  725. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  726. # assert isinstance(app_obj, App)
  727. def paint_p(polyg):
  728. if paint_method == "seed":
  729. # Type(cp) == FlatCAMRTreeStorage | None
  730. cp = self.clear_polygon2(polyg,
  731. tooldia=tooldia,
  732. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  733. overlap=overlap,
  734. contour=contour,
  735. connect=connect)
  736. elif paint_method == "lines":
  737. # Type(cp) == FlatCAMRTreeStorage | None
  738. cp = self.clear_polygon3(polyg,
  739. tooldia=tooldia,
  740. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  741. overlap=overlap,
  742. contour=contour,
  743. connect=connect)
  744. else:
  745. # Type(cp) == FlatCAMRTreeStorage | None
  746. cp = self.clear_polygon(polyg,
  747. tooldia=tooldia,
  748. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  749. overlap=overlap,
  750. contour=contour,
  751. connect=connect)
  752. if cp is not None:
  753. geo_obj.solid_geometry += list(cp.get_objects())
  754. return cp
  755. else:
  756. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  757. return None
  758. geo_obj.solid_geometry = []
  759. try:
  760. a, b, c, d = poly.bounds()
  761. geo_obj.options['xmin'] = a
  762. geo_obj.options['ymin'] = b
  763. geo_obj.options['xmax'] = c
  764. geo_obj.options['ymax'] = d
  765. except Exception as e:
  766. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  767. return
  768. try:
  769. poly_buf = poly.buffer(-paint_margin)
  770. if isinstance(poly_buf, MultiPolygon):
  771. cp = []
  772. for pp in poly_buf:
  773. cp.append(paint_p(pp))
  774. else:
  775. cp = paint_p(poly_buf)
  776. except Exception as e:
  777. log.debug("Could not Paint the polygons. %s" % str(e))
  778. self.app.inform.emit(
  779. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  780. "Or a different strategy of paint\n%s") % str(e))
  781. return
  782. if cp is not None:
  783. if isinstance(cp, list):
  784. for x in cp:
  785. geo_obj.solid_geometry += list(x.get_objects())
  786. else:
  787. geo_obj.solid_geometry = list(cp.get_objects())
  788. geo_obj.options["cnctooldia"] = tooldia
  789. # this turn on the FlatCAMCNCJob plot for multiple tools
  790. geo_obj.multigeo = False
  791. geo_obj.multitool = True
  792. current_uid = int(self.tools_table.item(0, 3).text())
  793. for k, v in self.paint_tools.items():
  794. if k == current_uid:
  795. v['data']['name'] = name
  796. geo_obj.tools = dict(self.paint_tools)
  797. # Experimental...
  798. # print("Indexing...", end=' ')
  799. # geo_obj.make_index()
  800. # if errors == 0:
  801. # print("[success] Paint single polygon Done")
  802. # self.app.inform.emit("[success] Paint single polygon Done")
  803. # else:
  804. # print("[WARNING] Paint single polygon done with errors")
  805. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  806. # "%d area(s) could not be painted.\n"
  807. # "Use different paint parameters or edit the paint geometry and correct"
  808. # "the issue."
  809. # % errors)
  810. def job_thread(app_obj):
  811. try:
  812. app_obj.new_object("geometry", name, gen_paintarea)
  813. except Exception as e:
  814. proc.done()
  815. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  816. return
  817. proc.done()
  818. # focus on Selected Tab
  819. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  820. self.app.inform.emit(_("Polygon Paint started ..."))
  821. # Promise object with the new name
  822. self.app.collection.promise(name)
  823. # Background
  824. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  825. def paint_poly_all(self, obj, overlap, outname=None,
  826. connect=True, contour=True):
  827. """
  828. Paints all polygons in this object.
  829. :param tooldia:
  830. :param overlap:
  831. :param outname:
  832. :param connect: Connect lines to avoid tool lifts.
  833. :param contour: Paint around the edges.
  834. :return:
  835. """
  836. paint_method = self.paintmethod_combo.get_value()
  837. try:
  838. paint_margin = float(self.paintmargin_entry.get_value())
  839. except ValueError:
  840. # try to convert comma to decimal point. if it's still not working error message and return
  841. try:
  842. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  843. except ValueError:
  844. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  845. "use a number."))
  846. return
  847. proc = self.app.proc_container.new(_("Painting polygon..."))
  848. name = outname if outname else self.obj_name + "_paint"
  849. over = overlap
  850. conn = connect
  851. cont = contour
  852. # This is a recursive generator of individual Polygons.
  853. # Note: Double check correct implementation. Might exit
  854. # early if it finds something that is not a Polygon?
  855. # def recurse(geo):
  856. # try:
  857. # for subg in geo:
  858. # for subsubg in recurse(subg):
  859. # yield subsubg
  860. # except TypeError:
  861. # if isinstance(geo, Polygon):
  862. # yield geo
  863. #
  864. # raise StopIteration
  865. def recurse(geometry, reset=True):
  866. """
  867. Creates a list of non-iterable linear geometry objects.
  868. Results are placed in self.flat_geometry
  869. :param geometry: Shapely type or list or list of list of such.
  870. :param reset: Clears the contents of self.flat_geometry.
  871. """
  872. if geometry is None:
  873. return
  874. if reset:
  875. self.flat_geometry = []
  876. ## If iterable, expand recursively.
  877. try:
  878. for geo in geometry:
  879. if geo is not None:
  880. recurse(geometry=geo, reset=False)
  881. ## Not iterable, do the actual indexing and add.
  882. except TypeError:
  883. self.flat_geometry.append(geometry)
  884. return self.flat_geometry
  885. # Initializes the new geometry object
  886. def gen_paintarea(geo_obj, app_obj):
  887. assert isinstance(geo_obj, FlatCAMGeometry), \
  888. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  889. sorted_tools = []
  890. for row in range(self.tools_table.rowCount()):
  891. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  892. sorted_tools.sort(reverse=True)
  893. try:
  894. a, b, c, d = obj.bounds()
  895. geo_obj.options['xmin'] = a
  896. geo_obj.options['ymin'] = b
  897. geo_obj.options['xmax'] = c
  898. geo_obj.options['ymax'] = d
  899. except Exception as e:
  900. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  901. return
  902. total_geometry = []
  903. current_uid = int(1)
  904. geo_obj.solid_geometry = []
  905. for tool_dia in sorted_tools:
  906. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  907. for k, v in self.paint_tools.items():
  908. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  909. current_uid = int(k)
  910. break
  911. for geo in recurse(obj.solid_geometry):
  912. try:
  913. if not isinstance(geo, Polygon):
  914. geo = Polygon(geo)
  915. poly_buf = geo.buffer(-paint_margin)
  916. if paint_method == "seed":
  917. # Type(cp) == FlatCAMRTreeStorage | None
  918. cp = self.clear_polygon2(poly_buf,
  919. tooldia=tool_dia,
  920. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  921. overlap=over,
  922. contour=cont,
  923. connect=conn)
  924. elif paint_method == "lines":
  925. # Type(cp) == FlatCAMRTreeStorage | None
  926. cp = self.clear_polygon3(poly_buf,
  927. tooldia=tool_dia,
  928. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  929. overlap=over,
  930. contour=cont,
  931. connect=conn)
  932. else:
  933. # Type(cp) == FlatCAMRTreeStorage | None
  934. cp = self.clear_polygon(poly_buf,
  935. tooldia=tool_dia,
  936. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  937. overlap=over,
  938. contour=cont,
  939. connect=conn)
  940. if cp is not None:
  941. total_geometry += list(cp.get_objects())
  942. except Exception as e:
  943. log.debug("Could not Paint the polygons. %s" % str(e))
  944. self.app.inform.emit(
  945. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  946. "Or a different Method of paint\n%s") % str(e))
  947. return
  948. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  949. # temporary list that stored that solid_geometry
  950. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  951. self.paint_tools[current_uid]['data']['name'] = name
  952. total_geometry[:] = []
  953. geo_obj.options["cnctooldia"] = tool_dia
  954. # this turn on the FlatCAMCNCJob plot for multiple tools
  955. geo_obj.multigeo = True
  956. geo_obj.multitool = True
  957. geo_obj.tools.clear()
  958. geo_obj.tools = dict(self.paint_tools)
  959. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  960. has_solid_geo = 0
  961. for tooluid in geo_obj.tools:
  962. if geo_obj.tools[tooluid]['solid_geometry']:
  963. has_solid_geo += 1
  964. if has_solid_geo == 0:
  965. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  966. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  967. "Change the painting parameters and try again."))
  968. return
  969. # Experimental...
  970. # print("Indexing...", end=' ')
  971. # geo_obj.make_index()
  972. self.app.inform.emit(_("[success] Paint All Done."))
  973. # Initializes the new geometry object
  974. def gen_paintarea_rest_machining(geo_obj, app_obj):
  975. assert isinstance(geo_obj, FlatCAMGeometry), \
  976. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  977. sorted_tools = []
  978. for row in range(self.tools_table.rowCount()):
  979. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  980. sorted_tools.sort(reverse=True)
  981. cleared_geo = []
  982. current_uid = int(1)
  983. geo_obj.solid_geometry = []
  984. try:
  985. a, b, c, d = obj.bounds()
  986. geo_obj.options['xmin'] = a
  987. geo_obj.options['ymin'] = b
  988. geo_obj.options['xmax'] = c
  989. geo_obj.options['ymax'] = d
  990. except Exception as e:
  991. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  992. return
  993. for tool_dia in sorted_tools:
  994. for geo in recurse(obj.solid_geometry):
  995. try:
  996. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  997. poly_buf = geo.buffer(-paint_margin)
  998. if paint_method == "standard":
  999. # Type(cp) == FlatCAMRTreeStorage | None
  1000. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1001. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1002. overlap=over, contour=cont, connect=conn)
  1003. elif paint_method == "seed":
  1004. # Type(cp) == FlatCAMRTreeStorage | None
  1005. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1006. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1007. overlap=over, contour=cont, connect=conn)
  1008. elif paint_method == "lines":
  1009. # Type(cp) == FlatCAMRTreeStorage | None
  1010. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1011. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1012. overlap=over, contour=cont, connect=conn)
  1013. if cp is not None:
  1014. cleared_geo += list(cp.get_objects())
  1015. except Exception as e:
  1016. log.debug("Could not Paint the polygons. %s" % str(e))
  1017. self.app.inform.emit(
  1018. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1019. "Or a different Method of paint\n%s") % str(e))
  1020. return
  1021. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1022. for k, v in self.paint_tools.items():
  1023. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1024. current_uid = int(k)
  1025. break
  1026. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1027. # temporary list that stored that solid_geometry
  1028. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1029. self.paint_tools[current_uid]['data']['name'] = name
  1030. cleared_geo[:] = []
  1031. geo_obj.options["cnctooldia"] = tool_dia
  1032. # this turn on the FlatCAMCNCJob plot for multiple tools
  1033. geo_obj.multigeo = True
  1034. geo_obj.multitool = True
  1035. geo_obj.tools.clear()
  1036. geo_obj.tools = dict(self.paint_tools)
  1037. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1038. has_solid_geo = 0
  1039. for tooluid in geo_obj.tools:
  1040. if geo_obj.tools[tooluid]['solid_geometry']:
  1041. has_solid_geo += 1
  1042. if has_solid_geo == 0:
  1043. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1044. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1045. "Change the painting parameters and try again."))
  1046. return
  1047. # Experimental...
  1048. # print("Indexing...", end=' ')
  1049. # geo_obj.make_index()
  1050. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1051. def job_thread(app_obj):
  1052. try:
  1053. if self.rest_cb.isChecked():
  1054. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1055. else:
  1056. app_obj.new_object("geometry", name, gen_paintarea)
  1057. except Exception as e:
  1058. proc.done()
  1059. traceback.print_stack()
  1060. return
  1061. proc.done()
  1062. # focus on Selected Tab
  1063. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1064. self.app.inform.emit(_("Polygon Paint started ..."))
  1065. # Promise object with the new name
  1066. self.app.collection.promise(name)
  1067. # Background
  1068. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1069. def reset_fields(self):
  1070. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))