ToolPaint.py 78 KB

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