ToolPaint.py 78 KB

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