ToolNonCopperClear.py 176 KB

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