ToolPaint.py 56 KB

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