ToolNonCopperClear.py 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668
  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. form = QtWidgets.QFormLayout()
  119. self.tools_box.addLayout(form)
  120. # Milling Type Radio Button
  121. self.milling_type_label = QtWidgets.QLabel('%s:' % _('Milling Type'))
  122. self.milling_type_label.setToolTip(
  123. _("Milling type when the selected tool is of type: 'iso_op':\n"
  124. "- climb / best for precision milling and to reduce tool usage\n"
  125. "- conventional / useful when there is no backlash compensation")
  126. )
  127. self.milling_type_radio = RadioSet([{'label': _('Climb'), 'value': 'cl'},
  128. {'label': _('Conv.'), 'value': 'cv'}])
  129. self.milling_type_radio.setToolTip(
  130. _("Milling type when the selected tool is of type: 'iso_op':\n"
  131. "- climb / best for precision milling and to reduce tool usage\n"
  132. "- conventional / useful when there is no backlash compensation")
  133. )
  134. # Tool order
  135. self.ncc_order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  136. self.ncc_order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  137. "'No' --> means that the used order is the one in the tool table\n"
  138. "'Forward' --> means that the tools will be ordered from small to big\n"
  139. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  140. "WARNING: using rest machining will automatically set the order\n"
  141. "in reverse and disable this control."))
  142. self.ncc_order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  143. {'label': _('Forward'), 'value': 'fwd'},
  144. {'label': _('Reverse'), 'value': 'rev'}])
  145. self.ncc_order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  146. "'No' --> means that the used order is the one in the tool table\n"
  147. "'Forward' --> means that the tools will be ordered from small to big\n"
  148. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  149. "WARNING: using rest machining will automatically set the order\n"
  150. "in reverse and disable this control."))
  151. form.addRow(self.milling_type_label, self.milling_type_radio)
  152. form.addRow(self.ncc_order_label, self.ncc_order_radio)
  153. form.addRow(QtWidgets.QLabel(''))
  154. self.milling_type_label.hide()
  155. self.milling_type_radio.hide()
  156. # #############################################################
  157. # ############### Tool selection ##############################
  158. # #############################################################
  159. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("Tool Selection"))
  160. form.addRow(self.tool_sel_label)
  161. # Tool Type Radio Button
  162. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  163. self.tool_type_label.setToolTip(
  164. _("Default tool type:\n"
  165. "- 'V-shape'\n"
  166. "- Circular")
  167. )
  168. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  169. {'label': _('Circular'), 'value': 'C1'}])
  170. self.tool_type_radio.setToolTip(
  171. _("Default tool type:\n"
  172. "- 'V-shape'\n"
  173. "- Circular")
  174. )
  175. form.addRow(self.tool_type_label, self.tool_type_radio)
  176. # ### Add a new Tool ####
  177. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  178. self.addtool_entry_lbl.setToolTip(
  179. _("Diameter for the new tool to add in the Tool Table")
  180. )
  181. self.addtool_entry = FCEntry2()
  182. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  183. # Tip Dia
  184. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  185. self.tipdialabel.setToolTip(
  186. _("The tip diameter for V-Shape Tool"))
  187. self.tipdia_entry = LengthEntry()
  188. form.addRow(self.tipdialabel, self.tipdia_entry)
  189. # Tip Angle
  190. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  191. self.tipanglelabel.setToolTip(
  192. _("The tip angle for V-Shape Tool.\n"
  193. "In degree."))
  194. self.tipangle_entry = LengthEntry()
  195. form.addRow(self.tipanglelabel, self.tipangle_entry)
  196. grid2 = QtWidgets.QGridLayout()
  197. self.tools_box.addLayout(grid2)
  198. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  199. self.addtool_btn.setToolTip(
  200. _("Add a new tool to the Tool Table\n"
  201. "with the diameter specified above.")
  202. )
  203. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  204. # self.copytool_btn.setToolTip(
  205. # "Copy a selection of tools in the Tool Table\n"
  206. # "by first selecting a row in the Tool Table."
  207. # )
  208. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  209. self.deltool_btn.setToolTip(
  210. _("Delete a selection of tools in the Tool Table\n"
  211. "by first selecting a row(s) in the Tool Table.")
  212. )
  213. grid2.addWidget(self.addtool_btn, 0, 0)
  214. # grid2.addWidget(self.copytool_btn, 0, 1)
  215. grid2.addWidget(self.deltool_btn, 0, 2)
  216. self.empty_label_0 = QtWidgets.QLabel('')
  217. self.tools_box.addWidget(self.empty_label_0)
  218. grid3 = QtWidgets.QGridLayout()
  219. self.tools_box.addLayout(grid3)
  220. e_lab_1 = QtWidgets.QLabel('<b>%s:</b>' % _("Parameters"))
  221. grid3.addWidget(e_lab_1, 0, 0)
  222. # Cut Z entry
  223. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  224. cutzlabel.setToolTip(
  225. _("Depth of cut into material. Negative value.\n"
  226. "In FlatCAM units.")
  227. )
  228. self.cutz_entry = FloatEntry()
  229. self.cutz_entry.setToolTip(
  230. _("Depth of cut into material. Negative value.\n"
  231. "In FlatCAM units.")
  232. )
  233. grid3.addWidget(cutzlabel, 1, 0)
  234. grid3.addWidget(self.cutz_entry, 1, 1)
  235. # Overlap Entry
  236. nccoverlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  237. nccoverlabel.setToolTip(
  238. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  239. "Example:\n"
  240. "A value here of 0.25 means 25%% from the tool diameter found above.\n\n"
  241. "Adjust the value starting with lower values\n"
  242. "and increasing it if areas that should be cleared are still \n"
  243. "not cleared.\n"
  244. "Lower values = faster processing, faster execution on PCB.\n"
  245. "Higher values = slow processing and slow execution on CNC\n"
  246. "due of too many paths.")
  247. )
  248. self.ncc_overlap_entry = FCDoubleSpinner()
  249. self.ncc_overlap_entry.set_precision(3)
  250. self.ncc_overlap_entry.setWrapping(True)
  251. self.ncc_overlap_entry.setRange(0.000, 0.999)
  252. self.ncc_overlap_entry.setSingleStep(0.1)
  253. grid3.addWidget(nccoverlabel, 2, 0)
  254. grid3.addWidget(self.ncc_overlap_entry, 2, 1)
  255. nccmarginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  256. nccmarginlabel.setToolTip(
  257. _("Bounding box margin.")
  258. )
  259. grid3.addWidget(nccmarginlabel, 3, 0)
  260. self.ncc_margin_entry = FCEntry()
  261. grid3.addWidget(self.ncc_margin_entry, 3, 1)
  262. # Method
  263. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  264. methodlabel.setToolTip(
  265. _("Algorithm for non-copper clearing:<BR>"
  266. "<B>Standard</B>: Fixed step inwards.<BR>"
  267. "<B>Seed-based</B>: Outwards from seed.<BR>"
  268. "<B>Line-based</B>: Parallel lines.")
  269. )
  270. grid3.addWidget(methodlabel, 4, 0)
  271. self.ncc_method_radio = RadioSet([
  272. {"label": _("Standard"), "value": "standard"},
  273. {"label": _("Seed-based"), "value": "seed"},
  274. {"label": _("Straight lines"), "value": "lines"}
  275. ], orientation='vertical', stretch=False)
  276. grid3.addWidget(self.ncc_method_radio, 4, 1)
  277. # Connect lines
  278. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  279. pathconnectlabel.setToolTip(
  280. _("Draw lines between resulting\n"
  281. "segments to minimize tool lifts.")
  282. )
  283. grid3.addWidget(pathconnectlabel, 5, 0)
  284. self.ncc_connect_cb = FCCheckBox()
  285. grid3.addWidget(self.ncc_connect_cb, 5, 1)
  286. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  287. contourlabel.setToolTip(
  288. _("Cut around the perimeter of the polygon\n"
  289. "to trim rough edges.")
  290. )
  291. grid3.addWidget(contourlabel, 6, 0)
  292. self.ncc_contour_cb = FCCheckBox()
  293. grid3.addWidget(self.ncc_contour_cb, 6, 1)
  294. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  295. restlabel.setToolTip(
  296. _("If checked, use 'rest machining'.\n"
  297. "Basically it will clear copper outside PCB features,\n"
  298. "using the biggest tool and continue with the next tools,\n"
  299. "from bigger to smaller, to clear areas of copper that\n"
  300. "could not be cleared by previous tool, until there is\n"
  301. "no more copper to clear or there are no more tools.\n"
  302. "If not checked, use the standard algorithm.")
  303. )
  304. grid3.addWidget(restlabel, 7, 0)
  305. self.ncc_rest_cb = FCCheckBox()
  306. grid3.addWidget(self.ncc_rest_cb, 7, 1)
  307. # ## NCC Offset choice
  308. self.ncc_offset_choice_label = QtWidgets.QLabel('%s:' % _("Offset"))
  309. self.ncc_offset_choice_label.setToolTip(
  310. _("If used, it will add an offset to the copper features.\n"
  311. "The copper clearing will finish to a distance\n"
  312. "from the copper features.\n"
  313. "The value can be between 0 and 10 FlatCAM units.")
  314. )
  315. grid3.addWidget(self.ncc_offset_choice_label, 8, 0)
  316. self.ncc_choice_offset_cb = FCCheckBox()
  317. grid3.addWidget(self.ncc_choice_offset_cb, 8, 1)
  318. # ## NCC Offset value
  319. self.ncc_offset_label = QtWidgets.QLabel('%s:' % _("Offset value"))
  320. self.ncc_offset_label.setToolTip(
  321. _("If used, it will add an offset to the copper features.\n"
  322. "The copper clearing will finish to a distance\n"
  323. "from the copper features.\n"
  324. "The value can be between 0 and 10 FlatCAM units.")
  325. )
  326. grid3.addWidget(self.ncc_offset_label, 9, 0)
  327. self.ncc_offset_spinner = FCDoubleSpinner()
  328. self.ncc_offset_spinner.set_range(0.00, 10.00)
  329. self.ncc_offset_spinner.set_precision(4)
  330. self.ncc_offset_spinner.setWrapping(True)
  331. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  332. if units == 'MM':
  333. self.ncc_offset_spinner.setSingleStep(0.1)
  334. else:
  335. self.ncc_offset_spinner.setSingleStep(0.01)
  336. grid3.addWidget(self.ncc_offset_spinner, 9, 1)
  337. self.ncc_offset_label.hide()
  338. self.ncc_offset_spinner.hide()
  339. # ## Reference
  340. self.reference_radio = RadioSet([
  341. {'label': _('Itself'), 'value': 'itself'},
  342. {"label": _("Area Selection"), "value": "area"},
  343. {'label': _("Reference Object"), 'value': 'box'}
  344. ], orientation='vertical', stretch=False)
  345. self.reference_label = QtWidgets.QLabel(_("Reference:"))
  346. self.reference_label.setToolTip(
  347. _("- 'Itself' - the non copper clearing extent\n"
  348. "is based on the object that is copper cleared.\n "
  349. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  350. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  351. "- 'Reference Object' - will do non copper clearing within the area\n"
  352. "specified by another object.")
  353. )
  354. grid3.addWidget(self.reference_label, 10, 0)
  355. grid3.addWidget(self.reference_radio, 10, 1)
  356. form1 = QtWidgets.QFormLayout()
  357. self.tools_box.addLayout(form1)
  358. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  359. self.box_combo_type_label.setToolTip(
  360. _("The type of FlatCAM object to be used as non copper clearing reference.\n"
  361. "It can be Gerber, Excellon or Geometry.")
  362. )
  363. self.box_combo_type = QtWidgets.QComboBox()
  364. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  365. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  366. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  367. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  368. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  369. self.box_combo_label.setToolTip(
  370. _("The FlatCAM object to be used as non copper clearing reference.")
  371. )
  372. self.box_combo = QtWidgets.QComboBox()
  373. self.box_combo.setModel(self.app.collection)
  374. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  375. self.box_combo.setCurrentIndex(1)
  376. form1.addRow(self.box_combo_label, self.box_combo)
  377. self.box_combo.hide()
  378. self.box_combo_label.hide()
  379. self.box_combo_type.hide()
  380. self.box_combo_type_label.hide()
  381. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  382. self.generate_ncc_button.setToolTip(
  383. _("Create the Geometry Object\n"
  384. "for non-copper routing.")
  385. )
  386. self.tools_box.addWidget(self.generate_ncc_button)
  387. self.tools_box.addStretch()
  388. self.tools_table.setupContextMenu()
  389. self.tools_table.addContextMenu(
  390. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  391. self.tools_table.addContextMenu(
  392. "Delete", lambda:
  393. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  394. self.units = ''
  395. self.ncc_tools = {}
  396. self.tooluid = 0
  397. # store here the default data for Geometry Data
  398. self.default_data = {}
  399. self.obj_name = ""
  400. self.ncc_obj = None
  401. self.sel_rect = []
  402. self.bound_obj_name = ""
  403. self.bound_obj = None
  404. self.first_click = False
  405. self.cursor_pos = None
  406. self.mouse_is_dragging = False
  407. # store here solid_geometry when there are tool with isolation job
  408. self.solid_geometry = []
  409. self.tool_type_item_options = []
  410. self.addtool_btn.clicked.connect(self.on_tool_add)
  411. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  412. self.deltool_btn.clicked.connect(self.on_tool_delete)
  413. self.generate_ncc_button.clicked.connect(self.on_ncc_click)
  414. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  415. self.reference_radio.group_toggle_fn = self.on_toggle_reference
  416. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  417. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  418. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  419. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  420. def on_type_obj_index_changed(self, index):
  421. obj_type = self.type_obj_combo.currentIndex()
  422. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  423. self.object_combo.setCurrentIndex(0)
  424. def install(self, icon=None, separator=None, **kwargs):
  425. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  426. def run(self, toggle=True):
  427. self.app.report_usage("ToolNonCopperClear()")
  428. if toggle:
  429. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  430. if self.app.ui.splitter.sizes()[0] == 0:
  431. self.app.ui.splitter.setSizes([1, 1])
  432. else:
  433. try:
  434. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  435. # if tab is populated with the tool but it does not have the focus, focus on it
  436. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  437. # focus on Tool Tab
  438. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  439. else:
  440. self.app.ui.splitter.setSizes([0, 1])
  441. except AttributeError:
  442. pass
  443. else:
  444. if self.app.ui.splitter.sizes()[0] == 0:
  445. self.app.ui.splitter.setSizes([1, 1])
  446. FlatCAMTool.run(self)
  447. self.set_tool_ui()
  448. # reset those objects on a new run
  449. self.ncc_obj = None
  450. self.bound_obj = None
  451. self.obj_name = ''
  452. self.bound_obj_name = ''
  453. self.build_ui()
  454. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  455. def set_tool_ui(self):
  456. self.tools_frame.show()
  457. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  458. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  459. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  460. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  461. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  462. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  463. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  464. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  465. self.milling_type_radio.set_value(self.app.defaults["tools_nccmilling_type"])
  466. self.cutz_entry.set_value(self.app.defaults["tools_ncccutz"])
  467. self.tool_type_radio.set_value(self.app.defaults["tools_ncctool_type"])
  468. self.tipdia_entry.set_value(self.app.defaults["tools_ncctipdia"])
  469. self.tipangle_entry.set_value(self.app.defaults["tools_ncctipangle"])
  470. self.on_tool_type(val=self.tool_type_radio.get_value())
  471. # init the working variables
  472. self.default_data.clear()
  473. self.default_data.update({
  474. "name": '_ncc',
  475. "plot": self.app.defaults["geometry_plot"],
  476. "cutz": float(self.cutz_entry.get_value()),
  477. "vtipdia": float(self.tipdia_entry.get_value()),
  478. "vtipangle": float(self.tipangle_entry.get_value()),
  479. "travelz": self.app.defaults["geometry_travelz"],
  480. "feedrate": self.app.defaults["geometry_feedrate"],
  481. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  482. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  483. "dwell": self.app.defaults["geometry_dwell"],
  484. "dwelltime": self.app.defaults["geometry_dwelltime"],
  485. "multidepth": self.app.defaults["geometry_multidepth"],
  486. "ppname_g": self.app.defaults["geometry_ppname_g"],
  487. "depthperpass": self.app.defaults["geometry_depthperpass"],
  488. "extracut": self.app.defaults["geometry_extracut"],
  489. "toolchange": self.app.defaults["geometry_toolchange"],
  490. "toolchangez": self.app.defaults["geometry_toolchangez"],
  491. "endz": self.app.defaults["geometry_endz"],
  492. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  493. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  494. "startz": self.app.defaults["geometry_startz"],
  495. "tooldia": self.app.defaults["tools_painttooldia"],
  496. "paintmargin": self.app.defaults["tools_paintmargin"],
  497. "paintmethod": self.app.defaults["tools_paintmethod"],
  498. "selectmethod": self.app.defaults["tools_selectmethod"],
  499. "pathconnect": self.app.defaults["tools_pathconnect"],
  500. "paintcontour": self.app.defaults["tools_paintcontour"],
  501. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  502. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  503. "nccmargin": self.app.defaults["tools_nccmargin"],
  504. "nccmethod": self.app.defaults["tools_nccmethod"],
  505. "nccconnect": self.app.defaults["tools_nccconnect"],
  506. "ncccontour": self.app.defaults["tools_ncccontour"],
  507. "nccrest": self.app.defaults["tools_nccrest"]
  508. })
  509. try:
  510. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  511. except Exception as e:
  512. log.error("At least one tool diameter needed. "
  513. "Verify in Edit -> Preferences -> TOOLS -> NCC Tools. %s" % str(e))
  514. return
  515. self.tooluid = 0
  516. self.ncc_tools.clear()
  517. for tool_dia in dias:
  518. self.tooluid += 1
  519. self.ncc_tools.update({
  520. int(self.tooluid): {
  521. 'tooldia': float('%.4f' % tool_dia),
  522. 'offset': 'Path',
  523. 'offset_value': 0.0,
  524. 'type': 'Iso',
  525. 'tool_type': self.tool_type_radio.get_value(),
  526. 'operation': 'clear_op',
  527. 'data': deepcopy(self.default_data),
  528. 'solid_geometry': []
  529. }
  530. })
  531. self.obj_name = ""
  532. self.ncc_obj = None
  533. self.bound_obj_name = ""
  534. self.bound_obj = None
  535. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  536. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  537. def build_ui(self):
  538. self.ui_disconnect()
  539. # updated units
  540. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  541. if self.units == "IN":
  542. self.addtool_entry.set_value(0.039)
  543. else:
  544. self.addtool_entry.set_value(1)
  545. sorted_tools = []
  546. for k, v in self.ncc_tools.items():
  547. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  548. order = self.ncc_order_radio.get_value()
  549. if order == 'fwd':
  550. sorted_tools.sort(reverse=False)
  551. elif order == 'rev':
  552. sorted_tools.sort(reverse=True)
  553. else:
  554. pass
  555. n = len(sorted_tools)
  556. self.tools_table.setRowCount(n)
  557. tool_id = 0
  558. for tool_sorted in sorted_tools:
  559. for tooluid_key, tooluid_value in self.ncc_tools.items():
  560. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  561. tool_id += 1
  562. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  563. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  564. row_no = tool_id - 1
  565. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  566. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  567. # There are no drill bits in MM with more than 3 decimals diameter
  568. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  569. if self.units == 'MM':
  570. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  571. else:
  572. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  573. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  574. tool_type_item = QtWidgets.QComboBox()
  575. for item in self.tool_type_item_options:
  576. tool_type_item.addItem(item)
  577. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  578. idx = tool_type_item.findText(tooluid_value['tool_type'])
  579. tool_type_item.setCurrentIndex(idx)
  580. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  581. operation_type = QtWidgets.QComboBox()
  582. operation_type.addItem('iso_op')
  583. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  584. operation_type.addItem('clear_op')
  585. operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  586. op_idx = operation_type.findText(tooluid_value['operation'])
  587. operation_type.setCurrentIndex(op_idx)
  588. self.tools_table.setItem(row_no, 1, dia) # Diameter
  589. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  590. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  591. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  592. self.tools_table.setCellWidget(row_no, 4, operation_type)
  593. # make the diameter column editable
  594. for row in range(tool_id):
  595. self.tools_table.item(row, 1).setFlags(
  596. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  597. # all the tools are selected by default
  598. self.tools_table.selectColumn(0)
  599. #
  600. self.tools_table.resizeColumnsToContents()
  601. self.tools_table.resizeRowsToContents()
  602. vertical_header = self.tools_table.verticalHeader()
  603. vertical_header.hide()
  604. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  605. horizontal_header = self.tools_table.horizontalHeader()
  606. horizontal_header.setMinimumSectionSize(10)
  607. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  608. horizontal_header.resizeSection(0, 20)
  609. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  610. # self.tools_table.setSortingEnabled(True)
  611. # sort by tool diameter
  612. # self.tools_table.sortItems(1)
  613. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  614. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  615. self.ui_connect()
  616. def ui_connect(self):
  617. self.tools_table.itemChanged.connect(self.on_tool_edit)
  618. for row in range(self.tools_table.rowCount()):
  619. for col in [2, 4]:
  620. self.tools_table.cellWidget(row, col).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  621. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  622. def ui_disconnect(self):
  623. try:
  624. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  625. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  626. except (TypeError, AttributeError):
  627. pass
  628. try:
  629. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  630. self.tool_type_radio.activated_custom.disconnect(self.on_tool_type)
  631. except (TypeError, AttributeError):
  632. pass
  633. for row in range(self.tools_table.rowCount()):
  634. for col in [2, 4]:
  635. try:
  636. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  637. except (TypeError, AttributeError):
  638. pass
  639. def on_combo_box_type(self):
  640. obj_type = self.box_combo_type.currentIndex()
  641. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  642. self.box_combo.setCurrentIndex(0)
  643. def on_toggle_reference(self):
  644. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  645. self.box_combo.hide()
  646. self.box_combo_label.hide()
  647. self.box_combo_type.hide()
  648. self.box_combo_type_label.hide()
  649. else:
  650. self.box_combo.show()
  651. self.box_combo_label.show()
  652. self.box_combo_type.show()
  653. self.box_combo_type_label.show()
  654. def on_offset_choice(self, state):
  655. if state:
  656. self.ncc_offset_label.show()
  657. self.ncc_offset_spinner.show()
  658. else:
  659. self.ncc_offset_label.hide()
  660. self.ncc_offset_spinner.hide()
  661. def on_order_changed(self, order):
  662. if order != 'no':
  663. self.build_ui()
  664. def on_rest_machining_check(self, state):
  665. if state:
  666. self.ncc_order_radio.set_value('rev')
  667. self.ncc_order_label.setDisabled(True)
  668. self.ncc_order_radio.setDisabled(True)
  669. else:
  670. self.ncc_order_label.setDisabled(False)
  671. self.ncc_order_radio.setDisabled(False)
  672. def on_tooltable_cellwidget_change(self):
  673. cw = self.sender()
  674. cw_index = self.tools_table.indexAt(cw.pos())
  675. cw_row = cw_index.row()
  676. cw_col = cw_index.column()
  677. current_uid = int(self.tools_table.item(cw_row, 3).text())
  678. hide_iso_type = True
  679. for row in range(self.tools_table.rowCount()):
  680. if self.tools_table.cellWidget(row, 4).currentText() == 'iso_op':
  681. hide_iso_type = False
  682. break
  683. if hide_iso_type is False:
  684. self.milling_type_label.show()
  685. self.milling_type_radio.show()
  686. else:
  687. self.milling_type_label.hide()
  688. self.milling_type_radio.hide()
  689. # if the sender is in the column with index 2 then we update the tool_type key
  690. if cw_col == 2:
  691. tt = cw.currentText()
  692. if tt == 'V':
  693. typ = 'Iso'
  694. else:
  695. typ = "Rough"
  696. self.ncc_tools[current_uid].update({
  697. 'type': typ,
  698. 'tool_type': tt,
  699. })
  700. def on_tool_type(self, val):
  701. if val == 'V':
  702. self.addtool_entry_lbl.hide()
  703. self.addtool_entry.hide()
  704. self.tipdialabel.show()
  705. self.tipdia_entry.show()
  706. self.tipanglelabel.show()
  707. self.tipangle_entry.show()
  708. else:
  709. self.addtool_entry_lbl.show()
  710. self.addtool_entry.show()
  711. self.tipdialabel.hide()
  712. self.tipdia_entry.hide()
  713. self.tipanglelabel.hide()
  714. self.tipangle_entry.hide()
  715. def on_tool_add(self, dia=None, muted=None):
  716. self.ui_disconnect()
  717. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  718. if dia:
  719. tool_dia = dia
  720. else:
  721. if self.tool_type_radio.get_value() == 'V':
  722. try:
  723. tip_dia = float(self.tipdia_entry.get_value())
  724. except ValueError:
  725. # try to convert comma to decimal point. if it's still not working error message and return
  726. try:
  727. tip_dia = float(self.tipdia_entry.get_value().replace(',', '.'))
  728. except ValueError:
  729. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, "
  730. "use a number."))
  731. return
  732. try:
  733. tip_angle = float(self.tipangle_entry.get_value()) / 2
  734. except ValueError:
  735. # try to convert comma to decimal point. if it's still not working error message and return
  736. try:
  737. tip_angle = float(self.tipangle_entry.get_value().replace(',', '.')) / 2
  738. except ValueError:
  739. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  740. return
  741. try:
  742. cut_z = float(self.cutz_entry.get_value())
  743. except ValueError:
  744. # try to convert comma to decimal point. if it's still not working error message and return
  745. try:
  746. cut_z = float(self.cutz_entry.get_value().replace(',', '.'))
  747. except ValueError:
  748. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  749. return
  750. # calculated tool diameter so the cut_z parameter is obeyed
  751. tool_dia = tip_dia + 2 * cut_z * math.tan(math.radians(tip_angle))
  752. # update the default_data so it is used in the ncc_tools dict
  753. self.default_data.update({
  754. "vtipdia": tip_dia,
  755. "vtipangle": (tip_angle * 2),
  756. })
  757. else:
  758. try:
  759. tool_dia = float(self.addtool_entry.get_value())
  760. except ValueError:
  761. # try to convert comma to decimal point. if it's still not working error message and return
  762. try:
  763. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  764. except ValueError:
  765. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  766. return
  767. if tool_dia is None:
  768. self.build_ui()
  769. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  770. return
  771. if self.units == 'MM':
  772. tool_dia = float('%.2f' % tool_dia)
  773. else:
  774. tool_dia = float('%.4f' % tool_dia)
  775. if tool_dia == 0:
  776. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  777. "in Float format."))
  778. return
  779. # construct a list of all 'tooluid' in the self.tools
  780. tool_uid_list = []
  781. for tooluid_key in self.ncc_tools:
  782. tool_uid_item = int(tooluid_key)
  783. tool_uid_list.append(tool_uid_item)
  784. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  785. if not tool_uid_list:
  786. max_uid = 0
  787. else:
  788. max_uid = max(tool_uid_list)
  789. self.tooluid = int(max_uid + 1)
  790. tool_dias = []
  791. for k, v in self.ncc_tools.items():
  792. for tool_v in v.keys():
  793. if tool_v == 'tooldia':
  794. tool_dias.append(float('%.4f' % v[tool_v]))
  795. if float('%.4f' % tool_dia) in tool_dias:
  796. if muted is None:
  797. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  798. self.tools_table.itemChanged.connect(self.on_tool_edit)
  799. return
  800. else:
  801. if muted is None:
  802. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  803. self.ncc_tools.update({
  804. int(self.tooluid): {
  805. 'tooldia': float('%.4f' % tool_dia),
  806. 'offset': 'Path',
  807. 'offset_value': 0.0,
  808. 'type': 'Iso',
  809. 'tool_type': self.tool_type_radio.get_value(),
  810. 'operation': 'clear_op',
  811. 'data': deepcopy(self.default_data),
  812. 'solid_geometry': []
  813. }
  814. })
  815. self.build_ui()
  816. def on_tool_edit(self):
  817. self.ui_disconnect()
  818. old_tool_dia = ''
  819. tool_dias = []
  820. for k, v in self.ncc_tools.items():
  821. for tool_v in v.keys():
  822. if tool_v == 'tooldia':
  823. tool_dias.append(float('%.4f' % v[tool_v]))
  824. for row in range(self.tools_table.rowCount()):
  825. try:
  826. new_tool_dia = float(self.tools_table.item(row, 1).text())
  827. except ValueError:
  828. # try to convert comma to decimal point. if it's still not working error message and return
  829. try:
  830. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  831. except ValueError:
  832. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, "
  833. "use a number."))
  834. return
  835. tooluid = int(self.tools_table.item(row, 3).text())
  836. # identify the tool that was edited and get it's tooluid
  837. if new_tool_dia not in tool_dias:
  838. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  839. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  840. self.build_ui()
  841. return
  842. else:
  843. # identify the old tool_dia and restore the text in tool table
  844. for k, v in self.ncc_tools.items():
  845. if k == tooluid:
  846. old_tool_dia = v['tooldia']
  847. break
  848. restore_dia_item = self.tools_table.item(row, 1)
  849. restore_dia_item.setText(str(old_tool_dia))
  850. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Edit cancelled. "
  851. "New diameter value is already in the Tool Table."))
  852. self.build_ui()
  853. def on_tool_delete(self, rows_to_delete=None, all=None):
  854. self.ui_disconnect()
  855. deleted_tools_list = []
  856. if all:
  857. self.paint_tools.clear()
  858. self.build_ui()
  859. return
  860. if rows_to_delete:
  861. try:
  862. for row in rows_to_delete:
  863. tooluid_del = int(self.tools_table.item(row, 3).text())
  864. deleted_tools_list.append(tooluid_del)
  865. except TypeError:
  866. deleted_tools_list.append(rows_to_delete)
  867. for t in deleted_tools_list:
  868. self.ncc_tools.pop(t, None)
  869. self.build_ui()
  870. return
  871. try:
  872. if self.tools_table.selectedItems():
  873. for row_sel in self.tools_table.selectedItems():
  874. row = row_sel.row()
  875. if row < 0:
  876. continue
  877. tooluid_del = int(self.tools_table.item(row, 3).text())
  878. deleted_tools_list.append(tooluid_del)
  879. for t in deleted_tools_list:
  880. self.ncc_tools.pop(t, None)
  881. except AttributeError:
  882. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  883. return
  884. except Exception as e:
  885. log.debug(str(e))
  886. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  887. self.build_ui()
  888. def on_ncc_click(self):
  889. # init values for the next usage
  890. self.reset_usage()
  891. self.app.report_usage(_("on_paint_button_click"))
  892. try:
  893. overlap = float(self.ncc_overlap_entry.get_value())
  894. except ValueError:
  895. # try to convert comma to decimal point. if it's still not working error message and return
  896. try:
  897. overlap = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  898. except ValueError:
  899. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, "
  900. "use a number."))
  901. return
  902. if overlap >= 1 or overlap < 0:
  903. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Overlap value must be between "
  904. "0 (inclusive) and 1 (exclusive), "))
  905. return
  906. connect = self.ncc_connect_cb.get_value()
  907. contour = self.ncc_contour_cb.get_value()
  908. has_offset = self.ncc_choice_offset_cb.isChecked()
  909. rest = self.ncc_rest_cb.get_value()
  910. self.obj_name = self.object_combo.currentText()
  911. # Get source object.
  912. try:
  913. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  914. except Exception as e:
  915. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  916. return "Could not retrieve object: %s" % self.obj_name
  917. if self.ncc_obj is None:
  918. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  919. return
  920. # use the selected tools in the tool table; get diameters for non-copper clear
  921. iso_dia_list = list()
  922. # use the selected tools in the tool table; get diameters for non-copper clear
  923. ncc_dia_list = list()
  924. if self.tools_table.selectedItems():
  925. for x in self.tools_table.selectedItems():
  926. try:
  927. tooldia = float(self.tools_table.item(x.row(), 1).text())
  928. except ValueError:
  929. # try to convert comma to decimal point. if it's still not working error message and return
  930. try:
  931. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  932. except ValueError:
  933. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  934. "use a number."))
  935. continue
  936. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  937. iso_dia_list.append(tooldia)
  938. else:
  939. ncc_dia_list.append(tooldia)
  940. else:
  941. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  942. return
  943. o_name = '%s_ncc' % self.obj_name
  944. select_method = self.reference_radio.get_value()
  945. if select_method == 'itself':
  946. self.bound_obj_name = self.object_combo.currentText()
  947. # Get source object.
  948. try:
  949. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  950. except Exception as e:
  951. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  952. return "Could not retrieve object: %s" % self.obj_name
  953. self.clear_copper(ncc_obj=self.ncc_obj,
  954. ncctooldia=ncc_dia_list,
  955. isotooldia=iso_dia_list,
  956. has_offset=has_offset,
  957. outname=o_name,
  958. overlap=overlap,
  959. connect=connect,
  960. contour=contour,
  961. rest=rest)
  962. elif select_method == 'area':
  963. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  964. # use the first tool in the tool table; get the diameter
  965. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  966. # To be called after clicking on the plot.
  967. def on_mouse_release(event):
  968. # do clear area only for left mouse clicks
  969. if event.button == 1:
  970. if self.first_click is False:
  971. self.first_click = True
  972. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  973. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  974. if self.app.grid_status() == True:
  975. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  976. else:
  977. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  978. self.app.delete_selection_shape()
  979. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  980. if self.app.grid_status() == True:
  981. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  982. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  983. x1, y1 = curr_pos[0], curr_pos[1]
  984. pt1 = (x0, y0)
  985. pt2 = (x1, y0)
  986. pt3 = (x1, y1)
  987. pt4 = (x0, y1)
  988. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  989. self.first_click = False
  990. return
  991. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  992. #
  993. # if modifiers == QtCore.Qt.ShiftModifier:
  994. # mod_key = 'Shift'
  995. # elif modifiers == QtCore.Qt.ControlModifier:
  996. # mod_key = 'Control'
  997. # else:
  998. # mod_key = None
  999. #
  1000. # if mod_key == self.app.defaults["global_mselect_key"]:
  1001. # self.first_click = False
  1002. # return
  1003. #
  1004. # self.sel_rect = cascaded_union(self.sel_rect)
  1005. # self.clear_copper(ncc_obj=self.ncc_obj,
  1006. # sel_obj=self.bound_obj,
  1007. # ncctooldia=ncc_dia_list,
  1008. # isotooldia=iso_dia_list,
  1009. # has_offset=has_offset,
  1010. # outname=o_name,
  1011. # overlap=overlap,
  1012. # connect=connect,
  1013. # contour=contour,
  1014. # rest=rest)
  1015. #
  1016. # self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1017. # self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  1018. #
  1019. # self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1020. # self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1021. # self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1022. elif event.button == 2 and self.mouse_is_dragging == False:
  1023. self.first_click = False
  1024. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  1025. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  1026. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1027. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1028. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1029. if len(self.sel_rect) == 0:
  1030. return
  1031. self.sel_rect = cascaded_union(self.sel_rect)
  1032. self.clear_copper(ncc_obj=self.ncc_obj,
  1033. sel_obj=self.bound_obj,
  1034. ncctooldia=ncc_dia_list,
  1035. isotooldia=iso_dia_list,
  1036. has_offset=has_offset,
  1037. outname=o_name,
  1038. overlap=overlap,
  1039. connect=connect,
  1040. contour=contour,
  1041. rest=rest)
  1042. # called on mouse move
  1043. def on_mouse_move(event):
  1044. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  1045. self.app.app_cursor.enabled = False
  1046. # detect mouse dragging motion
  1047. if event.is_dragging is True:
  1048. self.mouse_is_dragging = True
  1049. else:
  1050. self.mouse_is_dragging = False
  1051. # update the cursor position
  1052. if self.app.grid_status() == True:
  1053. self.app.app_cursor.enabled = True
  1054. # Update cursor
  1055. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1056. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1057. symbol='++', edge_color='black', size=20)
  1058. # draw the utility geometry
  1059. if self.first_click:
  1060. self.app.delete_selection_shape()
  1061. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1062. coords=(curr_pos[0], curr_pos[1]),
  1063. face_alpha=0.0)
  1064. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1065. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1066. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1067. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  1068. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  1069. elif select_method == 'box':
  1070. self.bound_obj_name = self.box_combo.currentText()
  1071. # Get source object.
  1072. try:
  1073. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1074. except Exception as e:
  1075. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1076. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1077. self.clear_copper(ncc_obj=self.ncc_obj,
  1078. sel_obj=self.bound_obj,
  1079. ncctooldia=ncc_dia_list,
  1080. isotooldia=iso_dia_list,
  1081. has_offset=has_offset,
  1082. outname=o_name,
  1083. overlap=overlap,
  1084. connect=connect,
  1085. contour=contour,
  1086. rest=rest)
  1087. def clear_copper(self, ncc_obj,
  1088. sel_obj=None,
  1089. ncctooldia=None,
  1090. isotooldia=None,
  1091. margin=None,
  1092. has_offset=None,
  1093. offset=None,
  1094. select_method=None,
  1095. outname=None,
  1096. overlap=None,
  1097. connect=None,
  1098. contour=None,
  1099. order=None,
  1100. method=None,
  1101. rest=None,
  1102. tools_storage=None,
  1103. plot=True,
  1104. run_threaded=True):
  1105. """
  1106. Clear the excess copper from the entire object.
  1107. :param ncc_obj: ncc cleared object
  1108. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1109. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1110. :param overlap: value by which the paths will overlap
  1111. :param order: if the tools are ordered and how
  1112. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1113. another object
  1114. :param has_offset: True if an offset is needed
  1115. :param offset: distance from the copper features where the copper clearing is stopping
  1116. :param margin: a border around cleared area
  1117. :param outname: name of the resulting object
  1118. :param connect: Connect lines to avoid tool lifts.
  1119. :param contour: Paint around the edges.
  1120. :param method: choice out of 'seed', 'normal', 'lines'
  1121. :param rest: True if to use rest-machining
  1122. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1123. Usage of the different one is related to when this function is called from a TcL command.
  1124. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1125. run non-threaded for TclShell usage
  1126. :return:
  1127. """
  1128. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1129. # #####################################################################
  1130. # ####### Read the parameters #########################################
  1131. # #####################################################################
  1132. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value()
  1133. log.debug("NCC Tool started. Reading parameters.")
  1134. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  1135. ncc_method = method if method else self.ncc_method_radio.get_value()
  1136. if margin is not None:
  1137. ncc_margin = margin
  1138. else:
  1139. try:
  1140. ncc_margin = float(self.ncc_margin_entry.get_value())
  1141. except ValueError:
  1142. # try to convert comma to decimal point. if it's still not working error message and return
  1143. try:
  1144. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  1145. except ValueError:
  1146. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1147. return
  1148. if select_method is not None:
  1149. ncc_select = select_method
  1150. else:
  1151. ncc_select = self.reference_radio.get_value()
  1152. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  1153. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1154. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1155. order = order if order else self.ncc_order_radio.get_value()
  1156. # determine if to use the progressive plotting
  1157. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1158. prog_plot = True
  1159. else:
  1160. prog_plot = False
  1161. if tools_storage is not None:
  1162. tools_storage = tools_storage
  1163. else:
  1164. tools_storage = self.ncc_tools
  1165. ncc_offset = 0.0
  1166. if has_offset is True:
  1167. if offset is not None:
  1168. ncc_offset = offset
  1169. else:
  1170. try:
  1171. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1172. except ValueError:
  1173. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1174. return
  1175. # ######################################################################################################
  1176. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1177. # ######################################################################################################
  1178. sorted_tools = []
  1179. if ncctooldia is not None:
  1180. try:
  1181. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1182. except AttributeError:
  1183. if not isinstance(ncctooldia, list):
  1184. sorted_tools = [float(ncctooldia)]
  1185. else:
  1186. sorted_tools = ncctooldia
  1187. else:
  1188. for row in range(self.tools_table.rowCount()):
  1189. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1190. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1191. # ##############################################################################################################
  1192. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1193. # ##############################################################################################################
  1194. log.debug("NCC Tool. Preparing non-copper polygons.")
  1195. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1196. try:
  1197. if sel_obj is None or sel_obj == 'itself':
  1198. ncc_sel_obj = ncc_obj
  1199. else:
  1200. ncc_sel_obj = sel_obj
  1201. except Exception as e:
  1202. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1203. return 'fail'
  1204. bounding_box = None
  1205. if ncc_select == 'itself':
  1206. geo_n = ncc_sel_obj.solid_geometry
  1207. try:
  1208. if isinstance(geo_n, MultiPolygon):
  1209. env_obj = geo_n.convex_hull
  1210. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1211. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1212. env_obj = cascaded_union(geo_n)
  1213. else:
  1214. env_obj = cascaded_union(geo_n)
  1215. env_obj = env_obj.convex_hull
  1216. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1217. except Exception as e:
  1218. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1219. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1220. return 'fail'
  1221. elif ncc_select == 'area':
  1222. geo_n = cascaded_union(self.sel_rect)
  1223. try:
  1224. __ = iter(geo_n)
  1225. except Exception as e:
  1226. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1227. geo_n = [geo_n]
  1228. geo_buff_list = []
  1229. for poly in geo_n:
  1230. if self.app.abort_flag:
  1231. # graceful abort requested by the user
  1232. raise FlatCAMApp.GracefulException
  1233. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1234. bounding_box = cascaded_union(geo_buff_list)
  1235. elif ncc_select == 'box':
  1236. geo_n = ncc_sel_obj.solid_geometry
  1237. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1238. try:
  1239. __ = iter(geo_n)
  1240. except Exception as e:
  1241. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1242. geo_n = [geo_n]
  1243. geo_buff_list = []
  1244. for poly in geo_n:
  1245. if self.app.abort_flag:
  1246. # graceful abort requested by the user
  1247. raise FlatCAMApp.GracefulException
  1248. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1249. bounding_box = cascaded_union(geo_buff_list)
  1250. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1251. geo_n = cascaded_union(geo_n).convex_hull
  1252. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1253. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1254. else:
  1255. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1256. return 'fail'
  1257. log.debug("NCC Tool. Finished non-copper polygons.")
  1258. # ########################################################################################################
  1259. # set the name for the future Geometry object
  1260. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1261. # ########################################################################################################
  1262. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1263. if rest_machining_choice is True:
  1264. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1265. else:
  1266. name = outname if outname is not None else self.obj_name + "_ncc"
  1267. # ##########################################################################################
  1268. # Initializes the new geometry object ######################################################
  1269. # ##########################################################################################
  1270. def gen_clear_area(geo_obj, app_obj):
  1271. assert isinstance(geo_obj, FlatCAMGeometry), \
  1272. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1273. log.debug("NCC Tool. Normal copper clearing task started.")
  1274. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1275. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1276. # will store the number of tools for which the isolation is broken
  1277. warning_flag = 0
  1278. if order == 'fwd':
  1279. sorted_tools.sort(reverse=False)
  1280. elif order == 'rev':
  1281. sorted_tools.sort(reverse=True)
  1282. else:
  1283. pass
  1284. cleared_geo = []
  1285. # Already cleared area
  1286. cleared = MultiPolygon()
  1287. # flag for polygons not cleared
  1288. app_obj.poly_not_cleared = False
  1289. # Generate area for each tool
  1290. offset = sum(sorted_tools)
  1291. current_uid = int(1)
  1292. try:
  1293. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1294. except TypeError:
  1295. tool = eval(self.app.defaults["tools_ncctools"])
  1296. # ###################################################################################################
  1297. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1298. # ###################################################################################################
  1299. log.debug("NCC Tool. Calculate 'empty' area.")
  1300. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1301. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1302. # unfortunately for this function to work time efficient,
  1303. # if the Gerber was loaded without buffering then it require the buffering now.
  1304. if self.app.defaults['gerber_buffering'] == 'no':
  1305. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1306. else:
  1307. sol_geo = ncc_obj.solid_geometry
  1308. if has_offset is True:
  1309. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1310. _("Buffering"))
  1311. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1312. app_obj.inform.emit('[success] %s ...' %
  1313. _("Buffering finished"))
  1314. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1315. if empty == 'fail':
  1316. return 'fail'
  1317. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1318. isolated_geo = []
  1319. # unfortunately for this function to work time efficient,
  1320. # if the Gerber was loaded without buffering then it require the buffering now.
  1321. if self.app.defaults['gerber_buffering'] == 'no':
  1322. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1323. else:
  1324. self.solid_geometry = ncc_obj.solid_geometry
  1325. # if milling type is climb then the move is counter-clockwise around features
  1326. milling_type = self.milling_type_radio.get_value()
  1327. for tool_iso in isotooldia:
  1328. new_geometry = []
  1329. if milling_type == 'cl':
  1330. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1331. else:
  1332. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1333. if isolated_geo == 'fail':
  1334. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1335. else:
  1336. try:
  1337. for geo_elem in isolated_geo:
  1338. if self.app.abort_flag:
  1339. # graceful abort requested by the user
  1340. raise FlatCAMApp.GracefulException
  1341. if isinstance(geo_elem, Polygon):
  1342. for ring in self.poly2rings(geo_elem):
  1343. new_geo = ring.intersection(bounding_box)
  1344. if new_geo and not new_geo.is_empty:
  1345. new_geometry.append(new_geo)
  1346. elif isinstance(geo_elem, MultiPolygon):
  1347. for poly in geo_elem:
  1348. for ring in self.poly2rings(poly):
  1349. new_geo = ring.intersection(bounding_box)
  1350. if new_geo and not new_geo.is_empty:
  1351. new_geometry.append(new_geo)
  1352. elif isinstance(geo_elem, LineString):
  1353. new_geo = geo_elem.intersection(bounding_box)
  1354. if new_geo:
  1355. if not new_geo.is_empty:
  1356. new_geometry.append(new_geo)
  1357. elif isinstance(geo_elem, MultiLineString):
  1358. for line_elem in geo_elem:
  1359. new_geo = line_elem.intersection(bounding_box)
  1360. if new_geo and not new_geo.is_empty:
  1361. new_geometry.append(new_geo)
  1362. except TypeError:
  1363. if isinstance(isolated_geo, Polygon):
  1364. for ring in self.poly2rings(isolated_geo):
  1365. new_geo = ring.intersection(bounding_box)
  1366. if new_geo:
  1367. if not new_geo.is_empty:
  1368. new_geometry.append(new_geo)
  1369. elif isinstance(isolated_geo, LineString):
  1370. new_geo = isolated_geo.intersection(bounding_box)
  1371. if new_geo and not new_geo.is_empty:
  1372. new_geometry.append(new_geo)
  1373. elif isinstance(isolated_geo, MultiLineString):
  1374. for line_elem in isolated_geo:
  1375. new_geo = line_elem.intersection(bounding_box)
  1376. if new_geo and not new_geo.is_empty:
  1377. new_geometry.append(new_geo)
  1378. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1379. for geo_e in new_geometry:
  1380. if type(geo_e) == MultiLineString:
  1381. warning_flag += 1
  1382. break
  1383. for k, v in tools_storage.items():
  1384. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1385. current_uid = int(k)
  1386. # add the solid_geometry to the current too in self.paint_tools dictionary
  1387. # and then reset the temporary list that stored that solid_geometry
  1388. v['solid_geometry'] = deepcopy(new_geometry)
  1389. v['data']['name'] = name
  1390. break
  1391. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1392. sol_geo = cascaded_union(isolated_geo)
  1393. if has_offset is True:
  1394. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1395. _("Buffering"))
  1396. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1397. app_obj.inform.emit('[success] %s ...' %
  1398. _("Buffering finished"))
  1399. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1400. if empty == 'fail':
  1401. return 'fail'
  1402. elif isinstance(ncc_obj, FlatCAMGeometry):
  1403. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1404. if has_offset is True:
  1405. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1406. _("Buffering"))
  1407. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1408. app_obj.inform.emit('[success] %s ...' %
  1409. _("Buffering finished"))
  1410. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1411. if empty == 'fail':
  1412. return 'fail'
  1413. else:
  1414. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1415. _('The selected object is not suitable for copper clearing.'))
  1416. return
  1417. if empty.is_empty:
  1418. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1419. _("Could not get the extent of the area to be non copper cleared."))
  1420. return 'fail'
  1421. if type(empty) is Polygon:
  1422. empty = MultiPolygon([empty])
  1423. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1424. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1425. cp = None
  1426. for tool in sorted_tools:
  1427. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1428. if self.app.abort_flag:
  1429. # graceful abort requested by the user
  1430. raise FlatCAMApp.GracefulException
  1431. app_obj.inform.emit(
  1432. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1433. str(tool),
  1434. units.lower(),
  1435. _('started.'))
  1436. )
  1437. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1438. cleared_geo[:] = []
  1439. # Get remaining tools offset
  1440. offset -= (tool - 1e-12)
  1441. # Area to clear
  1442. area = empty.buffer(-offset)
  1443. try:
  1444. area = area.difference(cleared)
  1445. except Exception as e:
  1446. continue
  1447. # Transform area to MultiPolygon
  1448. if type(area) is Polygon:
  1449. area = MultiPolygon([area])
  1450. # variables to display the percentage of work done
  1451. geo_len = len(area.geoms)
  1452. disp_number = 0
  1453. old_disp_number = 0
  1454. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1455. if area.geoms:
  1456. if len(area.geoms) > 0:
  1457. pol_nr = 0
  1458. for p in area.geoms:
  1459. if self.app.abort_flag:
  1460. # graceful abort requested by the user
  1461. raise FlatCAMApp.GracefulException
  1462. if p is not None:
  1463. try:
  1464. if isinstance(p, Polygon):
  1465. if ncc_method == 'standard':
  1466. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1467. overlap=overlap, contour=contour, connect=connect,
  1468. prog_plot=prog_plot)
  1469. elif ncc_method == 'seed':
  1470. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1471. overlap=overlap, contour=contour, connect=connect,
  1472. prog_plot=prog_plot)
  1473. else:
  1474. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1475. overlap=overlap, contour=contour, connect=connect,
  1476. prog_plot=prog_plot)
  1477. if cp:
  1478. cleared_geo += list(cp.get_objects())
  1479. elif isinstance(p, MultiPolygon):
  1480. for pol in p:
  1481. if pol is not None:
  1482. if ncc_method == 'standard':
  1483. cp = self.clear_polygon(pol, tool,
  1484. self.app.defaults["gerber_circle_steps"],
  1485. overlap=overlap, contour=contour,
  1486. connect=connect,
  1487. prog_plot=prog_plot)
  1488. elif ncc_method == 'seed':
  1489. cp = self.clear_polygon2(pol, tool,
  1490. self.app.defaults["gerber_circle_steps"],
  1491. overlap=overlap, contour=contour,
  1492. connect=connect,
  1493. prog_plot=prog_plot)
  1494. else:
  1495. cp = self.clear_polygon3(pol, tool,
  1496. self.app.defaults["gerber_circle_steps"],
  1497. overlap=overlap, contour=contour,
  1498. connect=connect,
  1499. prog_plot=prog_plot)
  1500. if cp:
  1501. cleared_geo += list(cp.get_objects())
  1502. except Exception as e:
  1503. log.warning("Polygon can not be cleared. %s" % str(e))
  1504. app_obj.poly_not_cleared = True
  1505. continue
  1506. pol_nr += 1
  1507. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1508. # log.debug("Polygons cleared: %d" % pol_nr)
  1509. if old_disp_number < disp_number <= 100:
  1510. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1511. old_disp_number = disp_number
  1512. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1513. # check if there is a geometry at all in the cleared geometry
  1514. if cleared_geo:
  1515. # Overall cleared area
  1516. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1517. tool / 1.999999)
  1518. # clean-up cleared geo
  1519. cleared = cleared.buffer(0)
  1520. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1521. # solid_geometry
  1522. for k, v in tools_storage.items():
  1523. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1524. current_uid = int(k)
  1525. # add the solid_geometry to the current too in self.paint_tools dictionary
  1526. # and then reset the temporary list that stored that solid_geometry
  1527. v['solid_geometry'] = deepcopy(cleared_geo)
  1528. v['data']['name'] = name
  1529. break
  1530. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1531. else:
  1532. log.debug("There are no geometries in the cleared polygon.")
  1533. # clean the progressive plotted shapes if it was used
  1534. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1535. self.temp_shapes.clear(update=True)
  1536. # delete tools with empty geometry
  1537. keys_to_delete = []
  1538. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1539. for uid in tools_storage:
  1540. # if the solid_geometry (type=list) is empty
  1541. if not tools_storage[uid]['solid_geometry']:
  1542. keys_to_delete.append(uid)
  1543. # actual delete of keys from the tools_storage dict
  1544. for k in keys_to_delete:
  1545. tools_storage.pop(k, None)
  1546. geo_obj.options["cnctooldia"] = str(tool)
  1547. geo_obj.multigeo = True
  1548. geo_obj.tools.clear()
  1549. geo_obj.tools = dict(tools_storage)
  1550. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1551. has_solid_geo = 0
  1552. for tooluid in geo_obj.tools:
  1553. if geo_obj.tools[tooluid]['solid_geometry']:
  1554. has_solid_geo += 1
  1555. if has_solid_geo == 0:
  1556. app_obj.inform.emit('[ERROR] %s' % _("There is no Painting Geometry in the file.\n"
  1557. "Usually it means that the tool diameter is too big "
  1558. "for the painted geometry.\n"
  1559. "Change the painting parameters and try again."))
  1560. return
  1561. # Experimental...
  1562. # print("Indexing...", end=' ')
  1563. # geo_obj.make_index()
  1564. if warning_flag == 0:
  1565. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1566. else:
  1567. self.app.inform.emit('[WARNING] %s: %s %s.' % (_("NCC Tool clear all done but the copper features "
  1568. "isolation is broken for"),
  1569. str(warning_flag),
  1570. _("tools")))
  1571. # ###########################################################################################
  1572. # Initializes the new geometry object for the case of the rest-machining ####################
  1573. # ###########################################################################################
  1574. def gen_clear_area_rest(geo_obj, app_obj):
  1575. assert isinstance(geo_obj, FlatCAMGeometry), \
  1576. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1577. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1578. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1579. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1580. # will store the number of tools for which the isolation is broken
  1581. warning_flag = 0
  1582. sorted_tools.sort(reverse=True)
  1583. cleared_geo = []
  1584. cleared_by_last_tool = []
  1585. rest_geo = []
  1586. current_uid = 1
  1587. try:
  1588. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1589. except TypeError:
  1590. tool = eval(self.app.defaults["tools_ncctools"])
  1591. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1592. app_obj.poly_not_cleared = True
  1593. log.debug("NCC Tool. Calculate 'empty' area.")
  1594. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1595. # ###################################################################################################
  1596. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1597. # ###################################################################################################
  1598. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1599. sol_geo = ncc_obj.solid_geometry
  1600. if has_offset is True:
  1601. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1602. _("Buffering"))
  1603. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1604. app_obj.inform.emit('[success] %s ...' %
  1605. _("Buffering finished"))
  1606. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1607. if empty == 'fail':
  1608. return 'fail'
  1609. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1610. isolated_geo = []
  1611. self.solid_geometry = ncc_obj.solid_geometry
  1612. # if milling type is climb then the move is counter-clockwise around features
  1613. milling_type = self.milling_type_radio.get_value()
  1614. for tool_iso in isotooldia:
  1615. new_geometry = []
  1616. if milling_type == 'cl':
  1617. isolated_geo = self.generate_envelope(tool_iso, 1)
  1618. else:
  1619. isolated_geo = self.generate_envelope(tool_iso, 0)
  1620. if isolated_geo == 'fail':
  1621. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1622. else:
  1623. try:
  1624. for geo_elem in isolated_geo:
  1625. if self.app.abort_flag:
  1626. # graceful abort requested by the user
  1627. raise FlatCAMApp.GracefulException
  1628. if isinstance(geo_elem, Polygon):
  1629. for ring in self.poly2rings(geo_elem):
  1630. new_geo = ring.intersection(bounding_box)
  1631. if new_geo and not new_geo.is_empty:
  1632. new_geometry.append(new_geo)
  1633. elif isinstance(geo_elem, MultiPolygon):
  1634. for poly in geo_elem:
  1635. for ring in self.poly2rings(poly):
  1636. new_geo = ring.intersection(bounding_box)
  1637. if new_geo and not new_geo.is_empty:
  1638. new_geometry.append(new_geo)
  1639. elif isinstance(geo_elem, LineString):
  1640. new_geo = geo_elem.intersection(bounding_box)
  1641. if new_geo:
  1642. if not new_geo.is_empty:
  1643. new_geometry.append(new_geo)
  1644. elif isinstance(geo_elem, MultiLineString):
  1645. for line_elem in geo_elem:
  1646. new_geo = line_elem.intersection(bounding_box)
  1647. if new_geo and not new_geo.is_empty:
  1648. new_geometry.append(new_geo)
  1649. except TypeError:
  1650. try:
  1651. if isinstance(isolated_geo, Polygon):
  1652. for ring in self.poly2rings(isolated_geo):
  1653. new_geo = ring.intersection(bounding_box)
  1654. if new_geo:
  1655. if not new_geo.is_empty:
  1656. new_geometry.append(new_geo)
  1657. elif isinstance(isolated_geo, LineString):
  1658. new_geo = isolated_geo.intersection(bounding_box)
  1659. if new_geo and not new_geo.is_empty:
  1660. new_geometry.append(new_geo)
  1661. elif isinstance(isolated_geo, MultiLineString):
  1662. for line_elem in isolated_geo:
  1663. new_geo = line_elem.intersection(bounding_box)
  1664. if new_geo and not new_geo.is_empty:
  1665. new_geometry.append(new_geo)
  1666. except Exception as e:
  1667. pass
  1668. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1669. for geo_e in new_geometry:
  1670. if type(geo_e) == MultiLineString:
  1671. warning_flag += 1
  1672. break
  1673. for k, v in tools_storage.items():
  1674. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1675. current_uid = int(k)
  1676. # add the solid_geometry to the current too in self.paint_tools dictionary
  1677. # and then reset the temporary list that stored that solid_geometry
  1678. v['solid_geometry'] = deepcopy(new_geometry)
  1679. v['data']['name'] = name
  1680. break
  1681. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1682. sol_geo = cascaded_union(isolated_geo)
  1683. if has_offset is True:
  1684. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1685. _("Buffering"))
  1686. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1687. app_obj.inform.emit('[success] %s ...' %
  1688. _("Buffering finished"))
  1689. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1690. if empty == 'fail':
  1691. return 'fail'
  1692. elif isinstance(ncc_obj, FlatCAMGeometry):
  1693. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1694. if has_offset is True:
  1695. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1696. _("Buffering"))
  1697. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1698. app_obj.inform.emit('[success] %s ...' %
  1699. _("Buffering finished"))
  1700. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1701. if empty == 'fail':
  1702. return 'fail'
  1703. else:
  1704. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1705. _('The selected object is not suitable for copper clearing.'))
  1706. return
  1707. if empty.is_empty:
  1708. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1709. _("Could not get the extent of the area to be non copper cleared."))
  1710. return 'fail'
  1711. if self.app.abort_flag:
  1712. # graceful abort requested by the user
  1713. raise FlatCAMApp.GracefulException
  1714. if type(empty) is Polygon:
  1715. empty = MultiPolygon([empty])
  1716. area = empty.buffer(0)
  1717. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1718. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  1719. # Generate area for each tool
  1720. while sorted_tools:
  1721. if self.app.abort_flag:
  1722. # graceful abort requested by the user
  1723. raise FlatCAMApp.GracefulException
  1724. tool = sorted_tools.pop(0)
  1725. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1726. app_obj.inform.emit(
  1727. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1728. str(tool),
  1729. units.lower(),
  1730. _('started.'))
  1731. )
  1732. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1733. tool_used = tool - 1e-12
  1734. cleared_geo[:] = []
  1735. # Area to clear
  1736. for poly in cleared_by_last_tool:
  1737. if self.app.abort_flag:
  1738. # graceful abort requested by the user
  1739. raise FlatCAMApp.GracefulException
  1740. try:
  1741. area = area.difference(poly)
  1742. except Exception as e:
  1743. pass
  1744. cleared_by_last_tool[:] = []
  1745. # Transform area to MultiPolygon
  1746. if type(area) is Polygon:
  1747. area = MultiPolygon([area])
  1748. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1749. # and rest_geo it's a list
  1750. allparts = [p.buffer(0) for p in area.geoms]
  1751. allparts += deepcopy(rest_geo)
  1752. rest_geo[:] = []
  1753. area = MultiPolygon(deepcopy(allparts))
  1754. allparts[:] = []
  1755. # variables to display the percentage of work done
  1756. geo_len = len(area.geoms)
  1757. disp_number = 0
  1758. old_disp_number = 0
  1759. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1760. if area.geoms:
  1761. if len(area.geoms) > 0:
  1762. pol_nr = 0
  1763. for p in area.geoms:
  1764. if self.app.abort_flag:
  1765. # graceful abort requested by the user
  1766. raise FlatCAMApp.GracefulException
  1767. if p is not None:
  1768. if isinstance(p, Polygon):
  1769. try:
  1770. if ncc_method == 'standard':
  1771. cp = self.clear_polygon(p, tool_used,
  1772. self.app.defaults["gerber_circle_steps"],
  1773. overlap=overlap, contour=contour, connect=connect,
  1774. prog_plot=prog_plot)
  1775. elif ncc_method == 'seed':
  1776. cp = self.clear_polygon2(p, tool_used,
  1777. self.app.defaults["gerber_circle_steps"],
  1778. overlap=overlap, contour=contour, connect=connect,
  1779. prog_plot=prog_plot)
  1780. else:
  1781. cp = self.clear_polygon3(p, tool_used,
  1782. self.app.defaults["gerber_circle_steps"],
  1783. overlap=overlap, contour=contour, connect=connect,
  1784. prog_plot=prog_plot)
  1785. cleared_geo.append(list(cp.get_objects()))
  1786. except Exception as e:
  1787. log.warning("Polygon can't be cleared. %s" % str(e))
  1788. # this polygon should be added to a list and then try clear it with
  1789. # a smaller tool
  1790. rest_geo.append(p)
  1791. elif isinstance(p, MultiPolygon):
  1792. for poly in p:
  1793. if poly is not None:
  1794. try:
  1795. if ncc_method == 'standard':
  1796. cp = self.clear_polygon(poly, tool_used,
  1797. self.app.defaults["gerber_circle_steps"],
  1798. overlap=overlap, contour=contour,
  1799. connect=connect,
  1800. prog_plot=prog_plot)
  1801. elif ncc_method == 'seed':
  1802. cp = self.clear_polygon2(poly, tool_used,
  1803. self.app.defaults["gerber_circle_steps"],
  1804. overlap=overlap, contour=contour,
  1805. connect=connect,
  1806. prog_plot=prog_plot)
  1807. else:
  1808. cp = self.clear_polygon3(poly, tool_used,
  1809. self.app.defaults["gerber_circle_steps"],
  1810. overlap=overlap, contour=contour,
  1811. connect=connect,
  1812. prog_plot=prog_plot)
  1813. cleared_geo.append(list(cp.get_objects()))
  1814. except Exception as e:
  1815. log.warning("Polygon can't be cleared. %s" % str(e))
  1816. # this polygon should be added to a list and then try clear it with
  1817. # a smaller tool
  1818. rest_geo.append(poly)
  1819. pol_nr += 1
  1820. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1821. # log.debug("Polygons cleared: %d" % pol_nr)
  1822. if old_disp_number < disp_number <= 100:
  1823. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1824. old_disp_number = disp_number
  1825. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1826. if self.app.abort_flag:
  1827. # graceful abort requested by the user
  1828. raise FlatCAMApp.GracefulException
  1829. # check if there is a geometry at all in the cleared geometry
  1830. if cleared_geo:
  1831. # Overall cleared area
  1832. cleared_area = list(self.flatten_list(cleared_geo))
  1833. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1834. # for p in cleared_area])
  1835. # here we store the poly's already processed in the original geometry by the current tool
  1836. # into cleared_by_last_tool list
  1837. # this will be sutracted from the original geometry_to_be_cleared and make data for
  1838. # the next tool
  1839. buffer_value = tool_used / 2
  1840. for p in cleared_area:
  1841. if self.app.abort_flag:
  1842. # graceful abort requested by the user
  1843. raise FlatCAMApp.GracefulException
  1844. poly = p.buffer(buffer_value)
  1845. cleared_by_last_tool.append(poly)
  1846. # find the tooluid associated with the current tool_dia so we know
  1847. # where to add the tool solid_geometry
  1848. for k, v in tools_storage.items():
  1849. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1850. current_uid = int(k)
  1851. # add the solid_geometry to the current too in self.paint_tools dictionary
  1852. # and then reset the temporary list that stored that solid_geometry
  1853. v['solid_geometry'] = deepcopy(cleared_area)
  1854. v['data']['name'] = name
  1855. cleared_area[:] = []
  1856. break
  1857. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1858. else:
  1859. log.debug("There are no geometries in the cleared polygon.")
  1860. geo_obj.multigeo = True
  1861. geo_obj.options["cnctooldia"] = str(tool)
  1862. # clean the progressive plotted shapes if it was used
  1863. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1864. self.temp_shapes.clear(update=True)
  1865. # check to see if geo_obj.tools is empty
  1866. # it will be updated only if there is a solid_geometry for tools
  1867. if geo_obj.tools:
  1868. if warning_flag == 0:
  1869. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  1870. else:
  1871. self.app.inform.emit(
  1872. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  1873. "isolation is broken for"), str(warning_flag), _("tools")))
  1874. return
  1875. else:
  1876. # I will use this variable for this purpose although it was meant for something else
  1877. # signal that we have no geo in the object therefore don't create it
  1878. app_obj.poly_not_cleared = False
  1879. return "fail"
  1880. # ###########################################################################################
  1881. # Create the Job function and send it to the worker to be processed in another thread #######
  1882. # ###########################################################################################
  1883. def job_thread(app_obj):
  1884. try:
  1885. if rest_machining_choice is True:
  1886. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  1887. else:
  1888. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  1889. except FlatCAMApp.GracefulException:
  1890. proc.done()
  1891. return
  1892. except Exception as e:
  1893. proc.done()
  1894. traceback.print_stack()
  1895. return
  1896. proc.done()
  1897. # focus on Selected Tab
  1898. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1899. if run_threaded:
  1900. # Promise object with the new name
  1901. self.app.collection.promise(name)
  1902. # Background
  1903. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1904. else:
  1905. job_thread(app_obj=self.app)
  1906. # def on_ncc(self):
  1907. #
  1908. # # Prepare non-copper polygons
  1909. # if self.reference_radio.get_value() == 'area':
  1910. # geo_n = self.sel_rect
  1911. #
  1912. # geo_buff_list = []
  1913. # for poly in geo_n:
  1914. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1915. # bounding_box = cascaded_union(geo_buff_list)
  1916. # else:
  1917. # geo_n = self.bound_obj.solid_geometry
  1918. #
  1919. # try:
  1920. # if isinstance(geo_n, MultiPolygon):
  1921. # env_obj = geo_n.convex_hull
  1922. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1923. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1924. # env_obj = cascaded_union(geo_n)
  1925. # else:
  1926. # env_obj = cascaded_union(geo_n)
  1927. # env_obj = env_obj.convex_hull
  1928. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1929. # except Exception as e:
  1930. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1931. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1932. # return
  1933. #
  1934. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1935. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1936. # if self.ncc_choice_offset_cb.isChecked():
  1937. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1938. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1939. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1940. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1941. # else:
  1942. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1943. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1944. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1945. # if self.ncc_choice_offset_cb.isChecked():
  1946. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1947. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1948. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1949. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1950. # else:
  1951. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1952. # else:
  1953. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1954. # return
  1955. #
  1956. # if type(empty) is Polygon:
  1957. # empty = MultiPolygon([empty])
  1958. #
  1959. # if empty.is_empty:
  1960. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1961. # return
  1962. #
  1963. # # clear non copper using standard algorithm
  1964. # if clearing_method is False:
  1965. # self.clear_non_copper(
  1966. # empty=empty,
  1967. # over=over,
  1968. # pol_method=pol_method,
  1969. # connect=connect,
  1970. # contour=contour
  1971. # )
  1972. # # clear non copper using rest machining algorithm
  1973. # else:
  1974. # self.clear_non_copper_rest(
  1975. # empty=empty,
  1976. # over=over,
  1977. # pol_method=pol_method,
  1978. # connect=connect,
  1979. # contour=contour
  1980. # )
  1981. #
  1982. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1983. #
  1984. # name = outname if outname else self.obj_name + "_ncc"
  1985. #
  1986. # # Sort tools in descending order
  1987. # sorted_tools = []
  1988. # for k, v in self.ncc_tools.items():
  1989. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1990. #
  1991. # order = self.ncc_order_radio.get_value()
  1992. # if order == 'fwd':
  1993. # sorted_tools.sort(reverse=False)
  1994. # elif order == 'rev':
  1995. # sorted_tools.sort(reverse=True)
  1996. # else:
  1997. # pass
  1998. #
  1999. # # Do job in background
  2000. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  2001. #
  2002. # def initialize(geo_obj, app_obj):
  2003. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2004. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2005. #
  2006. # cleared_geo = []
  2007. # # Already cleared area
  2008. # cleared = MultiPolygon()
  2009. #
  2010. # # flag for polygons not cleared
  2011. # app_obj.poly_not_cleared = False
  2012. #
  2013. # # Generate area for each tool
  2014. # offset = sum(sorted_tools)
  2015. # current_uid = int(1)
  2016. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2017. #
  2018. # for tool in sorted_tools:
  2019. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  2020. # cleared_geo[:] = []
  2021. #
  2022. # # Get remaining tools offset
  2023. # offset -= (tool - 1e-12)
  2024. #
  2025. # # Area to clear
  2026. # area = empty.buffer(-offset)
  2027. # try:
  2028. # area = area.difference(cleared)
  2029. # except Exception as e:
  2030. # continue
  2031. #
  2032. # # Transform area to MultiPolygon
  2033. # if type(area) is Polygon:
  2034. # area = MultiPolygon([area])
  2035. #
  2036. # if area.geoms:
  2037. # if len(area.geoms) > 0:
  2038. # for p in area.geoms:
  2039. # try:
  2040. # if pol_method == 'standard':
  2041. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  2042. # overlap=over, contour=contour, connect=connect)
  2043. # elif pol_method == 'seed':
  2044. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  2045. # overlap=over, contour=contour, connect=connect)
  2046. # else:
  2047. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  2048. # overlap=over, contour=contour, connect=connect)
  2049. # if cp:
  2050. # cleared_geo += list(cp.get_objects())
  2051. # except Exception as e:
  2052. # log.warning("Polygon can not be cleared. %s" % str(e))
  2053. # app_obj.poly_not_cleared = True
  2054. # continue
  2055. #
  2056. # # check if there is a geometry at all in the cleared geometry
  2057. # if cleared_geo:
  2058. # # Overall cleared area
  2059. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  2060. # tool / 1.999999)
  2061. #
  2062. # # clean-up cleared geo
  2063. # cleared = cleared.buffer(0)
  2064. #
  2065. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  2066. # # solid_geometry
  2067. # for k, v in self.ncc_tools.items():
  2068. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2069. # current_uid = int(k)
  2070. #
  2071. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2072. # # and then reset the temporary list that stored that solid_geometry
  2073. # v['solid_geometry'] = deepcopy(cleared_geo)
  2074. # v['data']['name'] = name
  2075. # break
  2076. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2077. # else:
  2078. # log.debug("There are no geometries in the cleared polygon.")
  2079. #
  2080. # geo_obj.options["cnctooldia"] = str(tool)
  2081. # geo_obj.multigeo = True
  2082. #
  2083. # def job_thread(app_obj):
  2084. # try:
  2085. # app_obj.new_object("geometry", name, initialize)
  2086. # except Exception as e:
  2087. # proc.done()
  2088. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  2089. # return
  2090. # proc.done()
  2091. #
  2092. # if app_obj.poly_not_cleared is False:
  2093. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  2094. # else:
  2095. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  2096. # 'Check the result.'))
  2097. # # reset the variable for next use
  2098. # app_obj.poly_not_cleared = False
  2099. #
  2100. # # focus on Selected Tab
  2101. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2102. #
  2103. # # Promise object with the new name
  2104. # self.app.collection.promise(name)
  2105. #
  2106. # # Background
  2107. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2108. #
  2109. # # clear copper with 'rest-machining' algorithm
  2110. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  2111. #
  2112. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2113. #
  2114. # # Sort tools in descending order
  2115. # sorted_tools = []
  2116. # for k, v in self.ncc_tools.items():
  2117. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  2118. # sorted_tools.sort(reverse=True)
  2119. #
  2120. # # Do job in background
  2121. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  2122. #
  2123. # def initialize_rm(geo_obj, app_obj):
  2124. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2125. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2126. #
  2127. # cleared_geo = []
  2128. # cleared_by_last_tool = []
  2129. # rest_geo = []
  2130. # current_uid = 1
  2131. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2132. #
  2133. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2134. # app_obj.poly_not_cleared = True
  2135. #
  2136. # area = empty.buffer(0)
  2137. # # Generate area for each tool
  2138. # while sorted_tools:
  2139. # tool = sorted_tools.pop(0)
  2140. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  2141. #
  2142. # tool_used = tool - 1e-12
  2143. # cleared_geo[:] = []
  2144. #
  2145. # # Area to clear
  2146. # for poly in cleared_by_last_tool:
  2147. # try:
  2148. # area = area.difference(poly)
  2149. # except Exception as e:
  2150. # pass
  2151. # cleared_by_last_tool[:] = []
  2152. #
  2153. # # Transform area to MultiPolygon
  2154. # if type(area) is Polygon:
  2155. # area = MultiPolygon([area])
  2156. #
  2157. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2158. # # and rest_geo it's a list
  2159. # allparts = [p.buffer(0) for p in area.geoms]
  2160. # allparts += deepcopy(rest_geo)
  2161. # rest_geo[:] = []
  2162. # area = MultiPolygon(deepcopy(allparts))
  2163. # allparts[:] = []
  2164. #
  2165. # if area.geoms:
  2166. # if len(area.geoms) > 0:
  2167. # for p in area.geoms:
  2168. # try:
  2169. # if pol_method == 'standard':
  2170. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  2171. # overlap=over, contour=contour, connect=connect)
  2172. # elif pol_method == 'seed':
  2173. # cp = self.clear_polygon2(p, tool_used,
  2174. # self.app.defaults["gerber_circle_steps"],
  2175. # overlap=over, contour=contour, connect=connect)
  2176. # else:
  2177. # cp = self.clear_polygon3(p, tool_used,
  2178. # self.app.defaults["gerber_circle_steps"],
  2179. # overlap=over, contour=contour, connect=connect)
  2180. # cleared_geo.append(list(cp.get_objects()))
  2181. # except:
  2182. # log.warning("Polygon can't be cleared.")
  2183. # # this polygon should be added to a list and then try clear it with a smaller tool
  2184. # rest_geo.append(p)
  2185. #
  2186. # # check if there is a geometry at all in the cleared geometry
  2187. # if cleared_geo:
  2188. # # Overall cleared area
  2189. # cleared_area = list(self.flatten_list(cleared_geo))
  2190. #
  2191. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2192. # # for p in cleared_area])
  2193. #
  2194. # # here we store the poly's already processed in the original geometry by the current tool
  2195. # # into cleared_by_last_tool list
  2196. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  2197. # # the next tool
  2198. # buffer_value = tool_used / 2
  2199. # for p in cleared_area:
  2200. # poly = p.buffer(buffer_value)
  2201. # cleared_by_last_tool.append(poly)
  2202. #
  2203. # # find the tooluid associated with the current tool_dia so we know
  2204. # # where to add the tool solid_geometry
  2205. # for k, v in self.ncc_tools.items():
  2206. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2207. # current_uid = int(k)
  2208. #
  2209. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2210. # # and then reset the temporary list that stored that solid_geometry
  2211. # v['solid_geometry'] = deepcopy(cleared_area)
  2212. # v['data']['name'] = name
  2213. # cleared_area[:] = []
  2214. # break
  2215. #
  2216. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2217. # else:
  2218. # log.debug("There are no geometries in the cleared polygon.")
  2219. #
  2220. # geo_obj.multigeo = True
  2221. # geo_obj.options["cnctooldia"] = str(tool)
  2222. #
  2223. # # check to see if geo_obj.tools is empty
  2224. # # it will be updated only if there is a solid_geometry for tools
  2225. # if geo_obj.tools:
  2226. # return
  2227. # else:
  2228. # # I will use this variable for this purpose although it was meant for something else
  2229. # # signal that we have no geo in the object therefore don't create it
  2230. # app_obj.poly_not_cleared = False
  2231. # return "fail"
  2232. #
  2233. # def job_thread(app_obj):
  2234. # try:
  2235. # app_obj.new_object("geometry", name, initialize_rm)
  2236. # except Exception as e:
  2237. # proc.done()
  2238. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  2239. # return
  2240. #
  2241. # if app_obj.poly_not_cleared is True:
  2242. # app_obj.inform.emit('[success] NCC Tool finished.')
  2243. # # focus on Selected Tab
  2244. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2245. # else:
  2246. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  2247. # 'with current settings.'))
  2248. # # focus on Project Tab
  2249. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  2250. # proc.done()
  2251. # # reset the variable for next use
  2252. # app_obj.poly_not_cleared = False
  2253. #
  2254. # # Promise object with the new name
  2255. # self.app.collection.promise(name)
  2256. #
  2257. # # Background
  2258. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2259. def get_ncc_empty_area(self, target, boundary=None):
  2260. """
  2261. Returns the complement of target geometry within
  2262. the given boundary polygon. If not specified, it defaults to
  2263. the rectangular bounding box of target geometry.
  2264. """
  2265. if isinstance(target, Polygon):
  2266. geo_len = 1
  2267. else:
  2268. geo_len = len(target)
  2269. pol_nr = 0
  2270. old_disp_number = 0
  2271. if boundary is None:
  2272. boundary = target.envelope
  2273. else:
  2274. boundary = boundary
  2275. try:
  2276. ret_val = boundary.difference(target)
  2277. except Exception as e:
  2278. try:
  2279. for el in target:
  2280. if self.app.abort_flag:
  2281. # graceful abort requested by the user
  2282. raise FlatCAMApp.GracefulException
  2283. boundary = boundary.difference(el)
  2284. pol_nr += 1
  2285. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2286. if old_disp_number < disp_number <= 100:
  2287. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2288. old_disp_number = disp_number
  2289. return boundary
  2290. except Exception as e:
  2291. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2292. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  2293. "Reload the Gerber file after this change."))
  2294. return 'fail'
  2295. return ret_val
  2296. def reset_fields(self):
  2297. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2298. def reset_usage(self):
  2299. self.obj_name = ""
  2300. self.ncc_obj = None
  2301. self.bound_obj = None
  2302. self.first_click = False
  2303. self.cursor_pos = None
  2304. self.mouse_is_dragging = False
  2305. self.sel_rect = []
  2306. @staticmethod
  2307. def poly2rings(poly):
  2308. return [poly.exterior] + [interior for interior in poly.interiors]
  2309. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2310. # isolation_geometry produces an envelope that is going on the left of the geometry
  2311. # (the copper features). To leave the least amount of burrs on the features
  2312. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2313. # the first pass is the one cutting all of the features, so it needs to be reversed
  2314. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2315. # to cut on the right side of the left over copper i.e on the left side of the features.
  2316. try:
  2317. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2318. except Exception as e:
  2319. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2320. return 'fail'
  2321. if invert:
  2322. try:
  2323. try:
  2324. pl = []
  2325. for p in geom:
  2326. if p is not None:
  2327. if isinstance(p, Polygon):
  2328. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2329. elif isinstance(p, LinearRing):
  2330. pl.append(Polygon(p.coords[::-1]))
  2331. geom = MultiPolygon(pl)
  2332. except TypeError:
  2333. if isinstance(geom, Polygon) and geom is not None:
  2334. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2335. elif isinstance(geom, LinearRing) and geom is not None:
  2336. geom = Polygon(geom.coords[::-1])
  2337. else:
  2338. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2339. type(geom))
  2340. except Exception as e:
  2341. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2342. return 'fail'
  2343. return geom