ToolPaint.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155
  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 painting:\n"
  198. "- Standard: Fixed step inwards.\n"
  199. "- Seed-based: Outwards from seed.\n"
  200. "- Line-based: 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 Polygons to be painted.\n\n"
  243. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  244. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  245. "- 'All Polygons' - the Paint will start after click.\n"
  246. "- 'Reference Object' - will do non copper clearing within the area\n"
  247. "specified by another 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(_("on_paint_button_click"))
  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. # use the selected tools in the tool table; get diameters
  809. tooldia_list = list()
  810. if self.tools_table.selectedItems():
  811. for x in self.tools_table.selectedItems():
  812. try:
  813. tooldia = float(self.tools_table.item(x.row(), 1).text())
  814. except ValueError:
  815. # try to convert comma to decimal point. if it's still not working error message and return
  816. try:
  817. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  818. except ValueError:
  819. self.app.inform.emit(_("[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  820. "use a number."))
  821. continue
  822. tooldia_list.append(tooldia)
  823. else:
  824. self.app.inform.emit(_("[ERROR_NOTCL] No selected tools in Tool Table."))
  825. return
  826. if select_method == "all":
  827. self.paint_poly_all(self.paint_obj,
  828. tooldia=tooldia_list,
  829. outname=o_name,
  830. overlap=overlap,
  831. connect=connect,
  832. contour=contour)
  833. elif select_method == "single":
  834. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  835. # use the first tool in the tool table; get the diameter
  836. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  837. # To be called after clicking on the plot.
  838. def doit(event):
  839. # do paint single only for left mouse clicks
  840. if event.button == 1:
  841. self.app.inform.emit(_("Painting polygon..."))
  842. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  843. pos = self.app.plotcanvas.translate_coords(event.pos)
  844. if self.app.grid_status() == True:
  845. pos = self.app.geo_editor.snap(pos[0], pos[1])
  846. self.paint_poly(self.paint_obj,
  847. inside_pt=[pos[0], pos[1]],
  848. tooldia=tooldia_list,
  849. overlap=overlap,
  850. connect=connect,
  851. contour=contour)
  852. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  853. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  854. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  855. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  856. self.app.plotcanvas.vis_connect('mouse_press', doit)
  857. elif select_method == "area":
  858. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  859. # use the first tool in the tool table; get the diameter
  860. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  861. # To be called after clicking on the plot.
  862. def on_mouse_release(event):
  863. # do paint single only for left mouse clicks
  864. if event.button == 1:
  865. if not self.first_click:
  866. self.first_click = True
  867. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  868. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  869. if self.app.grid_status() == True:
  870. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  871. else:
  872. self.app.inform.emit(_("Zone added. Right click to finish."))
  873. self.app.delete_selection_shape()
  874. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  875. if self.app.grid_status() == True:
  876. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  877. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  878. x1, y1 = curr_pos[0], curr_pos[1]
  879. pt1 = (x0, y0)
  880. pt2 = (x1, y0)
  881. pt3 = (x1, y1)
  882. pt4 = (x0, y1)
  883. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  884. modifiers = QtWidgets.QApplication.keyboardModifiers()
  885. if modifiers == QtCore.Qt.ShiftModifier:
  886. mod_key = 'Shift'
  887. elif modifiers == QtCore.Qt.ControlModifier:
  888. mod_key = 'Control'
  889. else:
  890. mod_key = None
  891. if mod_key == self.app.defaults["global_mselect_key"]:
  892. self.first_click = False
  893. return
  894. self.sel_rect = cascaded_union(self.sel_rect)
  895. self.paint_poly_area(obj=self.paint_obj,
  896. tooldia=tooldia_list,
  897. sel_obj= self.sel_rect,
  898. outname=o_name,
  899. overlap=overlap,
  900. connect=connect,
  901. contour=contour)
  902. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  903. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  904. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  905. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  906. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  907. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  908. self.first_click = False
  909. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  910. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  911. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  912. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  913. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  914. self.sel_rect = cascaded_union(self.sel_rect)
  915. self.paint_poly_area(obj=self.paint_obj,
  916. tooldia=tooldia_list,
  917. sel_obj=self.sel_rect,
  918. outname=o_name,
  919. overlap=overlap,
  920. connect=connect,
  921. contour=contour)
  922. # called on mouse move
  923. def on_mouse_move(event):
  924. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  925. self.app.app_cursor.enabled = False
  926. if event.button == 2:
  927. if event.is_dragging is True:
  928. self.mouse_is_dragging = True
  929. else:
  930. self.mouse_is_dragging = False
  931. if self.app.grid_status() == True:
  932. self.app.app_cursor.enabled = True
  933. # Update cursor
  934. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  935. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  936. symbol='++', edge_color='black', size=20)
  937. if self.first_click:
  938. self.app.delete_selection_shape()
  939. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  940. coords=(curr_pos[0], curr_pos[1]),
  941. face_alpha=0.0)
  942. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  943. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  944. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  945. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  946. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  947. elif select_method == 'ref':
  948. self.bound_obj_name = self.box_combo.currentText()
  949. # Get source object.
  950. try:
  951. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  952. except Exception as e:
  953. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  954. return "Could not retrieve object: %s" % self.obj_name
  955. self.paint_poly_ref(obj=self.paint_obj,
  956. sel_obj=self.bound_obj,
  957. tooldia=tooldia_list,
  958. overlap=overlap,
  959. outname=o_name,
  960. connect=connect,
  961. contour=contour)
  962. def paint_poly(self, obj,
  963. inside_pt=None,
  964. tooldia=None,
  965. overlap=None,
  966. order=None,
  967. margin=None,
  968. method=None,
  969. outname=None,
  970. connect=None,
  971. contour=None,
  972. tools_storage=None):
  973. """
  974. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  975. Note:
  976. * The margin is taken directly from the form.
  977. :param obj: painted object
  978. :param inside_pt: [x, y]
  979. :param tooldia: Diameter of the painting tool
  980. :param overlap: Overlap of the tool between passes.
  981. :param order: if the tools are ordered and how
  982. :param margin: a border around painting area
  983. :param outname: Name of the resulting Geometry Object.
  984. :param connect: Connect lines to avoid tool lifts.
  985. :param contour: Paint around the edges.
  986. :param method: choice out of 'seed', 'normal', 'lines'
  987. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  988. Usage of the different one is related to when this function is called from a TcL command.
  989. :return: None
  990. """
  991. # Which polygon.
  992. # poly = find_polygon(self.solid_geometry, inside_pt)
  993. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  994. paint_method = method if method is None else self.paintmethod_combo.get_value()
  995. if margin is not None:
  996. paint_margin = margin
  997. else:
  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. # No polygon?
  1009. if poly is None:
  1010. self.app.log.warning('No polygon found.')
  1011. self.app.inform.emit(_('[WARNING] No polygon found.'))
  1012. return
  1013. proc = self.app.proc_container.new(_("Painting polygon."))
  1014. name = outname if outname is not None else self.obj_name + "_paint"
  1015. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1016. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1017. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1018. order = order if order is not None else self.order_radio.get_value()
  1019. sorted_tools = []
  1020. if tooldia is not None:
  1021. try:
  1022. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1023. except AttributeError:
  1024. if not isinstance(tooldia, list):
  1025. sorted_tools = [float(tooldia)]
  1026. else:
  1027. sorted_tools = tooldia
  1028. else:
  1029. for row in range(self.tools_table.rowCount()):
  1030. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1031. if tools_storage is not None:
  1032. tools_storage = tools_storage
  1033. else:
  1034. tools_storage = self.paint_tools
  1035. # Initializes the new geometry object
  1036. def gen_paintarea(geo_obj, app_obj):
  1037. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1038. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1039. # assert isinstance(app_obj, App)
  1040. tool_dia = None
  1041. if order == 'fwd':
  1042. sorted_tools.sort(reverse=False)
  1043. elif order == 'rev':
  1044. sorted_tools.sort(reverse=True)
  1045. else:
  1046. pass
  1047. def paint_p(polyg, tooldia):
  1048. if paint_method == "seed":
  1049. # Type(cp) == FlatCAMRTreeStorage | None
  1050. cpoly = self.clear_polygon2(polyg,
  1051. tooldia=tooldia,
  1052. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1053. overlap=over,
  1054. contour=cont,
  1055. connect=conn)
  1056. elif paint_method == "lines":
  1057. # Type(cp) == FlatCAMRTreeStorage | None
  1058. cpoly = self.clear_polygon3(polyg,
  1059. tooldia=tooldia,
  1060. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1061. overlap=over,
  1062. contour=cont,
  1063. connect=conn)
  1064. else:
  1065. # Type(cp) == FlatCAMRTreeStorage | None
  1066. cpoly = self.clear_polygon(polyg,
  1067. tooldia=tooldia,
  1068. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1069. overlap=over,
  1070. contour=cont,
  1071. connect=conn)
  1072. if cpoly is not None:
  1073. geo_obj.solid_geometry += list(cpoly.get_objects())
  1074. return cpoly
  1075. else:
  1076. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  1077. return None
  1078. try:
  1079. a, b, c, d = poly.bounds
  1080. geo_obj.options['xmin'] = a
  1081. geo_obj.options['ymin'] = b
  1082. geo_obj.options['xmax'] = c
  1083. geo_obj.options['ymax'] = d
  1084. except Exception as e:
  1085. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1086. return
  1087. total_geometry = []
  1088. current_uid = int(1)
  1089. geo_obj.solid_geometry = []
  1090. for tool_dia in sorted_tools:
  1091. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1092. for k, v in tools_storage.items():
  1093. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1094. current_uid = int(k)
  1095. break
  1096. try:
  1097. poly_buf = poly.buffer(-paint_margin)
  1098. if isinstance(poly_buf, MultiPolygon):
  1099. cp = []
  1100. for pp in poly_buf:
  1101. cp.append(paint_p(pp, tooldia=tool_dia))
  1102. else:
  1103. cp = paint_p(poly_buf, tooldia=tool_dia)
  1104. if cp is not None:
  1105. if isinstance(cp, list):
  1106. for x in cp:
  1107. total_geometry += list(x.get_objects())
  1108. else:
  1109. total_geometry = list(cp.get_objects())
  1110. except Exception as e:
  1111. log.debug("Could not Paint the polygons. %s" % str(e))
  1112. self.app.inform.emit(
  1113. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  1114. "Or a different strategy of paint\n%s") % str(e))
  1115. return
  1116. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1117. # dictionary and then reset the temporary list that stored that solid_geometry
  1118. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1119. tools_storage[current_uid]['data']['name'] = name
  1120. total_geometry[:] = []
  1121. # delete tools with empty geometry
  1122. keys_to_delete = []
  1123. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1124. for uid in tools_storage:
  1125. # if the solid_geometry (type=list) is empty
  1126. if not tools_storage[uid]['solid_geometry']:
  1127. keys_to_delete.append(uid)
  1128. # actual delete of keys from the tools_storage dict
  1129. for k in keys_to_delete:
  1130. tools_storage.pop(k, None)
  1131. geo_obj.options["cnctooldia"] = str(tool_dia)
  1132. # this turn on the FlatCAMCNCJob plot for multiple tools
  1133. geo_obj.multigeo = True
  1134. geo_obj.multitool = True
  1135. geo_obj.tools.clear()
  1136. geo_obj.tools = dict(tools_storage)
  1137. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1138. has_solid_geo = 0
  1139. for tooluid in geo_obj.tools:
  1140. if geo_obj.tools[tooluid]['solid_geometry']:
  1141. has_solid_geo += 1
  1142. if has_solid_geo == 0:
  1143. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1144. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1145. "Change the painting parameters and try again."))
  1146. return
  1147. self.app.inform.emit(_("[success] Paint Single Done."))
  1148. # Experimental...
  1149. # print("Indexing...", end=' ')
  1150. # geo_obj.make_index()
  1151. # if errors == 0:
  1152. # print("[success] Paint single polygon Done")
  1153. # self.app.inform.emit("[success] Paint single polygon Done")
  1154. # else:
  1155. # print("[WARNING] Paint single polygon done with errors")
  1156. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1157. # "%d area(s) could not be painted.\n"
  1158. # "Use different paint parameters or edit the paint geometry and correct"
  1159. # "the issue."
  1160. # % errors)
  1161. def job_thread(app_obj):
  1162. try:
  1163. app_obj.new_object("geometry", name, gen_paintarea)
  1164. except Exception as e:
  1165. proc.done()
  1166. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  1167. return
  1168. proc.done()
  1169. # focus on Selected Tab
  1170. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1171. self.app.inform.emit(_("Polygon Paint started ..."))
  1172. # Promise object with the new name
  1173. self.app.collection.promise(name)
  1174. # Background
  1175. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1176. def paint_poly_all(self, obj,
  1177. tooldia=None,
  1178. overlap=None,
  1179. order=None,
  1180. margin=None,
  1181. method=None,
  1182. outname=None,
  1183. connect=None,
  1184. contour=None,
  1185. tools_storage=None):
  1186. """
  1187. Paints all polygons in this object.
  1188. :param obj: painted object
  1189. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1190. :param overlap: value by which the paths will overlap
  1191. :param order: if the tools are ordered and how
  1192. :param margin: a border around painting area
  1193. :param outname: name of the resulting object
  1194. :param connect: Connect lines to avoid tool lifts.
  1195. :param contour: Paint around the edges.
  1196. :param method: choice out of 'seed', 'normal', 'lines'
  1197. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1198. Usage of the different one is related to when this function is called from a TcL command.
  1199. :return:
  1200. """
  1201. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1202. if margin is not None:
  1203. paint_margin = margin
  1204. else:
  1205. try:
  1206. paint_margin = float(self.paintmargin_entry.get_value())
  1207. except ValueError:
  1208. # try to convert comma to decimal point. if it's still not working error message and return
  1209. try:
  1210. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1211. except ValueError:
  1212. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1213. "use a number."))
  1214. return
  1215. proc = self.app.proc_container.new(_("Painting polygon..."))
  1216. name = outname if outname is not None else self.obj_name + "_paint"
  1217. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1218. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1219. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1220. order = order if order is not None else self.order_radio.get_value()
  1221. sorted_tools = []
  1222. if tooldia is not None:
  1223. try:
  1224. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1225. except AttributeError:
  1226. if not isinstance(tooldia, list):
  1227. sorted_tools = [float(tooldia)]
  1228. else:
  1229. sorted_tools = tooldia
  1230. else:
  1231. for row in range(self.tools_table.rowCount()):
  1232. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1233. if tools_storage is not None:
  1234. tools_storage = tools_storage
  1235. else:
  1236. tools_storage = self.paint_tools
  1237. # This is a recursive generator of individual Polygons.
  1238. # Note: Double check correct implementation. Might exit
  1239. # early if it finds something that is not a Polygon?
  1240. # def recurse(geo):
  1241. # try:
  1242. # for subg in geo:
  1243. # for subsubg in recurse(subg):
  1244. # yield subsubg
  1245. # except TypeError:
  1246. # if isinstance(geo, Polygon):
  1247. # yield geo
  1248. #
  1249. # raise StopIteration
  1250. def recurse(geometry, reset=True):
  1251. """
  1252. Creates a list of non-iterable linear geometry objects.
  1253. Results are placed in self.flat_geometry
  1254. :param geometry: Shapely type or list or list of list of such.
  1255. :param reset: Clears the contents of self.flat_geometry.
  1256. """
  1257. if geometry is None:
  1258. return
  1259. if reset:
  1260. self.flat_geometry = []
  1261. # ## If iterable, expand recursively.
  1262. try:
  1263. for geo in geometry:
  1264. if geo is not None:
  1265. recurse(geometry=geo, reset=False)
  1266. # ## Not iterable, do the actual indexing and add.
  1267. except TypeError:
  1268. if isinstance(geometry, LinearRing):
  1269. g = Polygon(geometry)
  1270. self.flat_geometry.append(g)
  1271. else:
  1272. self.flat_geometry.append(geometry)
  1273. return self.flat_geometry
  1274. # Initializes the new geometry object
  1275. def gen_paintarea(geo_obj, app_obj):
  1276. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1277. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1278. tool_dia = None
  1279. if order == 'fwd':
  1280. sorted_tools.sort(reverse=False)
  1281. elif order == 'rev':
  1282. sorted_tools.sort(reverse=True)
  1283. else:
  1284. pass
  1285. try:
  1286. a, b, c, d = obj.bounds()
  1287. geo_obj.options['xmin'] = a
  1288. geo_obj.options['ymin'] = b
  1289. geo_obj.options['xmax'] = c
  1290. geo_obj.options['ymax'] = d
  1291. except Exception as e:
  1292. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1293. return
  1294. total_geometry = []
  1295. current_uid = int(1)
  1296. geo_obj.solid_geometry = []
  1297. for tool_dia in sorted_tools:
  1298. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1299. for k, v in tools_storage.items():
  1300. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1301. current_uid = int(k)
  1302. break
  1303. for geo in recurse(obj.solid_geometry):
  1304. try:
  1305. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1306. if not isinstance(geo, Polygon):
  1307. continue
  1308. poly_buf = geo.buffer(-paint_margin)
  1309. if paint_method == "seed":
  1310. # Type(cp) == FlatCAMRTreeStorage | None
  1311. cp = self.clear_polygon2(poly_buf,
  1312. tooldia=tool_dia,
  1313. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1314. overlap=over,
  1315. contour=cont,
  1316. connect=conn)
  1317. elif paint_method == "lines":
  1318. # Type(cp) == FlatCAMRTreeStorage | None
  1319. cp = self.clear_polygon3(poly_buf,
  1320. tooldia=tool_dia,
  1321. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1322. overlap=over,
  1323. contour=cont,
  1324. connect=conn)
  1325. else:
  1326. # Type(cp) == FlatCAMRTreeStorage | None
  1327. cp = self.clear_polygon(poly_buf,
  1328. tooldia=tool_dia,
  1329. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1330. overlap=over,
  1331. contour=cont,
  1332. connect=conn)
  1333. if cp is not None:
  1334. total_geometry += list(cp.get_objects())
  1335. except Exception as e:
  1336. log.debug("Could not Paint the polygons. %s" % str(e))
  1337. self.app.inform.emit(
  1338. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1339. "Or a different Method of paint\n%s") % str(e))
  1340. return
  1341. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1342. # dictionary and then reset the temporary list that stored that solid_geometry
  1343. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1344. tools_storage[current_uid]['data']['name'] = name
  1345. total_geometry[:] = []
  1346. # delete tools with empty geometry
  1347. keys_to_delete = []
  1348. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1349. for uid in tools_storage:
  1350. # if the solid_geometry (type=list) is empty
  1351. if not tools_storage[uid]['solid_geometry']:
  1352. keys_to_delete.append(uid)
  1353. # actual delete of keys from the tools_storage dict
  1354. for k in keys_to_delete:
  1355. tools_storage.pop(k, None)
  1356. geo_obj.options["cnctooldia"] = str(tool_dia)
  1357. # this turn on the FlatCAMCNCJob plot for multiple tools
  1358. geo_obj.multigeo = True
  1359. geo_obj.multitool = True
  1360. geo_obj.tools.clear()
  1361. geo_obj.tools = dict(tools_storage)
  1362. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1363. has_solid_geo = 0
  1364. for tooluid in geo_obj.tools:
  1365. if geo_obj.tools[tooluid]['solid_geometry']:
  1366. has_solid_geo += 1
  1367. if has_solid_geo == 0:
  1368. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1369. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1370. "Change the painting parameters and try again."))
  1371. return
  1372. # Experimental...
  1373. # print("Indexing...", end=' ')
  1374. # geo_obj.make_index()
  1375. self.app.inform.emit(_("[success] Paint All Done."))
  1376. # Initializes the new geometry object
  1377. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1378. assert isinstance(geo_obj, FlatCAMGeometry), \
  1379. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1380. tool_dia = None
  1381. sorted_tools.sort(reverse=True)
  1382. cleared_geo = []
  1383. current_uid = int(1)
  1384. geo_obj.solid_geometry = []
  1385. try:
  1386. a, b, c, d = obj.bounds()
  1387. geo_obj.options['xmin'] = a
  1388. geo_obj.options['ymin'] = b
  1389. geo_obj.options['xmax'] = c
  1390. geo_obj.options['ymax'] = d
  1391. except Exception as e:
  1392. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1393. return
  1394. for tool_dia in sorted_tools:
  1395. for geo in recurse(obj.solid_geometry):
  1396. try:
  1397. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1398. poly_buf = geo.buffer(-paint_margin)
  1399. cp = None
  1400. if paint_method == "standard":
  1401. # Type(cp) == FlatCAMRTreeStorage | None
  1402. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1403. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1404. overlap=over, contour=cont, connect=conn)
  1405. elif paint_method == "seed":
  1406. # Type(cp) == FlatCAMRTreeStorage | None
  1407. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1408. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1409. overlap=over, contour=cont, connect=conn)
  1410. elif paint_method == "lines":
  1411. # Type(cp) == FlatCAMRTreeStorage | None
  1412. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1413. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1414. overlap=over, contour=cont, connect=conn)
  1415. if cp is not None:
  1416. cleared_geo += list(cp.get_objects())
  1417. except Exception as e:
  1418. log.debug("Could not Paint the polygons. %s" % str(e))
  1419. self.app.inform.emit(
  1420. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1421. "Or a different Method of paint\n%s") % str(e))
  1422. return
  1423. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1424. for k, v in tools_storage.items():
  1425. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1426. current_uid = int(k)
  1427. break
  1428. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1429. # then reset the temporary list that stored that solid_geometry
  1430. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1431. tools_storage[current_uid]['data']['name'] = name
  1432. cleared_geo[:] = []
  1433. geo_obj.options["cnctooldia"] = str(tool_dia)
  1434. # this turn on the FlatCAMCNCJob plot for multiple tools
  1435. geo_obj.multigeo = True
  1436. geo_obj.multitool = True
  1437. geo_obj.tools.clear()
  1438. geo_obj.tools = dict(tools_storage)
  1439. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1440. has_solid_geo = 0
  1441. for tooluid in geo_obj.tools:
  1442. if geo_obj.tools[tooluid]['solid_geometry']:
  1443. has_solid_geo += 1
  1444. if has_solid_geo == 0:
  1445. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1446. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1447. "Change the painting parameters and try again."))
  1448. return
  1449. # Experimental...
  1450. # print("Indexing...", end=' ')
  1451. # geo_obj.make_index()
  1452. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1453. def job_thread(app_obj):
  1454. try:
  1455. if self.rest_cb.isChecked():
  1456. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1457. else:
  1458. app_obj.new_object("geometry", name, gen_paintarea)
  1459. except Exception as e:
  1460. proc.done()
  1461. traceback.print_stack()
  1462. return
  1463. proc.done()
  1464. # focus on Selected Tab
  1465. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1466. self.app.inform.emit(_("Polygon Paint started ..."))
  1467. # Promise object with the new name
  1468. self.app.collection.promise(name)
  1469. # Background
  1470. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1471. def paint_poly_area(self, obj, sel_obj,
  1472. tooldia=None,
  1473. overlap=None,
  1474. order=None,
  1475. margin=None,
  1476. method=None,
  1477. outname=None,
  1478. connect=None,
  1479. contour=None,
  1480. tools_storage=None):
  1481. """
  1482. Paints all polygons in this object that are within the sel_obj object
  1483. :param obj: painted object
  1484. :param sel_obj: paint only what is inside this object bounds
  1485. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1486. :param overlap: value by which the paths will overlap
  1487. :param order: if the tools are ordered and how
  1488. :param margin: a border around painting area
  1489. :param outname: name of the resulting object
  1490. :param connect: Connect lines to avoid tool lifts.
  1491. :param contour: Paint around the edges.
  1492. :param method: choice out of 'seed', 'normal', 'lines'
  1493. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1494. Usage of the different one is related to when this function is called from a TcL command.
  1495. :return:
  1496. """
  1497. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1498. if margin is not None:
  1499. paint_margin = margin
  1500. else:
  1501. try:
  1502. paint_margin = float(self.paintmargin_entry.get_value())
  1503. except ValueError:
  1504. # try to convert comma to decimal point. if it's still not working error message and return
  1505. try:
  1506. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1507. except ValueError:
  1508. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1509. "use a number."))
  1510. return
  1511. proc = self.app.proc_container.new(_("Painting polygon..."))
  1512. name = outname if outname is not None else self.obj_name + "_paint"
  1513. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1514. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1515. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1516. order = order if order is not None else self.order_radio.get_value()
  1517. sorted_tools = []
  1518. if tooldia is not None:
  1519. try:
  1520. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1521. except AttributeError:
  1522. if not isinstance(tooldia, list):
  1523. sorted_tools = [float(tooldia)]
  1524. else:
  1525. sorted_tools = tooldia
  1526. else:
  1527. for row in range(self.tools_table.rowCount()):
  1528. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1529. if tools_storage is not None:
  1530. tools_storage = tools_storage
  1531. else:
  1532. tools_storage = self.paint_tools
  1533. def recurse(geometry, reset=True):
  1534. """
  1535. Creates a list of non-iterable linear geometry objects.
  1536. Results are placed in self.flat_geometry
  1537. :param geometry: Shapely type or list or list of list of such.
  1538. :param reset: Clears the contents of self.flat_geometry.
  1539. """
  1540. if geometry is None:
  1541. return
  1542. if reset:
  1543. self.flat_geometry = []
  1544. # ## If iterable, expand recursively.
  1545. try:
  1546. for geo in geometry:
  1547. if geo is not None:
  1548. recurse(geometry=geo, reset=False)
  1549. # ## Not iterable, do the actual indexing and add.
  1550. except TypeError:
  1551. if isinstance(geometry, LinearRing):
  1552. g = Polygon(geometry)
  1553. self.flat_geometry.append(g)
  1554. else:
  1555. self.flat_geometry.append(geometry)
  1556. return self.flat_geometry
  1557. # Initializes the new geometry object
  1558. def gen_paintarea(geo_obj, app_obj):
  1559. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1560. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1561. tool_dia = None
  1562. if order == 'fwd':
  1563. sorted_tools.sort(reverse=False)
  1564. elif order == 'rev':
  1565. sorted_tools.sort(reverse=True)
  1566. else:
  1567. pass
  1568. # this is were heavy lifting is done and creating the geometry to be painted
  1569. geo_to_paint = []
  1570. if not isinstance(obj.solid_geometry, list):
  1571. target_geo = [obj.solid_geometry]
  1572. else:
  1573. target_geo = obj.solid_geometry
  1574. for poly in target_geo:
  1575. new_pol = poly.intersection(sel_obj)
  1576. geo_to_paint.append(new_pol)
  1577. try:
  1578. a, b, c, d = self.paint_bounds(geo_to_paint)
  1579. geo_obj.options['xmin'] = a
  1580. geo_obj.options['ymin'] = b
  1581. geo_obj.options['xmax'] = c
  1582. geo_obj.options['ymax'] = d
  1583. except Exception as e:
  1584. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1585. return
  1586. total_geometry = []
  1587. current_uid = int(1)
  1588. geo_obj.solid_geometry = []
  1589. for tool_dia in sorted_tools:
  1590. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1591. for k, v in tools_storage.items():
  1592. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1593. current_uid = int(k)
  1594. break
  1595. for geo in recurse(geo_to_paint):
  1596. try:
  1597. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1598. if not isinstance(geo, Polygon):
  1599. continue
  1600. poly_buf = geo.buffer(-paint_margin)
  1601. if paint_method == "seed":
  1602. # Type(cp) == FlatCAMRTreeStorage | None
  1603. cp = self.clear_polygon2(poly_buf,
  1604. tooldia=tool_dia,
  1605. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1606. overlap=over,
  1607. contour=cont,
  1608. connect=conn)
  1609. elif paint_method == "lines":
  1610. # Type(cp) == FlatCAMRTreeStorage | None
  1611. cp = self.clear_polygon3(poly_buf,
  1612. tooldia=tool_dia,
  1613. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1614. overlap=over,
  1615. contour=cont,
  1616. connect=conn)
  1617. else:
  1618. # Type(cp) == FlatCAMRTreeStorage | None
  1619. cp = self.clear_polygon(poly_buf,
  1620. tooldia=tool_dia,
  1621. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1622. overlap=over,
  1623. contour=cont,
  1624. connect=conn)
  1625. if cp is not None:
  1626. total_geometry += list(cp.get_objects())
  1627. except Exception as e:
  1628. log.debug("Could not Paint the polygons. %s" % str(e))
  1629. self.app.inform.emit(
  1630. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1631. "Or a different Method of paint\n%s") % str(e))
  1632. return
  1633. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1634. # dictionary and then reset the temporary list that stored that solid_geometry
  1635. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1636. tools_storage[current_uid]['data']['name'] = name
  1637. total_geometry[:] = []
  1638. # delete tools with empty geometry
  1639. keys_to_delete = []
  1640. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1641. for uid in tools_storage:
  1642. # if the solid_geometry (type=list) is empty
  1643. if not tools_storage[uid]['solid_geometry']:
  1644. keys_to_delete.append(uid)
  1645. # actual delete of keys from the tools_storage dict
  1646. for k in keys_to_delete:
  1647. tools_storage.pop(k, None)
  1648. geo_obj.options["cnctooldia"] = str(tool_dia)
  1649. # this turn on the FlatCAMCNCJob plot for multiple tools
  1650. geo_obj.multigeo = True
  1651. geo_obj.multitool = True
  1652. geo_obj.tools.clear()
  1653. geo_obj.tools = dict(tools_storage)
  1654. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1655. has_solid_geo = 0
  1656. for tooluid in geo_obj.tools:
  1657. if geo_obj.tools[tooluid]['solid_geometry']:
  1658. has_solid_geo += 1
  1659. if has_solid_geo == 0:
  1660. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1661. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1662. "Change the painting parameters and try again."))
  1663. return
  1664. # Experimental...
  1665. # print("Indexing...", end=' ')
  1666. # geo_obj.make_index()
  1667. self.app.inform.emit(_("[success] Paint Area Done."))
  1668. # Initializes the new geometry object
  1669. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1670. assert isinstance(geo_obj, FlatCAMGeometry), \
  1671. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1672. tool_dia = None
  1673. sorted_tools.sort(reverse=True)
  1674. cleared_geo = []
  1675. current_uid = int(1)
  1676. geo_obj.solid_geometry = []
  1677. try:
  1678. a, b, c, d = obj.bounds()
  1679. geo_obj.options['xmin'] = a
  1680. geo_obj.options['ymin'] = b
  1681. geo_obj.options['xmax'] = c
  1682. geo_obj.options['ymax'] = d
  1683. except Exception as e:
  1684. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1685. return
  1686. for tool_dia in sorted_tools:
  1687. for geo in recurse(obj.solid_geometry):
  1688. try:
  1689. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1690. poly_buf = geo.buffer(-paint_margin)
  1691. cp = None
  1692. if paint_method == "standard":
  1693. # Type(cp) == FlatCAMRTreeStorage | None
  1694. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1695. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1696. overlap=over, contour=cont, connect=conn)
  1697. elif paint_method == "seed":
  1698. # Type(cp) == FlatCAMRTreeStorage | None
  1699. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1700. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1701. overlap=over, contour=cont, connect=conn)
  1702. elif paint_method == "lines":
  1703. # Type(cp) == FlatCAMRTreeStorage | None
  1704. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1705. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1706. overlap=over, contour=cont, connect=conn)
  1707. if cp is not None:
  1708. cleared_geo += list(cp.get_objects())
  1709. except Exception as e:
  1710. log.debug("Could not Paint the polygons. %s" % str(e))
  1711. self.app.inform.emit(
  1712. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1713. "Or a different Method of paint\n%s") % str(e))
  1714. return
  1715. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1716. for k, v in tools_storage.items():
  1717. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1718. current_uid = int(k)
  1719. break
  1720. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1721. # then reset the temporary list that stored that solid_geometry
  1722. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1723. tools_storage[current_uid]['data']['name'] = name
  1724. cleared_geo[:] = []
  1725. geo_obj.options["cnctooldia"] = str(tool_dia)
  1726. # this turn on the FlatCAMCNCJob plot for multiple tools
  1727. geo_obj.multigeo = True
  1728. geo_obj.multitool = True
  1729. geo_obj.tools.clear()
  1730. geo_obj.tools = dict(self.paint_tools)
  1731. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1732. has_solid_geo = 0
  1733. for tooluid in geo_obj.tools:
  1734. if geo_obj.tools[tooluid]['solid_geometry']:
  1735. has_solid_geo += 1
  1736. if has_solid_geo == 0:
  1737. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1738. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1739. "Change the painting parameters and try again."))
  1740. return
  1741. # Experimental...
  1742. # print("Indexing...", end=' ')
  1743. # geo_obj.make_index()
  1744. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1745. def job_thread(app_obj):
  1746. try:
  1747. if self.rest_cb.isChecked():
  1748. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1749. else:
  1750. app_obj.new_object("geometry", name, gen_paintarea)
  1751. except Exception as e:
  1752. proc.done()
  1753. traceback.print_stack()
  1754. return
  1755. proc.done()
  1756. # focus on Selected Tab
  1757. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1758. self.app.inform.emit(_("Polygon Paint started ..."))
  1759. # Promise object with the new name
  1760. self.app.collection.promise(name)
  1761. # Background
  1762. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1763. def paint_poly_ref(self, obj, sel_obj,
  1764. tooldia=None,
  1765. overlap=None,
  1766. order=None,
  1767. margin=None,
  1768. method=None,
  1769. outname=None,
  1770. connect=None,
  1771. contour=None,
  1772. tools_storage=None):
  1773. """
  1774. Paints all polygons in this object that are within the sel_obj object
  1775. :param obj: painted object
  1776. :param sel_obj: paint only what is inside this object bounds
  1777. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1778. :param overlap: value by which the paths will overlap
  1779. :param order: if the tools are ordered and how
  1780. :param margin: a border around painting area
  1781. :param outname: name of the resulting object
  1782. :param connect: Connect lines to avoid tool lifts.
  1783. :param contour: Paint around the edges.
  1784. :param method: choice out of 'seed', 'normal', 'lines'
  1785. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1786. Usage of the different one is related to when this function is called from a TcL command.
  1787. :return:
  1788. """
  1789. geo = sel_obj.solid_geometry
  1790. try:
  1791. if isinstance(geo, MultiPolygon):
  1792. env_obj = geo.convex_hull
  1793. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  1794. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  1795. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1796. else:
  1797. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1798. env_obj = env_obj.convex_hull
  1799. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  1800. except Exception as e:
  1801. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1802. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1803. return
  1804. self.paint_poly_area(obj=obj,
  1805. sel_obj=sel_rect,
  1806. tooldia=tooldia,
  1807. overlap=overlap,
  1808. order=order,
  1809. margin=margin,
  1810. method=method,
  1811. outname=outname,
  1812. connect=connect,
  1813. contour=contour,
  1814. tools_storage=tools_storage)
  1815. @staticmethod
  1816. def paint_bounds(geometry):
  1817. def bounds_rec(o):
  1818. if type(o) is list:
  1819. minx = Inf
  1820. miny = Inf
  1821. maxx = -Inf
  1822. maxy = -Inf
  1823. for k in o:
  1824. try:
  1825. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1826. except Exception as e:
  1827. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1828. return
  1829. minx = min(minx, minx_)
  1830. miny = min(miny, miny_)
  1831. maxx = max(maxx, maxx_)
  1832. maxy = max(maxy, maxy_)
  1833. return minx, miny, maxx, maxy
  1834. else:
  1835. # it's a Shapely object, return it's bounds
  1836. return o.bounds
  1837. return bounds_rec(geometry)
  1838. def reset_fields(self):
  1839. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))