ToolPaint.py 85 KB

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