ToolNCC.py 189 KB

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