ToolPaint.py 103 KB

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