ToolNCC.py 194 KB

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