ToolPaint.py 82 KB

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