ToolNonCopperClear.py 134 KB

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