ToolNonCopperClear.py 184 KB

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