ToolNonCopperClear.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified by: 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. import time
  12. from shapely.geometry import base
  13. import gettext
  14. import FlatCAMTranslation as fcTranslate
  15. import builtins
  16. fcTranslate.apply_language('strings')
  17. if '_' not in builtins.__dict__:
  18. _ = gettext.gettext
  19. class NonCopperClear(FlatCAMTool, Gerber):
  20. toolName = _("Non-Copper Clearing")
  21. def __init__(self, app):
  22. self.app = app
  23. FlatCAMTool.__init__(self, app)
  24. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  25. self.tools_frame = QtWidgets.QFrame()
  26. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  27. self.layout.addWidget(self.tools_frame)
  28. self.tools_box = QtWidgets.QVBoxLayout()
  29. self.tools_box.setContentsMargins(0, 0, 0, 0)
  30. self.tools_frame.setLayout(self.tools_box)
  31. # ## Title
  32. title_label = QtWidgets.QLabel("%s" % self.toolName)
  33. title_label.setStyleSheet("""
  34. QLabel
  35. {
  36. font-size: 16px;
  37. font-weight: bold;
  38. }
  39. """)
  40. self.tools_box.addWidget(title_label)
  41. # ## Form Layout
  42. form_layout = QtWidgets.QFormLayout()
  43. self.tools_box.addLayout(form_layout)
  44. # ################################################
  45. # ##### Type of object to be copper cleaned ######
  46. # ################################################
  47. self.type_obj_combo = QtWidgets.QComboBox()
  48. self.type_obj_combo.addItem("Gerber")
  49. self.type_obj_combo.addItem("Excellon")
  50. self.type_obj_combo.addItem("Geometry")
  51. # we get rid of item1 ("Excellon") as it is not suitable
  52. self.type_obj_combo.view().setRowHidden(1, True)
  53. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  54. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  55. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  56. self.type_obj_combo_label.setToolTip(
  57. _("Specify the type of object to be cleared of excess copper.\n"
  58. "It can be of type: Gerber or Geometry.\n"
  59. "What is selected here will dictate the kind\n"
  60. "of objects that will populate the 'Object' combobox.")
  61. )
  62. self.type_obj_combo_label.setMinimumWidth(60)
  63. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  64. # ################################################
  65. # ##### The object to be copper cleaned ##########
  66. # ################################################
  67. self.object_combo = QtWidgets.QComboBox()
  68. self.object_combo.setModel(self.app.collection)
  69. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  70. self.object_combo.setCurrentIndex(1)
  71. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  72. self.object_label.setToolTip(_("Object to be cleared of excess copper."))
  73. form_layout.addRow(self.object_label, self.object_combo)
  74. e_lab_0 = QtWidgets.QLabel('')
  75. form_layout.addRow(e_lab_0)
  76. # ### Tools ## ##
  77. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  78. self.tools_table_label.setToolTip(
  79. _("Tools pool from which the algorithm\n"
  80. "will pick the ones used for copper clearing.")
  81. )
  82. self.tools_box.addWidget(self.tools_table_label)
  83. self.tools_table = FCTable()
  84. self.tools_box.addWidget(self.tools_table)
  85. self.tools_table.setColumnCount(5)
  86. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), '', _("Operation")])
  87. self.tools_table.setColumnHidden(3, True)
  88. self.tools_table.setSortingEnabled(False)
  89. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  90. self.tools_table.horizontalHeaderItem(0).setToolTip(
  91. _("This is the Tool Number.\n"
  92. "Non copper clearing will start with the tool with the biggest \n"
  93. "diameter, continuing until there are no more tools.\n"
  94. "Only tools that create NCC clearing geometry will still be present\n"
  95. "in the resulting geometry. This is because with some tools\n"
  96. "this function will not be able to create painting geometry.")
  97. )
  98. self.tools_table.horizontalHeaderItem(1).setToolTip(
  99. _("Tool Diameter. It's value (in current FlatCAM units)\n"
  100. "is the cut width into the material."))
  101. self.tools_table.horizontalHeaderItem(2).setToolTip(
  102. _("The Tool Type (TT) can be:\n"
  103. "- Circular with 1 ... 4 teeth -> it is informative only. Being circular,\n"
  104. "the cut width in material is exactly the tool diameter.\n"
  105. "- Ball -> informative only and make reference to the Ball type endmill.\n"
  106. "- V-Shape -> it will disable de Z-Cut parameter in the resulting geometry UI form\n"
  107. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and\n"
  108. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such\n"
  109. "as the cut width into material will be equal with the value in the Tool Diameter\n"
  110. "column of this table.\n"
  111. "Choosing the 'V-Shape' Tool Type automatically will select the Operation Type\n"
  112. "in the resulting geometry as Isolation."))
  113. self.tools_table.horizontalHeaderItem(4).setToolTip(
  114. _("The 'Operation' can be:\n"
  115. "- Isolation -> will ensure that the non-copper clearing is always complete.\n"
  116. "If it's not successful then the non-copper clearing will fail, too.\n"
  117. "- Clear -> the regular non-copper clearing."))
  118. self.ncc_order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  119. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  120. "'No' --> means that the used order is the one in the tool table\n"
  121. "'Forward' --> means that the tools will be ordered from small to big\n"
  122. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  123. "WARNING: using rest machining will automatically set the order\n"
  124. "in reverse and disable this control."))
  125. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  126. {'label': _('Forward'), 'value': 'fwd'},
  127. {'label': _('Reverse'), 'value': 'rev'}])
  128. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  129. "'No' --> means that the used order is the one in the tool table\n"
  130. "'Forward' --> means that the tools will be ordered from small to big\n"
  131. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  132. "WARNING: using rest machining will automatically set the order\n"
  133. "in reverse and disable this control."))
  134. form = QtWidgets.QFormLayout()
  135. self.tools_box.addLayout(form)
  136. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  137. form.addRow(self.ncc_order_label, self.ncc_order_radio)
  138. # ### Add a new Tool ####
  139. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  140. self.addtool_entry_lbl.setToolTip(
  141. _("Diameter for the new tool to add in the Tool Table")
  142. )
  143. self.addtool_entry = FCEntry2()
  144. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  145. grid2 = QtWidgets.QGridLayout()
  146. self.tools_box.addLayout(grid2)
  147. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  148. self.addtool_btn.setToolTip(
  149. _("Add a new tool to the Tool Table\n"
  150. "with the diameter specified above.")
  151. )
  152. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  153. # self.copytool_btn.setToolTip(
  154. # "Copy a selection of tools in the Tool Table\n"
  155. # "by first selecting a row in the Tool Table."
  156. # )
  157. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  158. self.deltool_btn.setToolTip(
  159. _("Delete a selection of tools in the Tool Table\n"
  160. "by first selecting a row(s) in the Tool Table.")
  161. )
  162. grid2.addWidget(self.addtool_btn, 0, 0)
  163. # grid2.addWidget(self.copytool_btn, 0, 1)
  164. grid2.addWidget(self.deltool_btn, 0, 2)
  165. self.empty_label_0 = QtWidgets.QLabel('')
  166. self.tools_box.addWidget(self.empty_label_0)
  167. grid3 = QtWidgets.QGridLayout()
  168. self.tools_box.addLayout(grid3)
  169. e_lab_1 = QtWidgets.QLabel('<b>%s:</b>' % _("Parameters"))
  170. grid3.addWidget(e_lab_1, 0, 0)
  171. nccoverlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  172. nccoverlabel.setToolTip(
  173. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  174. "Example:\n"
  175. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  176. "Adjust the value starting with lower values\n"
  177. "and increasing it if areas that should be cleared are still \n"
  178. "not cleared.\n"
  179. "Lower values = faster processing, faster execution on PCB.\n"
  180. "Higher values = slow processing and slow execution on CNC\n"
  181. "due of too many paths.")
  182. )
  183. grid3.addWidget(nccoverlabel, 1, 0)
  184. self.ncc_overlap_entry = FCEntry()
  185. grid3.addWidget(self.ncc_overlap_entry, 1, 1)
  186. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  187. nccmarginlabel.setToolTip(
  188. _("Bounding box margin.")
  189. )
  190. grid3.addWidget(nccmarginlabel, 2, 0)
  191. self.ncc_margin_entry = FCEntry()
  192. grid3.addWidget(self.ncc_margin_entry, 2, 1)
  193. # Method
  194. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  195. methodlabel.setToolTip(
  196. _("Algorithm for non-copper clearing:<BR>"
  197. "<B>Standard</B>: Fixed step inwards.<BR>"
  198. "<B>Seed-based</B>: Outwards from seed.<BR>"
  199. "<B>Line-based</B>: Parallel lines.")
  200. )
  201. grid3.addWidget(methodlabel, 3, 0)
  202. self.ncc_method_radio = RadioSet([
  203. {"label": _("Standard"), "value": "standard"},
  204. {"label": _("Seed-based"), "value": "seed"},
  205. {"label": _("Straight lines"), "value": "lines"}
  206. ], orientation='vertical', stretch=False)
  207. grid3.addWidget(self.ncc_method_radio, 3, 1)
  208. # Connect lines
  209. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  210. pathconnectlabel.setToolTip(
  211. _("Draw lines between resulting\n"
  212. "segments to minimize tool lifts.")
  213. )
  214. grid3.addWidget(pathconnectlabel, 4, 0)
  215. self.ncc_connect_cb = FCCheckBox()
  216. grid3.addWidget(self.ncc_connect_cb, 4, 1)
  217. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  218. contourlabel.setToolTip(
  219. _("Cut around the perimeter of the polygon\n"
  220. "to trim rough edges.")
  221. )
  222. grid3.addWidget(contourlabel, 5, 0)
  223. self.ncc_contour_cb = FCCheckBox()
  224. grid3.addWidget(self.ncc_contour_cb, 5, 1)
  225. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  226. restlabel.setToolTip(
  227. _("If checked, use 'rest machining'.\n"
  228. "Basically it will clear copper outside PCB features,\n"
  229. "using the biggest tool and continue with the next tools,\n"
  230. "from bigger to smaller, to clear areas of copper that\n"
  231. "could not be cleared by previous tool, until there is\n"
  232. "no more copper to clear or there are no more tools.\n"
  233. "If not checked, use the standard algorithm.")
  234. )
  235. grid3.addWidget(restlabel, 6, 0)
  236. self.ncc_rest_cb = FCCheckBox()
  237. grid3.addWidget(self.ncc_rest_cb, 6, 1)
  238. # ## NCC Offset choice
  239. self.ncc_offset_choice_label = QtWidgets.QLabel('%s:' % _("Offset"))
  240. self.ncc_offset_choice_label.setToolTip(
  241. _("If used, it will add an offset to the copper features.\n"
  242. "The copper clearing will finish to a distance\n"
  243. "from the copper features.\n"
  244. "The value can be between 0 and 10 FlatCAM units.")
  245. )
  246. grid3.addWidget(self.ncc_offset_choice_label, 7, 0)
  247. self.ncc_choice_offset_cb = FCCheckBox()
  248. grid3.addWidget(self.ncc_choice_offset_cb, 7, 1)
  249. # ## NCC Offset value
  250. self.ncc_offset_label = QtWidgets.QLabel('%s:' % _("Offset value"))
  251. self.ncc_offset_label.setToolTip(
  252. _("If used, it will add an offset to the copper features.\n"
  253. "The copper clearing will finish to a distance\n"
  254. "from the copper features.\n"
  255. "The value can be between 0 and 10 FlatCAM units.")
  256. )
  257. grid3.addWidget(self.ncc_offset_label, 8, 0)
  258. self.ncc_offset_spinner = FCDoubleSpinner()
  259. self.ncc_offset_spinner.set_range(0.00, 10.00)
  260. self.ncc_offset_spinner.set_precision(4)
  261. self.ncc_offset_spinner.setWrapping(True)
  262. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  263. if units == 'MM':
  264. self.ncc_offset_spinner.setSingleStep(0.1)
  265. else:
  266. self.ncc_offset_spinner.setSingleStep(0.01)
  267. grid3.addWidget(self.ncc_offset_spinner, 8, 1)
  268. self.ncc_offset_label.hide()
  269. self.ncc_offset_spinner.hide()
  270. # ## Reference
  271. self.reference_radio = RadioSet([
  272. {'label': _('Itself'), 'value': 'itself'},
  273. {"label": _("Area Selection"), "value": "area"},
  274. {'label': _("Reference Object"), 'value': 'box'}
  275. ], orientation='vertical', stretch=False)
  276. self.reference_label = QtWidgets.QLabel(_("Reference:"))
  277. self.reference_label.setToolTip(
  278. _("- 'Itself' - the non copper clearing extent\n"
  279. "is based on the object that is copper cleared.\n "
  280. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  281. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  282. "- 'Reference Object' - will do non copper clearing within the area\n"
  283. "specified by another object.")
  284. )
  285. grid3.addWidget(self.reference_label, 9, 0)
  286. grid3.addWidget(self.reference_radio, 9, 1)
  287. form1 = QtWidgets.QFormLayout()
  288. self.tools_box.addLayout(form1)
  289. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  290. self.box_combo_type_label.setToolTip(
  291. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  292. "It can be Gerber, Excellon or Geometry.")
  293. )
  294. self.box_combo_type = QtWidgets.QComboBox()
  295. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  296. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  297. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  298. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  299. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  300. self.box_combo_label.setToolTip(
  301. _("The FlatCAM object to be used as non copper clearing reference.")
  302. )
  303. self.box_combo = QtWidgets.QComboBox()
  304. self.box_combo.setModel(self.app.collection)
  305. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  306. self.box_combo.setCurrentIndex(1)
  307. form1.addRow(self.box_combo_label, self.box_combo)
  308. self.box_combo.hide()
  309. self.box_combo_label.hide()
  310. self.box_combo_type.hide()
  311. self.box_combo_type_label.hide()
  312. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  313. self.generate_ncc_button.setToolTip(
  314. _("Create the Geometry Object\n"
  315. "for non-copper routing.")
  316. )
  317. self.tools_box.addWidget(self.generate_ncc_button)
  318. self.tools_box.addStretch()
  319. self.tools_table.setupContextMenu()
  320. self.tools_table.addContextMenu(
  321. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  322. self.tools_table.addContextMenu(
  323. "Delete", lambda:
  324. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  325. self.units = ''
  326. self.ncc_tools = {}
  327. self.tooluid = 0
  328. # store here the default data for Geometry Data
  329. self.default_data = {}
  330. self.obj_name = ""
  331. self.ncc_obj = None
  332. self.sel_rect = []
  333. self.bound_obj_name = ""
  334. self.bound_obj = None
  335. self.first_click = False
  336. self.cursor_pos = None
  337. self.mouse_is_dragging = False
  338. # store here solid_geometry when there are tool with isolation job
  339. self.solid_geometry = []
  340. self.addtool_btn.clicked.connect(self.on_tool_add)
  341. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  342. self.deltool_btn.clicked.connect(self.on_tool_delete)
  343. self.generate_ncc_button.clicked.connect(self.on_ncc_click)
  344. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  345. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  346. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  347. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  348. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  349. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  350. def on_type_obj_index_changed(self, index):
  351. obj_type = self.type_obj_combo.currentIndex()
  352. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  353. self.object_combo.setCurrentIndex(0)
  354. def install(self, icon=None, separator=None, **kwargs):
  355. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  356. def run(self, toggle=True):
  357. self.app.report_usage("ToolNonCopperClear()")
  358. if toggle:
  359. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  360. if self.app.ui.splitter.sizes()[0] == 0:
  361. self.app.ui.splitter.setSizes([1, 1])
  362. else:
  363. try:
  364. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  365. # if tab is populated with the tool but it does not have the focus, focus on it
  366. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  367. # focus on Tool Tab
  368. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  369. else:
  370. self.app.ui.splitter.setSizes([0, 1])
  371. except AttributeError:
  372. pass
  373. else:
  374. if self.app.ui.splitter.sizes()[0] == 0:
  375. self.app.ui.splitter.setSizes([1, 1])
  376. FlatCAMTool.run(self)
  377. self.set_tool_ui()
  378. # reset those objects on a new run
  379. self.ncc_obj = None
  380. self.bound_obj = None
  381. self.obj_name = ''
  382. self.bound_obj_name = ''
  383. self.build_ui()
  384. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  385. def set_tool_ui(self):
  386. self.tools_frame.show()
  387. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  388. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  389. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  390. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  391. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  392. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  393. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  394. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  395. # init the working variables
  396. self.default_data.clear()
  397. self.default_data.update({
  398. "name": '_ncc',
  399. "plot": self.app.defaults["geometry_plot"],
  400. "cutz": self.app.defaults["geometry_cutz"],
  401. "vtipdia": 0.1,
  402. "vtipangle": 30,
  403. "travelz": self.app.defaults["geometry_travelz"],
  404. "feedrate": self.app.defaults["geometry_feedrate"],
  405. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  406. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  407. "dwell": self.app.defaults["geometry_dwell"],
  408. "dwelltime": self.app.defaults["geometry_dwelltime"],
  409. "multidepth": self.app.defaults["geometry_multidepth"],
  410. "ppname_g": self.app.defaults["geometry_ppname_g"],
  411. "depthperpass": self.app.defaults["geometry_depthperpass"],
  412. "extracut": self.app.defaults["geometry_extracut"],
  413. "toolchange": self.app.defaults["geometry_toolchange"],
  414. "toolchangez": self.app.defaults["geometry_toolchangez"],
  415. "endz": self.app.defaults["geometry_endz"],
  416. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  417. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  418. "startz": self.app.defaults["geometry_startz"],
  419. "tooldia": self.app.defaults["tools_painttooldia"],
  420. "paintmargin": self.app.defaults["tools_paintmargin"],
  421. "paintmethod": self.app.defaults["tools_paintmethod"],
  422. "selectmethod": self.app.defaults["tools_selectmethod"],
  423. "pathconnect": self.app.defaults["tools_pathconnect"],
  424. "paintcontour": self.app.defaults["tools_paintcontour"],
  425. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  426. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  427. "nccmargin": self.app.defaults["tools_nccmargin"],
  428. "nccmethod": self.app.defaults["tools_nccmethod"],
  429. "nccconnect": self.app.defaults["tools_nccconnect"],
  430. "ncccontour": self.app.defaults["tools_ncccontour"],
  431. "nccrest": self.app.defaults["tools_nccrest"]
  432. })
  433. try:
  434. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  435. except Exception as e:
  436. log.error("At least one tool diameter needed. "
  437. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  438. return
  439. self.tooluid = 0
  440. self.ncc_tools.clear()
  441. for tool_dia in dias:
  442. self.tooluid += 1
  443. self.ncc_tools.update({
  444. int(self.tooluid): {
  445. 'tooldia': float('%.4f' % tool_dia),
  446. 'offset': 'Path',
  447. 'offset_value': 0.0,
  448. 'type': 'Iso',
  449. 'tool_type': 'V',
  450. 'operation': 'clear',
  451. 'data': dict(self.default_data),
  452. 'solid_geometry': []
  453. }
  454. })
  455. self.obj_name = ""
  456. self.ncc_obj = None
  457. self.bound_obj_name = ""
  458. self.bound_obj = None
  459. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  460. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  461. def build_ui(self):
  462. self.ui_disconnect()
  463. # updated units
  464. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  465. if self.units == "IN":
  466. self.addtool_entry.set_value(0.039)
  467. else:
  468. self.addtool_entry.set_value(1)
  469. sorted_tools = []
  470. for k, v in self.ncc_tools.items():
  471. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  472. order = self.ncc_order_radio.get_value()
  473. if order == 'fwd':
  474. sorted_tools.sort(reverse=False)
  475. elif order == 'rev':
  476. sorted_tools.sort(reverse=True)
  477. else:
  478. pass
  479. n = len(sorted_tools)
  480. self.tools_table.setRowCount(n)
  481. tool_id = 0
  482. for tool_sorted in sorted_tools:
  483. for tooluid_key, tooluid_value in self.ncc_tools.items():
  484. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  485. tool_id += 1
  486. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  487. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  488. row_no = tool_id - 1
  489. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  490. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  491. # There are no drill bits in MM with more than 3 decimals diameter
  492. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  493. if self.units == 'MM':
  494. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  495. else:
  496. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  497. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  498. tool_type_item = QtWidgets.QComboBox()
  499. for item in self.tool_type_item_options:
  500. tool_type_item.addItem(item)
  501. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  502. idx = tool_type_item.findText(tooluid_value['tool_type'])
  503. tool_type_item.setCurrentIndex(idx)
  504. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  505. operation_type = QtWidgets.QComboBox()
  506. operation_type.addItem('iso')
  507. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  508. operation_type.addItem('clear')
  509. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  510. op_idx = operation_type.findText(tooluid_value['operation'])
  511. operation_type.setCurrentIndex(op_idx)
  512. self.tools_table.setItem(row_no, 1, dia) # Diameter
  513. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  514. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  515. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  516. self.tools_table.setCellWidget(row_no, 4, operation_type)
  517. # make the diameter column editable
  518. for row in range(tool_id):
  519. self.tools_table.item(row, 1).setFlags(
  520. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  521. # all the tools are selected by default
  522. self.tools_table.selectColumn(0)
  523. #
  524. self.tools_table.resizeColumnsToContents()
  525. self.tools_table.resizeRowsToContents()
  526. vertical_header = self.tools_table.verticalHeader()
  527. vertical_header.hide()
  528. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  529. horizontal_header = self.tools_table.horizontalHeader()
  530. horizontal_header.setMinimumSectionSize(10)
  531. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  532. horizontal_header.resizeSection(0, 20)
  533. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  534. # self.tools_table.setSortingEnabled(True)
  535. # sort by tool diameter
  536. # self.tools_table.sortItems(1)
  537. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  538. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  539. self.ui_connect()
  540. def ui_connect(self):
  541. self.tools_table.itemChanged.connect(self.on_tool_edit)
  542. def ui_disconnect(self):
  543. try:
  544. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  545. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  546. except (TypeError, AttributeError):
  547. pass
  548. def on_combo_box_type(self):
  549. obj_type = self.box_combo_type.currentIndex()
  550. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  551. self.box_combo.setCurrentIndex(0)
  552. def on_toggle_reference(self):
  553. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  554. self.box_combo.hide()
  555. self.box_combo_label.hide()
  556. self.box_combo_type.hide()
  557. self.box_combo_type_label.hide()
  558. else:
  559. self.box_combo.show()
  560. self.box_combo_label.show()
  561. self.box_combo_type.show()
  562. self.box_combo_type_label.show()
  563. def on_offset_choice(self, state):
  564. if state:
  565. self.ncc_offset_label.show()
  566. self.ncc_offset_spinner.show()
  567. else:
  568. self.ncc_offset_label.hide()
  569. self.ncc_offset_spinner.hide()
  570. def on_order_changed(self, order):
  571. if order != 'no':
  572. self.build_ui()
  573. def on_rest_machining_check(self, state):
  574. if state:
  575. self.ncc_order_radio.set_value('rev')
  576. self.ncc_order_label.setDisabled(True)
  577. self.ncc_order_radio.setDisabled(True)
  578. else:
  579. self.ncc_order_label.setDisabled(False)
  580. self.ncc_order_radio.setDisabled(False)
  581. def on_tool_add(self, dia=None, muted=None):
  582. self.ui_disconnect()
  583. if dia:
  584. tool_dia = dia
  585. else:
  586. try:
  587. tool_dia = float(self.addtool_entry.get_value())
  588. except ValueError:
  589. # try to convert comma to decimal point. if it's still not working error message and return
  590. try:
  591. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  592. except ValueError:
  593. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  594. "use a number."))
  595. return
  596. if tool_dia is None:
  597. self.build_ui()
  598. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  599. return
  600. if tool_dia == 0:
  601. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, "
  602. "in Float format."))
  603. return
  604. # construct a list of all 'tooluid' in the self.tools
  605. tool_uid_list = []
  606. for tooluid_key in self.ncc_tools:
  607. tool_uid_item = int(tooluid_key)
  608. tool_uid_list.append(tool_uid_item)
  609. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  610. if not tool_uid_list:
  611. max_uid = 0
  612. else:
  613. max_uid = max(tool_uid_list)
  614. self.tooluid = int(max_uid + 1)
  615. tool_dias = []
  616. for k, v in self.ncc_tools.items():
  617. for tool_v in v.keys():
  618. if tool_v == 'tooldia':
  619. tool_dias.append(float('%.4f' % v[tool_v]))
  620. if float('%.4f' % tool_dia) in tool_dias:
  621. if muted is None:
  622. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  623. self.tools_table.itemChanged.connect(self.on_tool_edit)
  624. return
  625. else:
  626. if muted is None:
  627. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  628. self.ncc_tools.update({
  629. int(self.tooluid): {
  630. 'tooldia': float('%.4f' % tool_dia),
  631. 'offset': 'Path',
  632. 'offset_value': 0.0,
  633. 'type': 'Iso',
  634. 'tool_type': 'V',
  635. 'operation': 'clear',
  636. 'data': dict(self.default_data),
  637. 'solid_geometry': []
  638. }
  639. })
  640. self.build_ui()
  641. def on_tool_edit(self):
  642. self.ui_disconnect()
  643. tool_dias = []
  644. for k, v in self.ncc_tools.items():
  645. for tool_v in v.keys():
  646. if tool_v == 'tooldia':
  647. tool_dias.append(float('%.4f' % v[tool_v]))
  648. for row in range(self.tools_table.rowCount()):
  649. try:
  650. new_tool_dia = float(self.tools_table.item(row, 1).text())
  651. except ValueError:
  652. # try to convert comma to decimal point. if it's still not working error message and return
  653. try:
  654. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  655. except ValueError:
  656. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  657. "use a number."))
  658. return
  659. tooluid = int(self.tools_table.item(row, 3).text())
  660. # identify the tool that was edited and get it's tooluid
  661. if new_tool_dia not in tool_dias:
  662. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  663. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  664. self.build_ui()
  665. return
  666. else:
  667. # identify the old tool_dia and restore the text in tool table
  668. for k, v in self.ncc_tools.items():
  669. if k == tooluid:
  670. old_tool_dia = v['tooldia']
  671. break
  672. restore_dia_item = self.tools_table.item(row, 1)
  673. restore_dia_item.setText(str(old_tool_dia))
  674. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  675. "New diameter value is already in the Tool Table."))
  676. self.build_ui()
  677. def on_tool_delete(self, rows_to_delete=None, all=None):
  678. self.ui_disconnect()
  679. deleted_tools_list = []
  680. if all:
  681. self.paint_tools.clear()
  682. self.build_ui()
  683. return
  684. if rows_to_delete:
  685. try:
  686. for row in rows_to_delete:
  687. tooluid_del = int(self.tools_table.item(row, 3).text())
  688. deleted_tools_list.append(tooluid_del)
  689. except TypeError:
  690. deleted_tools_list.append(rows_to_delete)
  691. for t in deleted_tools_list:
  692. self.ncc_tools.pop(t, None)
  693. self.build_ui()
  694. return
  695. try:
  696. if self.tools_table.selectedItems():
  697. for row_sel in self.tools_table.selectedItems():
  698. row = row_sel.row()
  699. if row < 0:
  700. continue
  701. tooluid_del = int(self.tools_table.item(row, 3).text())
  702. deleted_tools_list.append(tooluid_del)
  703. for t in deleted_tools_list:
  704. self.ncc_tools.pop(t, None)
  705. except AttributeError:
  706. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  707. return
  708. except Exception as e:
  709. log.debug(str(e))
  710. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  711. self.build_ui()
  712. def on_ncc_click(self):
  713. # init values for the next usage
  714. self.reset_usage()
  715. self.app.report_usage(_("on_paint_button_click"))
  716. try:
  717. overlap = float(self.ncc_overlap_entry.get_value())
  718. except ValueError:
  719. # try to convert comma to decimal point. if it's still not working error message and return
  720. try:
  721. overlap = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  722. except ValueError:
  723. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  724. "use a number."))
  725. return
  726. if overlap >= 1 or overlap < 0:
  727. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  728. "0 (inclusive) and 1 (exclusive), "))
  729. return
  730. connect = self.ncc_connect_cb.get_value()
  731. contour = self.ncc_contour_cb.get_value()
  732. has_offset = self.ncc_choice_offset_cb.isChecked()
  733. rest = self.ncc_rest_cb.get_value()
  734. self.obj_name = self.object_combo.currentText()
  735. # Get source object.
  736. try:
  737. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  738. except Exception as e:
  739. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  740. return "Could not retrieve object: %s" % self.obj_name
  741. if self.ncc_obj is None:
  742. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.ncc_obj)
  743. return
  744. # use the selected tools in the tool table; get diameters for non-copper clear
  745. iso_dia_list = list()
  746. # use the selected tools in the tool table; get diameters for non-copper clear
  747. ncc_dia_list = list()
  748. if self.tools_table.selectedItems():
  749. for x in self.tools_table.selectedItems():
  750. try:
  751. tooldia = float(self.tools_table.item(x.row(), 1).text())
  752. except ValueError:
  753. # try to convert comma to decimal point. if it's still not working error message and return
  754. try:
  755. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  756. except ValueError:
  757. self.app.inform.emit(_("[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  758. "use a number."))
  759. continue
  760. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso':
  761. iso_dia_list.append(tooldia)
  762. else:
  763. ncc_dia_list.append(tooldia)
  764. else:
  765. self.app.inform.emit(_("[ERROR_NOTCL] No selected tools in Tool Table."))
  766. return
  767. o_name = '%s_ncc' % self.obj_name
  768. select_method = self.reference_radio.get_value()
  769. if select_method == 'itself':
  770. self.bound_obj_name = self.object_combo.currentText()
  771. # Get source object.
  772. try:
  773. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  774. except Exception as e:
  775. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  776. return "Could not retrieve object: %s" % self.obj_name
  777. self.clear_copper(ncc_obj=self.ncc_obj,
  778. ncctooldia=ncc_dia_list,
  779. isotooldia=iso_dia_list,
  780. has_offset=has_offset,
  781. outname=o_name,
  782. overlap=overlap,
  783. connect=connect,
  784. contour=contour,
  785. rest=rest)
  786. elif select_method == 'area':
  787. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the area."))
  788. # use the first tool in the tool table; get the diameter
  789. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  790. # To be called after clicking on the plot.
  791. def on_mouse_release(event):
  792. # do clear area only for left mouse clicks
  793. if event.button == 1:
  794. if self.first_click is False:
  795. self.first_click = True
  796. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  797. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  798. if self.app.grid_status() == True:
  799. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  800. else:
  801. self.app.inform.emit(_("Zone added. Right click to finish."))
  802. self.app.delete_selection_shape()
  803. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  804. if self.app.grid_status() == True:
  805. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  806. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  807. x1, y1 = curr_pos[0], curr_pos[1]
  808. pt1 = (x0, y0)
  809. pt2 = (x1, y0)
  810. pt3 = (x1, y1)
  811. pt4 = (x0, y1)
  812. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  813. modifiers = QtWidgets.QApplication.keyboardModifiers()
  814. if modifiers == QtCore.Qt.ShiftModifier:
  815. mod_key = 'Shift'
  816. elif modifiers == QtCore.Qt.ControlModifier:
  817. mod_key = 'Control'
  818. else:
  819. mod_key = None
  820. if mod_key == self.app.defaults["global_mselect_key"]:
  821. self.first_click = False
  822. return
  823. self.sel_rect = cascaded_union(self.sel_rect)
  824. self.clear_copper(ncc_obj=self.ncc_obj,
  825. sel_obj=self.bound_obj,
  826. ncctooldia=ncc_dia_list,
  827. isotooldia=iso_dia_list,
  828. has_offset=has_offset,
  829. outname=o_name,
  830. overlap=overlap,
  831. connect=connect,
  832. contour=contour,
  833. rest=rest)
  834. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  835. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  836. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  837. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  838. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  839. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  840. self.first_click = False
  841. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  842. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  843. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  844. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  845. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  846. self.sel_rect = cascaded_union(self.sel_rect)
  847. self.clear_copper(ncc_obj=self.ncc_obj,
  848. sel_obj=self.bound_obj,
  849. ncctooldia=ncc_dia_list,
  850. isotooldia=iso_dia_list,
  851. has_offset=has_offset,
  852. outname=o_name,
  853. overlap=overlap,
  854. connect=connect,
  855. contour=contour,
  856. rest=rest)
  857. # called on mouse move
  858. def on_mouse_move(event):
  859. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  860. self.app.app_cursor.enabled = False
  861. if event.button == 2:
  862. if event.is_dragging is True:
  863. self.mouse_is_dragging = True
  864. else:
  865. self.mouse_is_dragging = False
  866. if self.app.grid_status() == True:
  867. self.app.app_cursor.enabled = True
  868. # Update cursor
  869. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  870. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  871. symbol='++', edge_color='black', size=20)
  872. if self.first_click:
  873. self.app.delete_selection_shape()
  874. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  875. coords=(curr_pos[0], curr_pos[1]),
  876. face_alpha=0.0)
  877. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  878. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  879. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  880. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  881. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  882. elif select_method == 'box':
  883. self.bound_obj_name = self.box_combo.currentText()
  884. # Get source object.
  885. try:
  886. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  887. except Exception as e:
  888. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.bound_obj_name)
  889. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  890. self.clear_copper(ncc_obj=self.ncc_obj,
  891. sel_obj=self.bound_obj,
  892. ncctooldia=ncc_dia_list,
  893. isotooldia=iso_dia_list,
  894. has_offset=has_offset,
  895. outname=o_name,
  896. overlap=overlap,
  897. connect=connect,
  898. contour=contour,
  899. rest=rest)
  900. def clear_copper(self, ncc_obj,
  901. sel_obj=None,
  902. ncctooldia=None,
  903. isotooldia=None,
  904. margin=None,
  905. has_offset=None,
  906. offset=None,
  907. select_method=None,
  908. outname=None,
  909. overlap=None,
  910. connect=None,
  911. contour=None,
  912. order=None,
  913. method=None,
  914. rest=None,
  915. tools_storage=None):
  916. """
  917. Clear the excess copper from the entire object.
  918. :param ncc_obj: ncc cleared object
  919. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  920. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  921. :param overlap: value by which the paths will overlap
  922. :param order: if the tools are ordered and how
  923. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  924. another object
  925. :param has_offset: True if an offset is needed
  926. :param offset: distance from the copper features where the copper clearing is stopping
  927. :param margin: a border around cleared area
  928. :param outname: name of the resulting object
  929. :param connect: Connect lines to avoid tool lifts.
  930. :param contour: Paint around the edges.
  931. :param method: choice out of 'seed', 'normal', 'lines'
  932. :param rest: True if to use rest-machining
  933. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  934. Usage of the different one is related to when this function is called from a TcL command.
  935. :return:
  936. """
  937. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  938. # #####################################################################
  939. # ####### Read the parameters #########################################
  940. # #####################################################################
  941. ncc_method = method if method else self.ncc_method_radio.get_value()
  942. if margin is not None:
  943. ncc_margin = margin
  944. else:
  945. try:
  946. ncc_margin = float(self.ncc_margin_entry.get_value())
  947. except ValueError:
  948. # try to convert comma to decimal point. if it's still not working error message and return
  949. try:
  950. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  951. except ValueError:
  952. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  953. "use a number."))
  954. return
  955. if select_method is not None:
  956. ncc_select = select_method
  957. else:
  958. ncc_select = self.reference_radio.get_value()
  959. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  960. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  961. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  962. order = order if order else self.ncc_order_radio.get_value()
  963. if tools_storage is not None:
  964. tools_storage = tools_storage
  965. else:
  966. tools_storage = self.ncc_tools
  967. ncc_offset = 0.0
  968. if has_offset is True:
  969. if offset is not None:
  970. ncc_offset = offset
  971. else:
  972. try:
  973. ncc_offset = float(self.ncc_offset_spinner.get_value())
  974. except ValueError:
  975. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  976. "use a number."))
  977. return
  978. # ######################################################################################################
  979. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  980. # ######################################################################################################
  981. sorted_tools = []
  982. if ncctooldia is not None:
  983. try:
  984. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  985. except AttributeError:
  986. if not isinstance(ncctooldia, list):
  987. sorted_tools = [float(ncctooldia)]
  988. else:
  989. sorted_tools = ncctooldia
  990. else:
  991. for row in range(self.tools_table.rowCount()):
  992. if self.tools_table.cellWidget(row, 1).currentText() == 'clear':
  993. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  994. # ##############################################################################################################
  995. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  996. # ##############################################################################################################
  997. try:
  998. if sel_obj is None or sel_obj == 'itself':
  999. ncc_sel_obj = ncc_obj
  1000. else:
  1001. ncc_sel_obj = sel_obj
  1002. bounding_box = None
  1003. if ncc_select == 'itself':
  1004. geo_n = ncc_sel_obj.solid_geometry
  1005. try:
  1006. if isinstance(geo_n, MultiPolygon):
  1007. env_obj = geo_n.convex_hull
  1008. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1009. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1010. env_obj = cascaded_union(geo_n)
  1011. else:
  1012. env_obj = cascaded_union(geo_n)
  1013. env_obj = env_obj.convex_hull
  1014. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1015. except Exception as e:
  1016. log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1017. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1018. return
  1019. elif ncc_select == 'area':
  1020. geo_n = MultiPolygon(self.sel_rect)
  1021. try:
  1022. __ = iter(geo_n)
  1023. except TypeError:
  1024. geo_n = [geo_n]
  1025. geo_buff_list = []
  1026. for poly in geo_n:
  1027. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1028. bounding_box = cascaded_union(geo_buff_list)
  1029. elif ncc_select == 'box':
  1030. geo_n = ncc_sel_obj.solid_geometry
  1031. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1032. try:
  1033. __ = iter(geo_n)
  1034. except TypeError:
  1035. geo_n = [geo_n]
  1036. geo_buff_list = []
  1037. for poly in geo_n:
  1038. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1039. bounding_box = cascaded_union(geo_buff_list)
  1040. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1041. geo_n = cascaded_union(geo_n).convex_hull
  1042. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1043. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1044. else:
  1045. self.app.inform.emit(_("[ERROR_NOTCL] The reference object type is not supported."))
  1046. return 'fail'
  1047. except Exception as e:
  1048. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1049. return 'fail'
  1050. # ########################################################################################################
  1051. # set the name for the future Geometry object
  1052. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1053. # ########################################################################################################
  1054. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1055. if rest_machining_choice is True:
  1056. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1057. else:
  1058. name = outname if outname is not None else self.obj_name + "_ncc"
  1059. # ##########################################################################################
  1060. # Initializes the new geometry object ######################################################
  1061. # ##########################################################################################
  1062. def gen_clear_area(geo_obj, app_obj):
  1063. assert isinstance(geo_obj, FlatCAMGeometry), \
  1064. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1065. if order == 'fwd':
  1066. sorted_tools.sort(reverse=False)
  1067. elif order == 'rev':
  1068. sorted_tools.sort(reverse=True)
  1069. else:
  1070. pass
  1071. cleared_geo = []
  1072. # Already cleared area
  1073. cleared = MultiPolygon()
  1074. # flag for polygons not cleared
  1075. app_obj.poly_not_cleared = False
  1076. # Generate area for each tool
  1077. offset = sum(sorted_tools)
  1078. current_uid = int(1)
  1079. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1080. # ###################################################################################################
  1081. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1082. # ###################################################################################################
  1083. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1084. sol_geo = ncc_obj.solid_geometry
  1085. if has_offset is True:
  1086. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1087. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1088. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1089. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1090. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1091. isolated_geo = []
  1092. self.solid_geometry = ncc_obj.solid_geometry
  1093. # if milling type is climb then the move is counter-clockwise around features
  1094. milling_type = 'cl'
  1095. for tool_iso in isotooldia:
  1096. new_geometry = []
  1097. if milling_type == 'cl':
  1098. isolated_geo = self.generate_envelope(tool_iso, 1)
  1099. else:
  1100. isolated_geo = self.generate_envelope(tool_iso, 0)
  1101. if isolated_geo == 'fail':
  1102. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1103. else:
  1104. try:
  1105. for geo_elem in isolated_geo:
  1106. if isinstance(geo_elem, Polygon):
  1107. for ring in self.poly2rings(geo_elem):
  1108. new_geo = ring.intersection(bounding_box)
  1109. if new_geo and not new_geo.is_empty:
  1110. new_geometry.append(new_geo)
  1111. elif isinstance(geo_elem, MultiPolygon):
  1112. for poly in geo_elem:
  1113. for ring in self.poly2rings(poly):
  1114. new_geo = ring.intersection(bounding_box)
  1115. if new_geo and not new_geo.is_empty:
  1116. new_geometry.append(new_geo)
  1117. elif isinstance(geo_elem, LineString):
  1118. new_geo = geo_elem.intersection(bounding_box)
  1119. if new_geo:
  1120. if not new_geo.is_empty:
  1121. new_geometry.append(new_geo)
  1122. elif isinstance(geo_elem, MultiLineString):
  1123. for line_elem in geo_elem:
  1124. new_geo = line_elem.intersection(bounding_box)
  1125. if new_geo and not new_geo.is_empty:
  1126. new_geometry.append(new_geo)
  1127. except TypeError:
  1128. if isinstance(isolated_geo, Polygon):
  1129. for ring in self.poly2rings(isolated_geo):
  1130. new_geo = ring.intersection(bounding_box)
  1131. if new_geo:
  1132. if not new_geo.is_empty:
  1133. new_geometry.append(new_geo)
  1134. elif isinstance(isolated_geo, LineString):
  1135. new_geo = isolated_geo.intersection(bounding_box)
  1136. if new_geo and not new_geo.is_empty:
  1137. new_geometry.append(new_geo)
  1138. elif isinstance(isolated_geo, MultiLineString):
  1139. for line_elem in isolated_geo:
  1140. new_geo = line_elem.intersection(bounding_box)
  1141. if new_geo and not new_geo.is_empty:
  1142. new_geometry.append(new_geo)
  1143. for k, v in tools_storage.items():
  1144. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1145. current_uid = int(k)
  1146. # add the solid_geometry to the current too in self.paint_tools dictionary
  1147. # and then reset the temporary list that stored that solid_geometry
  1148. v['solid_geometry'] = deepcopy(new_geometry)
  1149. v['data']['name'] = name
  1150. break
  1151. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1152. sol_geo = cascaded_union(isolated_geo)
  1153. if has_offset is True:
  1154. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1155. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1156. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1157. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1158. elif isinstance(ncc_obj, FlatCAMGeometry):
  1159. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1160. if has_offset is True:
  1161. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1162. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1163. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1164. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1165. else:
  1166. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1167. return
  1168. if empty.is_empty:
  1169. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1170. return 'fail'
  1171. if type(empty) is Polygon:
  1172. empty = MultiPolygon([empty])
  1173. for tool in sorted_tools:
  1174. app_obj.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1175. cleared_geo[:] = []
  1176. # Get remaining tools offset
  1177. offset -= (tool - 1e-12)
  1178. # Area to clear
  1179. area = empty.buffer(-offset)
  1180. try:
  1181. area = area.difference(cleared)
  1182. except Exception as e:
  1183. continue
  1184. # Transform area to MultiPolygon
  1185. if type(area) is Polygon:
  1186. area = MultiPolygon([area])
  1187. if area.geoms:
  1188. if len(area.geoms) > 0:
  1189. for p in area.geoms:
  1190. try:
  1191. if ncc_method == 'standard':
  1192. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1193. overlap=overlap, contour=contour, connect=connect)
  1194. elif ncc_method == 'seed':
  1195. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1196. overlap=overlap, contour=contour, connect=connect)
  1197. else:
  1198. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1199. overlap=overlap, contour=contour, connect=connect)
  1200. if cp:
  1201. cleared_geo += list(cp.get_objects())
  1202. except Exception as e:
  1203. log.warning("Polygon can not be cleared. %s" % str(e))
  1204. app_obj.poly_not_cleared = True
  1205. continue
  1206. # check if there is a geometry at all in the cleared geometry
  1207. if cleared_geo:
  1208. # Overall cleared area
  1209. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1210. tool / 1.999999)
  1211. # clean-up cleared geo
  1212. cleared = cleared.buffer(0)
  1213. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1214. # solid_geometry
  1215. for k, v in tools_storage.items():
  1216. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1217. current_uid = int(k)
  1218. # add the solid_geometry to the current too in self.paint_tools dictionary
  1219. # and then reset the temporary list that stored that solid_geometry
  1220. v['solid_geometry'] = deepcopy(cleared_geo)
  1221. v['data']['name'] = name
  1222. break
  1223. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1224. else:
  1225. log.debug("There are no geometries in the cleared polygon.")
  1226. # delete tools with empty geometry
  1227. keys_to_delete = []
  1228. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1229. for uid in tools_storage:
  1230. # if the solid_geometry (type=list) is empty
  1231. if not tools_storage[uid]['solid_geometry']:
  1232. keys_to_delete.append(uid)
  1233. # actual delete of keys from the tools_storage dict
  1234. for k in keys_to_delete:
  1235. tools_storage.pop(k, None)
  1236. geo_obj.options["cnctooldia"] = str(tool)
  1237. geo_obj.multigeo = True
  1238. geo_obj.tools.clear()
  1239. geo_obj.tools = dict(tools_storage)
  1240. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1241. has_solid_geo = 0
  1242. for tooluid in geo_obj.tools:
  1243. if geo_obj.tools[tooluid]['solid_geometry']:
  1244. has_solid_geo += 1
  1245. if has_solid_geo == 0:
  1246. app_obj.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1247. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1248. "Change the painting parameters and try again."))
  1249. return
  1250. # Experimental...
  1251. # print("Indexing...", end=' ')
  1252. # geo_obj.make_index()
  1253. self.app.inform.emit(_("[success] Non-Copper clear all done."))
  1254. # ###########################################################################################
  1255. # Initializes the new geometry object for the case of the rest-machining ####################
  1256. # ###########################################################################################
  1257. def gen_clear_area_rest(geo_obj, app_obj):
  1258. assert isinstance(geo_obj, FlatCAMGeometry), \
  1259. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1260. sorted_tools.sort(reverse=True)
  1261. cleared_geo = []
  1262. cleared_by_last_tool = []
  1263. rest_geo = []
  1264. current_uid = 1
  1265. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1266. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1267. app_obj.poly_not_cleared = True
  1268. # ###################################################################################################
  1269. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1270. # ###################################################################################################
  1271. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1272. sol_geo = ncc_obj.solid_geometry
  1273. if has_offset is True:
  1274. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1275. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1276. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1277. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1278. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1279. isolated_geo = []
  1280. self.solid_geometry = ncc_obj.solid_geometry
  1281. # if milling type is climb then the move is counter-clockwise around features
  1282. milling_type = 'cl'
  1283. for tool_iso in isotooldia:
  1284. new_geometry = []
  1285. if milling_type == 'cl':
  1286. isolated_geo = self.generate_envelope(tool_iso, 1)
  1287. else:
  1288. isolated_geo = self.generate_envelope(tool_iso, 0)
  1289. if isolated_geo == 'fail':
  1290. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1291. else:
  1292. try:
  1293. for geo_elem in isolated_geo:
  1294. if isinstance(geo_elem, Polygon):
  1295. for ring in self.poly2rings(geo_elem):
  1296. new_geo = ring.intersection(bounding_box)
  1297. if new_geo and not new_geo.is_empty:
  1298. new_geometry.append(new_geo)
  1299. elif isinstance(geo_elem, MultiPolygon):
  1300. for poly in geo_elem:
  1301. for ring in self.poly2rings(poly):
  1302. new_geo = ring.intersection(bounding_box)
  1303. if new_geo and not new_geo.is_empty:
  1304. new_geometry.append(new_geo)
  1305. elif isinstance(geo_elem, LineString):
  1306. new_geo = geo_elem.intersection(bounding_box)
  1307. if new_geo:
  1308. if not new_geo.is_empty:
  1309. new_geometry.append(new_geo)
  1310. elif isinstance(geo_elem, MultiLineString):
  1311. for line_elem in geo_elem:
  1312. new_geo = line_elem.intersection(bounding_box)
  1313. if new_geo and not new_geo.is_empty:
  1314. new_geometry.append(new_geo)
  1315. except TypeError:
  1316. if isinstance(isolated_geo, Polygon):
  1317. for ring in self.poly2rings(isolated_geo):
  1318. new_geo = ring.intersection(bounding_box)
  1319. if new_geo:
  1320. if not new_geo.is_empty:
  1321. new_geometry.append(new_geo)
  1322. elif isinstance(isolated_geo, LineString):
  1323. new_geo = isolated_geo.intersection(bounding_box)
  1324. if new_geo and not new_geo.is_empty:
  1325. new_geometry.append(new_geo)
  1326. elif isinstance(isolated_geo, MultiLineString):
  1327. for line_elem in isolated_geo:
  1328. new_geo = line_elem.intersection(bounding_box)
  1329. if new_geo and not new_geo.is_empty:
  1330. new_geometry.append(new_geo)
  1331. for k, v in tools_storage.items():
  1332. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1333. current_uid = int(k)
  1334. # add the solid_geometry to the current too in self.paint_tools dictionary
  1335. # and then reset the temporary list that stored that solid_geometry
  1336. v['solid_geometry'] = deepcopy(new_geometry)
  1337. v['data']['name'] = name
  1338. break
  1339. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1340. sol_geo = cascaded_union(isolated_geo)
  1341. if has_offset is True:
  1342. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1343. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1344. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1345. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1346. elif isinstance(ncc_obj, FlatCAMGeometry):
  1347. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1348. if has_offset is True:
  1349. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1350. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1351. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1352. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1353. else:
  1354. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1355. return
  1356. if empty.is_empty:
  1357. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1358. return 'fail'
  1359. if type(empty) is Polygon:
  1360. empty = MultiPolygon([empty])
  1361. area = empty.buffer(0)
  1362. # Generate area for each tool
  1363. while sorted_tools:
  1364. tool = sorted_tools.pop(0)
  1365. app_obj.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1366. tool_used = tool - 1e-12
  1367. cleared_geo[:] = []
  1368. # Area to clear
  1369. for poly in cleared_by_last_tool:
  1370. try:
  1371. area = area.difference(poly)
  1372. except Exception as e:
  1373. pass
  1374. cleared_by_last_tool[:] = []
  1375. # Transform area to MultiPolygon
  1376. if type(area) is Polygon:
  1377. area = MultiPolygon([area])
  1378. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1379. # and rest_geo it's a list
  1380. allparts = [p.buffer(0) for p in area.geoms]
  1381. allparts += deepcopy(rest_geo)
  1382. rest_geo[:] = []
  1383. area = MultiPolygon(deepcopy(allparts))
  1384. allparts[:] = []
  1385. if area.geoms:
  1386. if len(area.geoms) > 0:
  1387. for p in area.geoms:
  1388. try:
  1389. if ncc_method == 'standard':
  1390. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1391. overlap=overlap, contour=contour, connect=connect)
  1392. elif ncc_method == 'seed':
  1393. cp = self.clear_polygon2(p, tool_used,
  1394. self.app.defaults["gerber_circle_steps"],
  1395. overlap=overlap, contour=contour, connect=connect)
  1396. else:
  1397. cp = self.clear_polygon3(p, tool_used,
  1398. self.app.defaults["gerber_circle_steps"],
  1399. overlap=overlap, contour=contour, connect=connect)
  1400. cleared_geo.append(list(cp.get_objects()))
  1401. except:
  1402. log.warning("Polygon can't be cleared.")
  1403. # this polygon should be added to a list and then try clear it with a smaller tool
  1404. rest_geo.append(p)
  1405. # check if there is a geometry at all in the cleared geometry
  1406. if cleared_geo:
  1407. # Overall cleared area
  1408. cleared_area = list(self.flatten_list(cleared_geo))
  1409. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1410. # for p in cleared_area])
  1411. # here we store the poly's already processed in the original geometry by the current tool
  1412. # into cleared_by_last_tool list
  1413. # this will be sustracted from the original geometry_to_be_cleared and make data for
  1414. # the next tool
  1415. buffer_value = tool_used / 2
  1416. for p in cleared_area:
  1417. poly = p.buffer(buffer_value)
  1418. cleared_by_last_tool.append(poly)
  1419. # find the tooluid associated with the current tool_dia so we know
  1420. # where to add the tool solid_geometry
  1421. for k, v in tools_storage.items():
  1422. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1423. current_uid = int(k)
  1424. # add the solid_geometry to the current too in self.paint_tools dictionary
  1425. # and then reset the temporary list that stored that solid_geometry
  1426. v['solid_geometry'] = deepcopy(cleared_area)
  1427. v['data']['name'] = name
  1428. cleared_area[:] = []
  1429. break
  1430. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1431. else:
  1432. log.debug("There are no geometries in the cleared polygon.")
  1433. geo_obj.multigeo = True
  1434. geo_obj.options["cnctooldia"] = str(tool)
  1435. # check to see if geo_obj.tools is empty
  1436. # it will be updated only if there is a solid_geometry for tools
  1437. if geo_obj.tools:
  1438. return
  1439. else:
  1440. # I will use this variable for this purpose although it was meant for something else
  1441. # signal that we have no geo in the object therefore don't create it
  1442. app_obj.poly_not_cleared = False
  1443. return "fail"
  1444. # ###########################################################################################
  1445. # Create the Job function and send it to the worker to be processed in another thread #######
  1446. # ###########################################################################################
  1447. def job_thread(app_obj):
  1448. try:
  1449. if rest_machining_choice is True:
  1450. app_obj.new_object("geometry", name, gen_clear_area_rest)
  1451. else:
  1452. app_obj.new_object("geometry", name, gen_clear_area)
  1453. except Exception as e:
  1454. proc.done()
  1455. traceback.print_stack()
  1456. return
  1457. proc.done()
  1458. # focus on Selected Tab
  1459. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1460. # Promise object with the new name
  1461. self.app.collection.promise(name)
  1462. # Background
  1463. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1464. # def on_ncc(self):
  1465. #
  1466. # # Prepare non-copper polygons
  1467. # if self.reference_radio.get_value() == 'area':
  1468. # geo_n = self.sel_rect
  1469. #
  1470. # geo_buff_list = []
  1471. # for poly in geo_n:
  1472. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1473. # bounding_box = cascaded_union(geo_buff_list)
  1474. # else:
  1475. # geo_n = self.bound_obj.solid_geometry
  1476. #
  1477. # try:
  1478. # if isinstance(geo_n, MultiPolygon):
  1479. # env_obj = geo_n.convex_hull
  1480. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1481. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1482. # env_obj = cascaded_union(geo_n)
  1483. # else:
  1484. # env_obj = cascaded_union(geo_n)
  1485. # env_obj = env_obj.convex_hull
  1486. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1487. # except Exception as e:
  1488. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1489. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1490. # return
  1491. #
  1492. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1493. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1494. # if self.ncc_choice_offset_cb.isChecked():
  1495. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1496. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1497. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1498. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1499. # else:
  1500. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1501. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1502. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1503. # if self.ncc_choice_offset_cb.isChecked():
  1504. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1505. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1506. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1507. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1508. # else:
  1509. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1510. # else:
  1511. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1512. # return
  1513. #
  1514. # if type(empty) is Polygon:
  1515. # empty = MultiPolygon([empty])
  1516. #
  1517. # if empty.is_empty:
  1518. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1519. # return
  1520. #
  1521. # # clear non copper using standard algorithm
  1522. # if clearing_method is False:
  1523. # self.clear_non_copper(
  1524. # empty=empty,
  1525. # over=over,
  1526. # pol_method=pol_method,
  1527. # connect=connect,
  1528. # contour=contour
  1529. # )
  1530. # # clear non copper using rest machining algorithm
  1531. # else:
  1532. # self.clear_non_copper_rest(
  1533. # empty=empty,
  1534. # over=over,
  1535. # pol_method=pol_method,
  1536. # connect=connect,
  1537. # contour=contour
  1538. # )
  1539. #
  1540. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1541. #
  1542. # name = outname if outname else self.obj_name + "_ncc"
  1543. #
  1544. # # Sort tools in descending order
  1545. # sorted_tools = []
  1546. # for k, v in self.ncc_tools.items():
  1547. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1548. #
  1549. # order = self.ncc_order_radio.get_value()
  1550. # if order == 'fwd':
  1551. # sorted_tools.sort(reverse=False)
  1552. # elif order == 'rev':
  1553. # sorted_tools.sort(reverse=True)
  1554. # else:
  1555. # pass
  1556. #
  1557. # # Do job in background
  1558. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1559. #
  1560. # def initialize(geo_obj, app_obj):
  1561. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1562. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1563. #
  1564. # cleared_geo = []
  1565. # # Already cleared area
  1566. # cleared = MultiPolygon()
  1567. #
  1568. # # flag for polygons not cleared
  1569. # app_obj.poly_not_cleared = False
  1570. #
  1571. # # Generate area for each tool
  1572. # offset = sum(sorted_tools)
  1573. # current_uid = int(1)
  1574. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1575. #
  1576. # for tool in sorted_tools:
  1577. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1578. # cleared_geo[:] = []
  1579. #
  1580. # # Get remaining tools offset
  1581. # offset -= (tool - 1e-12)
  1582. #
  1583. # # Area to clear
  1584. # area = empty.buffer(-offset)
  1585. # try:
  1586. # area = area.difference(cleared)
  1587. # except Exception as e:
  1588. # continue
  1589. #
  1590. # # Transform area to MultiPolygon
  1591. # if type(area) is Polygon:
  1592. # area = MultiPolygon([area])
  1593. #
  1594. # if area.geoms:
  1595. # if len(area.geoms) > 0:
  1596. # for p in area.geoms:
  1597. # try:
  1598. # if pol_method == 'standard':
  1599. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1600. # overlap=over, contour=contour, connect=connect)
  1601. # elif pol_method == 'seed':
  1602. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1603. # overlap=over, contour=contour, connect=connect)
  1604. # else:
  1605. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1606. # overlap=over, contour=contour, connect=connect)
  1607. # if cp:
  1608. # cleared_geo += list(cp.get_objects())
  1609. # except Exception as e:
  1610. # log.warning("Polygon can not be cleared. %s" % str(e))
  1611. # app_obj.poly_not_cleared = True
  1612. # continue
  1613. #
  1614. # # check if there is a geometry at all in the cleared geometry
  1615. # if cleared_geo:
  1616. # # Overall cleared area
  1617. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  1618. # tool / 1.999999)
  1619. #
  1620. # # clean-up cleared geo
  1621. # cleared = cleared.buffer(0)
  1622. #
  1623. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  1624. # # solid_geometry
  1625. # for k, v in self.ncc_tools.items():
  1626. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1627. # current_uid = int(k)
  1628. #
  1629. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1630. # # and then reset the temporary list that stored that solid_geometry
  1631. # v['solid_geometry'] = deepcopy(cleared_geo)
  1632. # v['data']['name'] = name
  1633. # break
  1634. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1635. # else:
  1636. # log.debug("There are no geometries in the cleared polygon.")
  1637. #
  1638. # geo_obj.options["cnctooldia"] = str(tool)
  1639. # geo_obj.multigeo = True
  1640. #
  1641. # def job_thread(app_obj):
  1642. # try:
  1643. # app_obj.new_object("geometry", name, initialize)
  1644. # except Exception as e:
  1645. # proc.done()
  1646. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  1647. # return
  1648. # proc.done()
  1649. #
  1650. # if app_obj.poly_not_cleared is False:
  1651. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  1652. # else:
  1653. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  1654. # 'Check the result.'))
  1655. # # reset the variable for next use
  1656. # app_obj.poly_not_cleared = False
  1657. #
  1658. # # focus on Selected Tab
  1659. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1660. #
  1661. # # Promise object with the new name
  1662. # self.app.collection.promise(name)
  1663. #
  1664. # # Background
  1665. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1666. #
  1667. # # clear copper with 'rest-machining' algorithm
  1668. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1669. #
  1670. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1671. #
  1672. # # Sort tools in descending order
  1673. # sorted_tools = []
  1674. # for k, v in self.ncc_tools.items():
  1675. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1676. # sorted_tools.sort(reverse=True)
  1677. #
  1678. # # Do job in background
  1679. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1680. #
  1681. # def initialize_rm(geo_obj, app_obj):
  1682. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1683. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1684. #
  1685. # cleared_geo = []
  1686. # cleared_by_last_tool = []
  1687. # rest_geo = []
  1688. # current_uid = 1
  1689. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1690. #
  1691. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1692. # app_obj.poly_not_cleared = True
  1693. #
  1694. # area = empty.buffer(0)
  1695. # # Generate area for each tool
  1696. # while sorted_tools:
  1697. # tool = sorted_tools.pop(0)
  1698. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1699. #
  1700. # tool_used = tool - 1e-12
  1701. # cleared_geo[:] = []
  1702. #
  1703. # # Area to clear
  1704. # for poly in cleared_by_last_tool:
  1705. # try:
  1706. # area = area.difference(poly)
  1707. # except Exception as e:
  1708. # pass
  1709. # cleared_by_last_tool[:] = []
  1710. #
  1711. # # Transform area to MultiPolygon
  1712. # if type(area) is Polygon:
  1713. # area = MultiPolygon([area])
  1714. #
  1715. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1716. # # and rest_geo it's a list
  1717. # allparts = [p.buffer(0) for p in area.geoms]
  1718. # allparts += deepcopy(rest_geo)
  1719. # rest_geo[:] = []
  1720. # area = MultiPolygon(deepcopy(allparts))
  1721. # allparts[:] = []
  1722. #
  1723. # if area.geoms:
  1724. # if len(area.geoms) > 0:
  1725. # for p in area.geoms:
  1726. # try:
  1727. # if pol_method == 'standard':
  1728. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1729. # overlap=over, contour=contour, connect=connect)
  1730. # elif pol_method == 'seed':
  1731. # cp = self.clear_polygon2(p, tool_used,
  1732. # self.app.defaults["gerber_circle_steps"],
  1733. # overlap=over, contour=contour, connect=connect)
  1734. # else:
  1735. # cp = self.clear_polygon3(p, tool_used,
  1736. # self.app.defaults["gerber_circle_steps"],
  1737. # overlap=over, contour=contour, connect=connect)
  1738. # cleared_geo.append(list(cp.get_objects()))
  1739. # except:
  1740. # log.warning("Polygon can't be cleared.")
  1741. # # this polygon should be added to a list and then try clear it with a smaller tool
  1742. # rest_geo.append(p)
  1743. #
  1744. # # check if there is a geometry at all in the cleared geometry
  1745. # if cleared_geo:
  1746. # # Overall cleared area
  1747. # cleared_area = list(self.flatten_list(cleared_geo))
  1748. #
  1749. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1750. # # for p in cleared_area])
  1751. #
  1752. # # here we store the poly's already processed in the original geometry by the current tool
  1753. # # into cleared_by_last_tool list
  1754. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  1755. # # the next tool
  1756. # buffer_value = tool_used / 2
  1757. # for p in cleared_area:
  1758. # poly = p.buffer(buffer_value)
  1759. # cleared_by_last_tool.append(poly)
  1760. #
  1761. # # find the tooluid associated with the current tool_dia so we know
  1762. # # where to add the tool solid_geometry
  1763. # for k, v in self.ncc_tools.items():
  1764. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1765. # current_uid = int(k)
  1766. #
  1767. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1768. # # and then reset the temporary list that stored that solid_geometry
  1769. # v['solid_geometry'] = deepcopy(cleared_area)
  1770. # v['data']['name'] = name
  1771. # cleared_area[:] = []
  1772. # break
  1773. #
  1774. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1775. # else:
  1776. # log.debug("There are no geometries in the cleared polygon.")
  1777. #
  1778. # geo_obj.multigeo = True
  1779. # geo_obj.options["cnctooldia"] = str(tool)
  1780. #
  1781. # # check to see if geo_obj.tools is empty
  1782. # # it will be updated only if there is a solid_geometry for tools
  1783. # if geo_obj.tools:
  1784. # return
  1785. # else:
  1786. # # I will use this variable for this purpose although it was meant for something else
  1787. # # signal that we have no geo in the object therefore don't create it
  1788. # app_obj.poly_not_cleared = False
  1789. # return "fail"
  1790. #
  1791. # def job_thread(app_obj):
  1792. # try:
  1793. # app_obj.new_object("geometry", name, initialize_rm)
  1794. # except Exception as e:
  1795. # proc.done()
  1796. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  1797. # return
  1798. #
  1799. # if app_obj.poly_not_cleared is True:
  1800. # app_obj.inform.emit('[success] NCC Tool finished.')
  1801. # # focus on Selected Tab
  1802. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1803. # else:
  1804. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  1805. # 'with current settings.'))
  1806. # # focus on Project Tab
  1807. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1808. # proc.done()
  1809. # # reset the variable for next use
  1810. # app_obj.poly_not_cleared = False
  1811. #
  1812. # # Promise object with the new name
  1813. # self.app.collection.promise(name)
  1814. #
  1815. # # Background
  1816. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1817. @staticmethod
  1818. def get_ncc_empty_area(target, boundary=None):
  1819. """
  1820. Returns the complement of target geometry within
  1821. the given boundary polygon. If not specified, it defaults to
  1822. the rectangular bounding box of target geometry.
  1823. """
  1824. if boundary is None:
  1825. boundary = target.envelope
  1826. return boundary.difference(target)
  1827. def reset_fields(self):
  1828. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1829. def reset_usage(self):
  1830. self.obj_name = ""
  1831. self.ncc_obj = None
  1832. self.bound_obj = None
  1833. self.first_click = False
  1834. self.cursor_pos = None
  1835. self.mouse_is_dragging = False
  1836. self.sel_rect = []
  1837. @staticmethod
  1838. def poly2rings(poly):
  1839. return [poly.exterior] + [interior for interior in poly.interiors]
  1840. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  1841. # isolation_geometry produces an envelope that is going on the left of the geometry
  1842. # (the copper features). To leave the least amount of burrs on the features
  1843. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1844. # the first pass is the one cutting all of the features, so it needs to be reversed
  1845. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1846. # to cut on the right side of the left over copper i.e on the left side of the features.
  1847. try:
  1848. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  1849. except Exception as e:
  1850. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  1851. return 'fail'
  1852. if invert:
  1853. try:
  1854. try:
  1855. pl = []
  1856. for p in geom:
  1857. if p is not None:
  1858. if isinstance(p, Polygon):
  1859. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1860. elif isinstance(p, LinearRing):
  1861. pl.append(Polygon(p.coords[::-1]))
  1862. geom = MultiPolygon(pl)
  1863. except TypeError:
  1864. if isinstance(geom, Polygon) and geom is not None:
  1865. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1866. elif isinstance(geom, LinearRing) and geom is not None:
  1867. geom = Polygon(geom.coords[::-1])
  1868. else:
  1869. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  1870. type(geom))
  1871. except Exception as e:
  1872. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  1873. return 'fail'
  1874. return geom