ToolNonCopperClear.py 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  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('%s:' % _('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. except Exception as e:
  1003. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1004. return 'fail'
  1005. bounding_box = None
  1006. if ncc_select == 'itself':
  1007. geo_n = ncc_sel_obj.solid_geometry
  1008. try:
  1009. if isinstance(geo_n, MultiPolygon):
  1010. env_obj = geo_n.convex_hull
  1011. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1012. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1013. env_obj = cascaded_union(geo_n)
  1014. else:
  1015. env_obj = cascaded_union(geo_n)
  1016. env_obj = env_obj.convex_hull
  1017. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1018. except Exception as e:
  1019. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1020. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1021. return 'fail'
  1022. elif ncc_select == 'area':
  1023. geo_n = cascaded_union(self.sel_rect)
  1024. try:
  1025. __ = iter(geo_n)
  1026. except Exception as e:
  1027. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1028. geo_n = [geo_n]
  1029. geo_buff_list = []
  1030. for poly in geo_n:
  1031. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1032. bounding_box = cascaded_union(geo_buff_list)
  1033. elif ncc_select == 'box':
  1034. geo_n = ncc_sel_obj.solid_geometry
  1035. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1036. try:
  1037. __ = iter(geo_n)
  1038. except Exception as e:
  1039. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1040. geo_n = [geo_n]
  1041. geo_buff_list = []
  1042. for poly in geo_n:
  1043. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1044. bounding_box = cascaded_union(geo_buff_list)
  1045. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1046. geo_n = cascaded_union(geo_n).convex_hull
  1047. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1048. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1049. else:
  1050. self.app.inform.emit(_("[ERROR_NOTCL] The reference object type is not supported."))
  1051. return 'fail'
  1052. # ########################################################################################################
  1053. # set the name for the future Geometry object
  1054. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1055. # ########################################################################################################
  1056. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1057. if rest_machining_choice is True:
  1058. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1059. else:
  1060. name = outname if outname is not None else self.obj_name + "_ncc"
  1061. # ##########################################################################################
  1062. # Initializes the new geometry object ######################################################
  1063. # ##########################################################################################
  1064. def gen_clear_area(geo_obj, app_obj):
  1065. assert isinstance(geo_obj, FlatCAMGeometry), \
  1066. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1067. if order == 'fwd':
  1068. sorted_tools.sort(reverse=False)
  1069. elif order == 'rev':
  1070. sorted_tools.sort(reverse=True)
  1071. else:
  1072. pass
  1073. cleared_geo = []
  1074. # Already cleared area
  1075. cleared = MultiPolygon()
  1076. # flag for polygons not cleared
  1077. app_obj.poly_not_cleared = False
  1078. # Generate area for each tool
  1079. offset = sum(sorted_tools)
  1080. current_uid = int(1)
  1081. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1082. # ###################################################################################################
  1083. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1084. # ###################################################################################################
  1085. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1086. sol_geo = ncc_obj.solid_geometry
  1087. if has_offset is True:
  1088. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1089. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1090. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1091. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1092. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1093. isolated_geo = []
  1094. self.solid_geometry = ncc_obj.solid_geometry
  1095. # if milling type is climb then the move is counter-clockwise around features
  1096. milling_type = 'cl'
  1097. for tool_iso in isotooldia:
  1098. new_geometry = []
  1099. if milling_type == 'cl':
  1100. isolated_geo = self.generate_envelope(tool_iso, 1)
  1101. else:
  1102. isolated_geo = self.generate_envelope(tool_iso, 0)
  1103. if isolated_geo == 'fail':
  1104. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1105. else:
  1106. try:
  1107. for geo_elem in isolated_geo:
  1108. if isinstance(geo_elem, Polygon):
  1109. for ring in self.poly2rings(geo_elem):
  1110. new_geo = ring.intersection(bounding_box)
  1111. if new_geo and not new_geo.is_empty:
  1112. new_geometry.append(new_geo)
  1113. elif isinstance(geo_elem, MultiPolygon):
  1114. for poly in geo_elem:
  1115. for ring in self.poly2rings(poly):
  1116. new_geo = ring.intersection(bounding_box)
  1117. if new_geo and not new_geo.is_empty:
  1118. new_geometry.append(new_geo)
  1119. elif isinstance(geo_elem, LineString):
  1120. new_geo = geo_elem.intersection(bounding_box)
  1121. if new_geo:
  1122. if not new_geo.is_empty:
  1123. new_geometry.append(new_geo)
  1124. elif isinstance(geo_elem, MultiLineString):
  1125. for line_elem in geo_elem:
  1126. new_geo = line_elem.intersection(bounding_box)
  1127. if new_geo and not new_geo.is_empty:
  1128. new_geometry.append(new_geo)
  1129. except TypeError:
  1130. if isinstance(isolated_geo, Polygon):
  1131. for ring in self.poly2rings(isolated_geo):
  1132. new_geo = ring.intersection(bounding_box)
  1133. if new_geo:
  1134. if not new_geo.is_empty:
  1135. new_geometry.append(new_geo)
  1136. elif isinstance(isolated_geo, LineString):
  1137. new_geo = isolated_geo.intersection(bounding_box)
  1138. if new_geo and not new_geo.is_empty:
  1139. new_geometry.append(new_geo)
  1140. elif isinstance(isolated_geo, MultiLineString):
  1141. for line_elem in isolated_geo:
  1142. new_geo = line_elem.intersection(bounding_box)
  1143. if new_geo and not new_geo.is_empty:
  1144. new_geometry.append(new_geo)
  1145. for k, v in tools_storage.items():
  1146. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1147. current_uid = int(k)
  1148. # add the solid_geometry to the current too in self.paint_tools dictionary
  1149. # and then reset the temporary list that stored that solid_geometry
  1150. v['solid_geometry'] = deepcopy(new_geometry)
  1151. v['data']['name'] = name
  1152. break
  1153. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1154. sol_geo = cascaded_union(isolated_geo)
  1155. if has_offset is True:
  1156. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1157. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1158. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1159. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1160. elif isinstance(ncc_obj, FlatCAMGeometry):
  1161. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1162. if has_offset is True:
  1163. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1164. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1165. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1166. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1167. else:
  1168. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1169. return
  1170. if empty.is_empty:
  1171. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1172. return 'fail'
  1173. if type(empty) is Polygon:
  1174. empty = MultiPolygon([empty])
  1175. for tool in sorted_tools:
  1176. app_obj.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1177. cleared_geo[:] = []
  1178. # Get remaining tools offset
  1179. offset -= (tool - 1e-12)
  1180. # Area to clear
  1181. area = empty.buffer(-offset)
  1182. try:
  1183. area = area.difference(cleared)
  1184. except Exception as e:
  1185. continue
  1186. # Transform area to MultiPolygon
  1187. if type(area) is Polygon:
  1188. area = MultiPolygon([area])
  1189. if area.geoms:
  1190. if len(area.geoms) > 0:
  1191. for p in area.geoms:
  1192. try:
  1193. if ncc_method == 'standard':
  1194. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1195. overlap=overlap, contour=contour, connect=connect)
  1196. elif ncc_method == 'seed':
  1197. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1198. overlap=overlap, contour=contour, connect=connect)
  1199. else:
  1200. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1201. overlap=overlap, contour=contour, connect=connect)
  1202. if cp:
  1203. cleared_geo += list(cp.get_objects())
  1204. except Exception as e:
  1205. log.warning("Polygon can not be cleared. %s" % str(e))
  1206. app_obj.poly_not_cleared = True
  1207. continue
  1208. # check if there is a geometry at all in the cleared geometry
  1209. if cleared_geo:
  1210. # Overall cleared area
  1211. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1212. tool / 1.999999)
  1213. # clean-up cleared geo
  1214. cleared = cleared.buffer(0)
  1215. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1216. # solid_geometry
  1217. for k, v in tools_storage.items():
  1218. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1219. current_uid = int(k)
  1220. # add the solid_geometry to the current too in self.paint_tools dictionary
  1221. # and then reset the temporary list that stored that solid_geometry
  1222. v['solid_geometry'] = deepcopy(cleared_geo)
  1223. v['data']['name'] = name
  1224. break
  1225. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1226. else:
  1227. log.debug("There are no geometries in the cleared polygon.")
  1228. # delete tools with empty geometry
  1229. keys_to_delete = []
  1230. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1231. for uid in tools_storage:
  1232. # if the solid_geometry (type=list) is empty
  1233. if not tools_storage[uid]['solid_geometry']:
  1234. keys_to_delete.append(uid)
  1235. # actual delete of keys from the tools_storage dict
  1236. for k in keys_to_delete:
  1237. tools_storage.pop(k, None)
  1238. geo_obj.options["cnctooldia"] = str(tool)
  1239. geo_obj.multigeo = True
  1240. geo_obj.tools.clear()
  1241. geo_obj.tools = dict(tools_storage)
  1242. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1243. has_solid_geo = 0
  1244. for tooluid in geo_obj.tools:
  1245. if geo_obj.tools[tooluid]['solid_geometry']:
  1246. has_solid_geo += 1
  1247. if has_solid_geo == 0:
  1248. app_obj.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1249. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1250. "Change the painting parameters and try again."))
  1251. return
  1252. # Experimental...
  1253. # print("Indexing...", end=' ')
  1254. # geo_obj.make_index()
  1255. self.app.inform.emit(_("[success] Non-Copper clear all done."))
  1256. # ###########################################################################################
  1257. # Initializes the new geometry object for the case of the rest-machining ####################
  1258. # ###########################################################################################
  1259. def gen_clear_area_rest(geo_obj, app_obj):
  1260. assert isinstance(geo_obj, FlatCAMGeometry), \
  1261. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1262. sorted_tools.sort(reverse=True)
  1263. cleared_geo = []
  1264. cleared_by_last_tool = []
  1265. rest_geo = []
  1266. current_uid = 1
  1267. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1268. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1269. app_obj.poly_not_cleared = True
  1270. # ###################################################################################################
  1271. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1272. # ###################################################################################################
  1273. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1274. sol_geo = ncc_obj.solid_geometry
  1275. if has_offset is True:
  1276. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1277. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1278. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1279. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1280. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1281. isolated_geo = []
  1282. self.solid_geometry = ncc_obj.solid_geometry
  1283. # if milling type is climb then the move is counter-clockwise around features
  1284. milling_type = 'cl'
  1285. for tool_iso in isotooldia:
  1286. new_geometry = []
  1287. if milling_type == 'cl':
  1288. isolated_geo = self.generate_envelope(tool_iso, 1)
  1289. else:
  1290. isolated_geo = self.generate_envelope(tool_iso, 0)
  1291. if isolated_geo == 'fail':
  1292. app_obj.inform.emit(_("[ERROR_NOTCL] Isolation geometry could not be generated."))
  1293. else:
  1294. try:
  1295. for geo_elem in isolated_geo:
  1296. if isinstance(geo_elem, Polygon):
  1297. for ring in self.poly2rings(geo_elem):
  1298. new_geo = ring.intersection(bounding_box)
  1299. if new_geo and not new_geo.is_empty:
  1300. new_geometry.append(new_geo)
  1301. elif isinstance(geo_elem, MultiPolygon):
  1302. for poly in geo_elem:
  1303. for ring in self.poly2rings(poly):
  1304. new_geo = ring.intersection(bounding_box)
  1305. if new_geo and not new_geo.is_empty:
  1306. new_geometry.append(new_geo)
  1307. elif isinstance(geo_elem, LineString):
  1308. new_geo = geo_elem.intersection(bounding_box)
  1309. if new_geo:
  1310. if not new_geo.is_empty:
  1311. new_geometry.append(new_geo)
  1312. elif isinstance(geo_elem, MultiLineString):
  1313. for line_elem in geo_elem:
  1314. new_geo = line_elem.intersection(bounding_box)
  1315. if new_geo and not new_geo.is_empty:
  1316. new_geometry.append(new_geo)
  1317. except TypeError:
  1318. if isinstance(isolated_geo, Polygon):
  1319. for ring in self.poly2rings(isolated_geo):
  1320. new_geo = ring.intersection(bounding_box)
  1321. if new_geo:
  1322. if not new_geo.is_empty:
  1323. new_geometry.append(new_geo)
  1324. elif isinstance(isolated_geo, LineString):
  1325. new_geo = isolated_geo.intersection(bounding_box)
  1326. if new_geo and not new_geo.is_empty:
  1327. new_geometry.append(new_geo)
  1328. elif isinstance(isolated_geo, MultiLineString):
  1329. for line_elem in isolated_geo:
  1330. new_geo = line_elem.intersection(bounding_box)
  1331. if new_geo and not new_geo.is_empty:
  1332. new_geometry.append(new_geo)
  1333. for k, v in tools_storage.items():
  1334. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1335. current_uid = int(k)
  1336. # add the solid_geometry to the current too in self.paint_tools dictionary
  1337. # and then reset the temporary list that stored that solid_geometry
  1338. v['solid_geometry'] = deepcopy(new_geometry)
  1339. v['data']['name'] = name
  1340. break
  1341. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1342. sol_geo = cascaded_union(isolated_geo)
  1343. if has_offset is True:
  1344. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1345. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1346. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1347. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1348. elif isinstance(ncc_obj, FlatCAMGeometry):
  1349. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1350. if has_offset is True:
  1351. app_obj.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1352. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1353. app_obj.inform.emit(_("[success] Buffering finished ..."))
  1354. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1355. else:
  1356. app_obj.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1357. return
  1358. if empty.is_empty:
  1359. app_obj.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1360. return 'fail'
  1361. if type(empty) is Polygon:
  1362. empty = MultiPolygon([empty])
  1363. area = empty.buffer(0)
  1364. # Generate area for each tool
  1365. while sorted_tools:
  1366. tool = sorted_tools.pop(0)
  1367. app_obj.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1368. tool_used = tool - 1e-12
  1369. cleared_geo[:] = []
  1370. # Area to clear
  1371. for poly in cleared_by_last_tool:
  1372. try:
  1373. area = area.difference(poly)
  1374. except Exception as e:
  1375. pass
  1376. cleared_by_last_tool[:] = []
  1377. # Transform area to MultiPolygon
  1378. if type(area) is Polygon:
  1379. area = MultiPolygon([area])
  1380. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1381. # and rest_geo it's a list
  1382. allparts = [p.buffer(0) for p in area.geoms]
  1383. allparts += deepcopy(rest_geo)
  1384. rest_geo[:] = []
  1385. area = MultiPolygon(deepcopy(allparts))
  1386. allparts[:] = []
  1387. if area.geoms:
  1388. if len(area.geoms) > 0:
  1389. for p in area.geoms:
  1390. try:
  1391. if ncc_method == 'standard':
  1392. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1393. overlap=overlap, contour=contour, connect=connect)
  1394. elif ncc_method == 'seed':
  1395. cp = self.clear_polygon2(p, tool_used,
  1396. self.app.defaults["gerber_circle_steps"],
  1397. overlap=overlap, contour=contour, connect=connect)
  1398. else:
  1399. cp = self.clear_polygon3(p, tool_used,
  1400. self.app.defaults["gerber_circle_steps"],
  1401. overlap=overlap, contour=contour, connect=connect)
  1402. cleared_geo.append(list(cp.get_objects()))
  1403. except:
  1404. log.warning("Polygon can't be cleared.")
  1405. # this polygon should be added to a list and then try clear it with a smaller tool
  1406. rest_geo.append(p)
  1407. # check if there is a geometry at all in the cleared geometry
  1408. if cleared_geo:
  1409. # Overall cleared area
  1410. cleared_area = list(self.flatten_list(cleared_geo))
  1411. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1412. # for p in cleared_area])
  1413. # here we store the poly's already processed in the original geometry by the current tool
  1414. # into cleared_by_last_tool list
  1415. # this will be sustracted from the original geometry_to_be_cleared and make data for
  1416. # the next tool
  1417. buffer_value = tool_used / 2
  1418. for p in cleared_area:
  1419. poly = p.buffer(buffer_value)
  1420. cleared_by_last_tool.append(poly)
  1421. # find the tooluid associated with the current tool_dia so we know
  1422. # where to add the tool solid_geometry
  1423. for k, v in tools_storage.items():
  1424. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1425. current_uid = int(k)
  1426. # add the solid_geometry to the current too in self.paint_tools dictionary
  1427. # and then reset the temporary list that stored that solid_geometry
  1428. v['solid_geometry'] = deepcopy(cleared_area)
  1429. v['data']['name'] = name
  1430. cleared_area[:] = []
  1431. break
  1432. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1433. else:
  1434. log.debug("There are no geometries in the cleared polygon.")
  1435. geo_obj.multigeo = True
  1436. geo_obj.options["cnctooldia"] = str(tool)
  1437. # check to see if geo_obj.tools is empty
  1438. # it will be updated only if there is a solid_geometry for tools
  1439. if geo_obj.tools:
  1440. return
  1441. else:
  1442. # I will use this variable for this purpose although it was meant for something else
  1443. # signal that we have no geo in the object therefore don't create it
  1444. app_obj.poly_not_cleared = False
  1445. return "fail"
  1446. # ###########################################################################################
  1447. # Create the Job function and send it to the worker to be processed in another thread #######
  1448. # ###########################################################################################
  1449. def job_thread(app_obj):
  1450. try:
  1451. if rest_machining_choice is True:
  1452. app_obj.new_object("geometry", name, gen_clear_area_rest)
  1453. else:
  1454. app_obj.new_object("geometry", name, gen_clear_area)
  1455. except Exception as e:
  1456. proc.done()
  1457. traceback.print_stack()
  1458. return
  1459. proc.done()
  1460. # focus on Selected Tab
  1461. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1462. # Promise object with the new name
  1463. self.app.collection.promise(name)
  1464. # Background
  1465. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1466. # def on_ncc(self):
  1467. #
  1468. # # Prepare non-copper polygons
  1469. # if self.reference_radio.get_value() == 'area':
  1470. # geo_n = self.sel_rect
  1471. #
  1472. # geo_buff_list = []
  1473. # for poly in geo_n:
  1474. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1475. # bounding_box = cascaded_union(geo_buff_list)
  1476. # else:
  1477. # geo_n = self.bound_obj.solid_geometry
  1478. #
  1479. # try:
  1480. # if isinstance(geo_n, MultiPolygon):
  1481. # env_obj = geo_n.convex_hull
  1482. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1483. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1484. # env_obj = cascaded_union(geo_n)
  1485. # else:
  1486. # env_obj = cascaded_union(geo_n)
  1487. # env_obj = env_obj.convex_hull
  1488. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1489. # except Exception as e:
  1490. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1491. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1492. # return
  1493. #
  1494. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1495. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1496. # if self.ncc_choice_offset_cb.isChecked():
  1497. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1498. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1499. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1500. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1501. # else:
  1502. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1503. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1504. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1505. # if self.ncc_choice_offset_cb.isChecked():
  1506. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1507. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1508. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1509. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1510. # else:
  1511. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1512. # else:
  1513. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1514. # return
  1515. #
  1516. # if type(empty) is Polygon:
  1517. # empty = MultiPolygon([empty])
  1518. #
  1519. # if empty.is_empty:
  1520. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1521. # return
  1522. #
  1523. # # clear non copper using standard algorithm
  1524. # if clearing_method is False:
  1525. # self.clear_non_copper(
  1526. # empty=empty,
  1527. # over=over,
  1528. # pol_method=pol_method,
  1529. # connect=connect,
  1530. # contour=contour
  1531. # )
  1532. # # clear non copper using rest machining algorithm
  1533. # else:
  1534. # self.clear_non_copper_rest(
  1535. # empty=empty,
  1536. # over=over,
  1537. # pol_method=pol_method,
  1538. # connect=connect,
  1539. # contour=contour
  1540. # )
  1541. #
  1542. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1543. #
  1544. # name = outname if outname else self.obj_name + "_ncc"
  1545. #
  1546. # # Sort tools in descending order
  1547. # sorted_tools = []
  1548. # for k, v in self.ncc_tools.items():
  1549. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1550. #
  1551. # order = self.ncc_order_radio.get_value()
  1552. # if order == 'fwd':
  1553. # sorted_tools.sort(reverse=False)
  1554. # elif order == 'rev':
  1555. # sorted_tools.sort(reverse=True)
  1556. # else:
  1557. # pass
  1558. #
  1559. # # Do job in background
  1560. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1561. #
  1562. # def initialize(geo_obj, app_obj):
  1563. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1564. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1565. #
  1566. # cleared_geo = []
  1567. # # Already cleared area
  1568. # cleared = MultiPolygon()
  1569. #
  1570. # # flag for polygons not cleared
  1571. # app_obj.poly_not_cleared = False
  1572. #
  1573. # # Generate area for each tool
  1574. # offset = sum(sorted_tools)
  1575. # current_uid = int(1)
  1576. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1577. #
  1578. # for tool in sorted_tools:
  1579. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  1580. # cleared_geo[:] = []
  1581. #
  1582. # # Get remaining tools offset
  1583. # offset -= (tool - 1e-12)
  1584. #
  1585. # # Area to clear
  1586. # area = empty.buffer(-offset)
  1587. # try:
  1588. # area = area.difference(cleared)
  1589. # except Exception as e:
  1590. # continue
  1591. #
  1592. # # Transform area to MultiPolygon
  1593. # if type(area) is Polygon:
  1594. # area = MultiPolygon([area])
  1595. #
  1596. # if area.geoms:
  1597. # if len(area.geoms) > 0:
  1598. # for p in area.geoms:
  1599. # try:
  1600. # if pol_method == 'standard':
  1601. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1602. # overlap=over, contour=contour, connect=connect)
  1603. # elif pol_method == 'seed':
  1604. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1605. # overlap=over, contour=contour, connect=connect)
  1606. # else:
  1607. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1608. # overlap=over, contour=contour, connect=connect)
  1609. # if cp:
  1610. # cleared_geo += list(cp.get_objects())
  1611. # except Exception as e:
  1612. # log.warning("Polygon can not be cleared. %s" % str(e))
  1613. # app_obj.poly_not_cleared = True
  1614. # continue
  1615. #
  1616. # # check if there is a geometry at all in the cleared geometry
  1617. # if cleared_geo:
  1618. # # Overall cleared area
  1619. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  1620. # tool / 1.999999)
  1621. #
  1622. # # clean-up cleared geo
  1623. # cleared = cleared.buffer(0)
  1624. #
  1625. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  1626. # # solid_geometry
  1627. # for k, v in self.ncc_tools.items():
  1628. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1629. # current_uid = int(k)
  1630. #
  1631. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1632. # # and then reset the temporary list that stored that solid_geometry
  1633. # v['solid_geometry'] = deepcopy(cleared_geo)
  1634. # v['data']['name'] = name
  1635. # break
  1636. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1637. # else:
  1638. # log.debug("There are no geometries in the cleared polygon.")
  1639. #
  1640. # geo_obj.options["cnctooldia"] = str(tool)
  1641. # geo_obj.multigeo = True
  1642. #
  1643. # def job_thread(app_obj):
  1644. # try:
  1645. # app_obj.new_object("geometry", name, initialize)
  1646. # except Exception as e:
  1647. # proc.done()
  1648. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  1649. # return
  1650. # proc.done()
  1651. #
  1652. # if app_obj.poly_not_cleared is False:
  1653. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  1654. # else:
  1655. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  1656. # 'Check the result.'))
  1657. # # reset the variable for next use
  1658. # app_obj.poly_not_cleared = False
  1659. #
  1660. # # focus on Selected Tab
  1661. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1662. #
  1663. # # Promise object with the new name
  1664. # self.app.collection.promise(name)
  1665. #
  1666. # # Background
  1667. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1668. #
  1669. # # clear copper with 'rest-machining' algorithm
  1670. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1671. #
  1672. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1673. #
  1674. # # Sort tools in descending order
  1675. # sorted_tools = []
  1676. # for k, v in self.ncc_tools.items():
  1677. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1678. # sorted_tools.sort(reverse=True)
  1679. #
  1680. # # Do job in background
  1681. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1682. #
  1683. # def initialize_rm(geo_obj, app_obj):
  1684. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1685. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1686. #
  1687. # cleared_geo = []
  1688. # cleared_by_last_tool = []
  1689. # rest_geo = []
  1690. # current_uid = 1
  1691. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  1692. #
  1693. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1694. # app_obj.poly_not_cleared = True
  1695. #
  1696. # area = empty.buffer(0)
  1697. # # Generate area for each tool
  1698. # while sorted_tools:
  1699. # tool = sorted_tools.pop(0)
  1700. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  1701. #
  1702. # tool_used = tool - 1e-12
  1703. # cleared_geo[:] = []
  1704. #
  1705. # # Area to clear
  1706. # for poly in cleared_by_last_tool:
  1707. # try:
  1708. # area = area.difference(poly)
  1709. # except Exception as e:
  1710. # pass
  1711. # cleared_by_last_tool[:] = []
  1712. #
  1713. # # Transform area to MultiPolygon
  1714. # if type(area) is Polygon:
  1715. # area = MultiPolygon([area])
  1716. #
  1717. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1718. # # and rest_geo it's a list
  1719. # allparts = [p.buffer(0) for p in area.geoms]
  1720. # allparts += deepcopy(rest_geo)
  1721. # rest_geo[:] = []
  1722. # area = MultiPolygon(deepcopy(allparts))
  1723. # allparts[:] = []
  1724. #
  1725. # if area.geoms:
  1726. # if len(area.geoms) > 0:
  1727. # for p in area.geoms:
  1728. # try:
  1729. # if pol_method == 'standard':
  1730. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  1731. # overlap=over, contour=contour, connect=connect)
  1732. # elif pol_method == 'seed':
  1733. # cp = self.clear_polygon2(p, tool_used,
  1734. # self.app.defaults["gerber_circle_steps"],
  1735. # overlap=over, contour=contour, connect=connect)
  1736. # else:
  1737. # cp = self.clear_polygon3(p, tool_used,
  1738. # self.app.defaults["gerber_circle_steps"],
  1739. # overlap=over, contour=contour, connect=connect)
  1740. # cleared_geo.append(list(cp.get_objects()))
  1741. # except:
  1742. # log.warning("Polygon can't be cleared.")
  1743. # # this polygon should be added to a list and then try clear it with a smaller tool
  1744. # rest_geo.append(p)
  1745. #
  1746. # # check if there is a geometry at all in the cleared geometry
  1747. # if cleared_geo:
  1748. # # Overall cleared area
  1749. # cleared_area = list(self.flatten_list(cleared_geo))
  1750. #
  1751. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1752. # # for p in cleared_area])
  1753. #
  1754. # # here we store the poly's already processed in the original geometry by the current tool
  1755. # # into cleared_by_last_tool list
  1756. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  1757. # # the next tool
  1758. # buffer_value = tool_used / 2
  1759. # for p in cleared_area:
  1760. # poly = p.buffer(buffer_value)
  1761. # cleared_by_last_tool.append(poly)
  1762. #
  1763. # # find the tooluid associated with the current tool_dia so we know
  1764. # # where to add the tool solid_geometry
  1765. # for k, v in self.ncc_tools.items():
  1766. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1767. # current_uid = int(k)
  1768. #
  1769. # # add the solid_geometry to the current too in self.paint_tools dictionary
  1770. # # and then reset the temporary list that stored that solid_geometry
  1771. # v['solid_geometry'] = deepcopy(cleared_area)
  1772. # v['data']['name'] = name
  1773. # cleared_area[:] = []
  1774. # break
  1775. #
  1776. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  1777. # else:
  1778. # log.debug("There are no geometries in the cleared polygon.")
  1779. #
  1780. # geo_obj.multigeo = True
  1781. # geo_obj.options["cnctooldia"] = str(tool)
  1782. #
  1783. # # check to see if geo_obj.tools is empty
  1784. # # it will be updated only if there is a solid_geometry for tools
  1785. # if geo_obj.tools:
  1786. # return
  1787. # else:
  1788. # # I will use this variable for this purpose although it was meant for something else
  1789. # # signal that we have no geo in the object therefore don't create it
  1790. # app_obj.poly_not_cleared = False
  1791. # return "fail"
  1792. #
  1793. # def job_thread(app_obj):
  1794. # try:
  1795. # app_obj.new_object("geometry", name, initialize_rm)
  1796. # except Exception as e:
  1797. # proc.done()
  1798. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  1799. # return
  1800. #
  1801. # if app_obj.poly_not_cleared is True:
  1802. # app_obj.inform.emit('[success] NCC Tool finished.')
  1803. # # focus on Selected Tab
  1804. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1805. # else:
  1806. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  1807. # 'with current settings.'))
  1808. # # focus on Project Tab
  1809. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  1810. # proc.done()
  1811. # # reset the variable for next use
  1812. # app_obj.poly_not_cleared = False
  1813. #
  1814. # # Promise object with the new name
  1815. # self.app.collection.promise(name)
  1816. #
  1817. # # Background
  1818. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1819. @staticmethod
  1820. def get_ncc_empty_area(target, boundary=None):
  1821. """
  1822. Returns the complement of target geometry within
  1823. the given boundary polygon. If not specified, it defaults to
  1824. the rectangular bounding box of target geometry.
  1825. """
  1826. if boundary is None:
  1827. boundary = target.envelope
  1828. return boundary.difference(target)
  1829. def reset_fields(self):
  1830. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1831. def reset_usage(self):
  1832. self.obj_name = ""
  1833. self.ncc_obj = None
  1834. self.bound_obj = None
  1835. self.first_click = False
  1836. self.cursor_pos = None
  1837. self.mouse_is_dragging = False
  1838. self.sel_rect = []
  1839. @staticmethod
  1840. def poly2rings(poly):
  1841. return [poly.exterior] + [interior for interior in poly.interiors]
  1842. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  1843. # isolation_geometry produces an envelope that is going on the left of the geometry
  1844. # (the copper features). To leave the least amount of burrs on the features
  1845. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1846. # the first pass is the one cutting all of the features, so it needs to be reversed
  1847. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1848. # to cut on the right side of the left over copper i.e on the left side of the features.
  1849. try:
  1850. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  1851. except Exception as e:
  1852. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  1853. return 'fail'
  1854. if invert:
  1855. try:
  1856. try:
  1857. pl = []
  1858. for p in geom:
  1859. if p is not None:
  1860. if isinstance(p, Polygon):
  1861. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1862. elif isinstance(p, LinearRing):
  1863. pl.append(Polygon(p.coords[::-1]))
  1864. geom = MultiPolygon(pl)
  1865. except TypeError:
  1866. if isinstance(geom, Polygon) and geom is not None:
  1867. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1868. elif isinstance(geom, LinearRing) and geom is not None:
  1869. geom = Polygon(geom.coords[::-1])
  1870. else:
  1871. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  1872. type(geom))
  1873. except Exception as e:
  1874. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  1875. return 'fail'
  1876. return geom