ToolNonCopperClear.py 184 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816
  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"), tooluid)
  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. offset_item = self.ncc_choice_offset_cb.get_value()
  639. offset_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 == 'tooldia':
  647. temp_dia[key] = tooldia_item
  648. # update the 'offset', 'type' and 'tool_type' sections
  649. if key == 'offset':
  650. temp_dia[key] = offset_item
  651. if key == 'type':
  652. temp_dia[key] = type_item
  653. if key == 'offset_value':
  654. temp_dia[key] = offset_value_item
  655. if key == 'data':
  656. # update the 'data' section
  657. for data_key in tooluid_value[key].keys():
  658. for form_key, form_value in self.form_fields.items():
  659. if form_key == data_key:
  660. temp_data[data_key] = form_value.get_value()
  661. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  662. # updated from self.app.defaults
  663. if data_key not in self.form_fields:
  664. temp_data[data_key] = value[data_key]
  665. temp_dia[key] = deepcopy(temp_data)
  666. temp_data.clear()
  667. if key == 'solid_geometry':
  668. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  669. temp_tools[tooluid_key] = deepcopy(temp_dia)
  670. self.ncc_tools.clear()
  671. self.ncc_tools = deepcopy(temp_tools)
  672. temp_tools.clear()
  673. self.blockSignals(False)
  674. def on_add_tool_by_key(self):
  675. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  676. text='%s:' % _('Enter a Tool Diameter'),
  677. min=0.0001, max=9999.9999, decimals=self.decimals)
  678. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  679. val, ok = tool_add_popup.get_value()
  680. if ok:
  681. if float(val) == 0:
  682. self.app.inform.emit('[WARNING_NOTCL] %s' %
  683. _("Please enter a tool diameter with non-zero value, in Float format."))
  684. return
  685. self.on_tool_add(dia=float(val))
  686. else:
  687. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  688. def install(self, icon=None, separator=None, **kwargs):
  689. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  690. def run(self, toggle=True):
  691. self.app.report_usage("ToolNonCopperClear()")
  692. if toggle:
  693. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  694. if self.app.ui.splitter.sizes()[0] == 0:
  695. self.app.ui.splitter.setSizes([1, 1])
  696. else:
  697. try:
  698. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  699. # if tab is populated with the tool but it does not have the focus, focus on it
  700. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  701. # focus on Tool Tab
  702. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  703. else:
  704. self.app.ui.splitter.setSizes([0, 1])
  705. except AttributeError:
  706. pass
  707. else:
  708. if self.app.ui.splitter.sizes()[0] == 0:
  709. self.app.ui.splitter.setSizes([1, 1])
  710. FlatCAMTool.run(self)
  711. self.set_tool_ui()
  712. # reset those objects on a new run
  713. self.ncc_obj = None
  714. self.bound_obj = None
  715. self.obj_name = ''
  716. self.bound_obj_name = ''
  717. self.build_ui()
  718. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  719. def set_tool_ui(self):
  720. self.units = self.app.defaults['units'].upper()
  721. self.tools_frame.show()
  722. self.ncc_order_radio.set_value(self.app.defaults["tools_nccorder"])
  723. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  724. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  725. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  726. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  727. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  728. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  729. self.ncc_choice_offset_cb.set_value(self.app.defaults["tools_ncc_offset_choice"])
  730. self.ncc_offset_spinner.set_value(self.app.defaults["tools_ncc_offset_value"])
  731. self.reference_radio.set_value(self.app.defaults["tools_nccref"])
  732. self.milling_type_radio.set_value(self.app.defaults["tools_nccmilling_type"])
  733. self.cutz_entry.set_value(self.app.defaults["tools_ncccutz"])
  734. self.tool_type_radio.set_value(self.app.defaults["tools_ncctool_type"])
  735. self.tipdia_entry.set_value(self.app.defaults["tools_ncctipdia"])
  736. self.tipangle_entry.set_value(self.app.defaults["tools_ncctipangle"])
  737. self.addtool_entry.set_value(self.app.defaults["tools_nccnewdia"])
  738. self.on_tool_type(val=self.tool_type_radio.get_value())
  739. # init the working variables
  740. self.default_data.clear()
  741. self.default_data = {
  742. "name": '_ncc',
  743. "plot": self.app.defaults["geometry_plot"],
  744. "cutz": float(self.cutz_entry.get_value()),
  745. "vtipdia": float(self.tipdia_entry.get_value()),
  746. "vtipangle": float(self.tipangle_entry.get_value()),
  747. "travelz": self.app.defaults["geometry_travelz"],
  748. "feedrate": self.app.defaults["geometry_feedrate"],
  749. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  750. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  751. "dwell": self.app.defaults["geometry_dwell"],
  752. "dwelltime": self.app.defaults["geometry_dwelltime"],
  753. "multidepth": self.app.defaults["geometry_multidepth"],
  754. "ppname_g": self.app.defaults["geometry_ppname_g"],
  755. "depthperpass": self.app.defaults["geometry_depthperpass"],
  756. "extracut": self.app.defaults["geometry_extracut"],
  757. "extracut_length": self.app.defaults["geometry_extracut_length"],
  758. "toolchange": self.app.defaults["geometry_toolchange"],
  759. "toolchangez": self.app.defaults["geometry_toolchangez"],
  760. "endz": self.app.defaults["geometry_endz"],
  761. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  762. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  763. "startz": self.app.defaults["geometry_startz"],
  764. "nccmargin": self.app.defaults["tools_nccmargin"],
  765. "nccmethod": self.app.defaults["tools_nccmethod"],
  766. "nccconnect": self.app.defaults["tools_nccconnect"],
  767. "ncccontour": self.app.defaults["tools_ncccontour"],
  768. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  769. "nccrest": self.app.defaults["tools_nccrest"],
  770. "nccref": self.app.defaults["tools_nccref"],
  771. "nccoffset": self.app.defaults["tools_ncc_offset_choice"],
  772. "nccoffset_value": self.app.defaults["tools_ncc_offset_value"],
  773. }
  774. try:
  775. dias = [float(self.app.defaults["tools_ncctools"])]
  776. except (ValueError, TypeError):
  777. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",") if dia != '']
  778. if not dias:
  779. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  780. return
  781. self.tooluid = 0
  782. self.ncc_tools.clear()
  783. for tool_dia in dias:
  784. self.tooluid += 1
  785. self.ncc_tools.update({
  786. int(self.tooluid): {
  787. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  788. 'offset': 'Path',
  789. 'offset_value': 0.0,
  790. 'type': 'Iso',
  791. 'tool_type': self.tool_type_radio.get_value(),
  792. 'operation': 'clear_op',
  793. 'data': deepcopy(self.default_data),
  794. 'solid_geometry': []
  795. }
  796. })
  797. self.obj_name = ""
  798. self.ncc_obj = None
  799. self.bound_obj_name = ""
  800. self.bound_obj = None
  801. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  802. self.units = self.app.defaults['units'].upper()
  803. def build_ui(self):
  804. self.ui_disconnect()
  805. # updated units
  806. self.units = self.app.defaults['units'].upper()
  807. sorted_tools = []
  808. for k, v in self.ncc_tools.items():
  809. if self.units == "IN":
  810. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  811. else:
  812. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  813. order = self.ncc_order_radio.get_value()
  814. if order == 'fwd':
  815. sorted_tools.sort(reverse=False)
  816. elif order == 'rev':
  817. sorted_tools.sort(reverse=True)
  818. else:
  819. pass
  820. n = len(sorted_tools)
  821. self.tools_table.setRowCount(n)
  822. tool_id = 0
  823. for tool_sorted in sorted_tools:
  824. for tooluid_key, tooluid_value in self.ncc_tools.items():
  825. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  826. tool_id += 1
  827. id_ = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  828. id_.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  829. row_no = tool_id - 1
  830. self.tools_table.setItem(row_no, 0, id_) # Tool name/id
  831. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  832. # There are no drill bits in MM with more than 2 decimals diameter
  833. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  834. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  835. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  836. tool_type_item = QtWidgets.QComboBox()
  837. for item in self.tool_type_item_options:
  838. tool_type_item.addItem(item)
  839. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  840. idx = tool_type_item.findText(tooluid_value['tool_type'])
  841. tool_type_item.setCurrentIndex(idx)
  842. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  843. operation_type = QtWidgets.QComboBox()
  844. operation_type.addItem('iso_op')
  845. # operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  846. operation_type.addItem('clear_op')
  847. # operation_type.setStyleSheet('background-color: rgb(255,255,255)')
  848. op_idx = operation_type.findText(tooluid_value['operation'])
  849. operation_type.setCurrentIndex(op_idx)
  850. self.tools_table.setItem(row_no, 1, dia) # Diameter
  851. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  852. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  853. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  854. self.tools_table.setCellWidget(row_no, 4, operation_type)
  855. # make the diameter column editable
  856. for row in range(tool_id):
  857. self.tools_table.item(row, 1).setFlags(
  858. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  859. # all the tools are selected by default
  860. self.tools_table.selectColumn(0)
  861. #
  862. self.tools_table.resizeColumnsToContents()
  863. self.tools_table.resizeRowsToContents()
  864. vertical_header = self.tools_table.verticalHeader()
  865. vertical_header.hide()
  866. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  867. horizontal_header = self.tools_table.horizontalHeader()
  868. horizontal_header.setMinimumSectionSize(10)
  869. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  870. horizontal_header.resizeSection(0, 20)
  871. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  872. # self.tools_table.setSortingEnabled(True)
  873. # sort by tool diameter
  874. # self.tools_table.sortItems(1)
  875. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  876. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  877. self.ui_connect()
  878. def ui_connect(self):
  879. self.tools_table.itemChanged.connect(self.on_tool_edit)
  880. for row in range(self.tools_table.rowCount()):
  881. try:
  882. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  883. except AttributeError:
  884. pass
  885. try:
  886. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  887. except AttributeError:
  888. pass
  889. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  890. # first disconnect
  891. for opt in self.form_fields:
  892. current_widget = self.form_fields[opt]
  893. if isinstance(current_widget, FCCheckBox):
  894. try:
  895. current_widget.stateChanged.disconnect(self.form_to_storage)
  896. except (TypeError, ValueError):
  897. pass
  898. if isinstance(current_widget, RadioSet):
  899. try:
  900. current_widget.activated_custom.disconnect(self.form_to_storage)
  901. except (TypeError, ValueError):
  902. pass
  903. elif isinstance(current_widget, FCDoubleSpinner):
  904. try:
  905. current_widget.returnPressed.disconnect(self.form_to_storage)
  906. except (TypeError, ValueError):
  907. pass
  908. for opt in self.form_fields:
  909. current_widget = self.form_fields[opt]
  910. if isinstance(current_widget, FCCheckBox):
  911. current_widget.stateChanged.connect(self.form_to_storage)
  912. if isinstance(current_widget, RadioSet):
  913. current_widget.activated_custom.connect(self.form_to_storage)
  914. elif isinstance(current_widget, FCDoubleSpinner):
  915. current_widget.returnPressed.connect(self.form_to_storage)
  916. def ui_disconnect(self):
  917. try:
  918. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  919. self.tools_table.itemChanged.disconnect()
  920. except (TypeError, AttributeError):
  921. pass
  922. try:
  923. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  924. self.tool_type_radio.activated_custom.disconnect()
  925. except (TypeError, AttributeError):
  926. pass
  927. for row in range(self.tools_table.rowCount()):
  928. for col in [2, 4]:
  929. try:
  930. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  931. except (TypeError, AttributeError):
  932. pass
  933. for opt in self.form_fields:
  934. current_widget = self.form_fields[opt]
  935. if isinstance(current_widget, FCCheckBox):
  936. try:
  937. current_widget.stateChanged.disconnect()
  938. except (TypeError, ValueError):
  939. pass
  940. if isinstance(current_widget, RadioSet):
  941. try:
  942. current_widget.activated_custom.disconnect()
  943. except (TypeError, ValueError):
  944. pass
  945. elif isinstance(current_widget, FCDoubleSpinner):
  946. try:
  947. current_widget.returnPressed.disconnect()
  948. except (TypeError, ValueError):
  949. pass
  950. def on_combo_box_type(self):
  951. obj_type = self.box_combo_type.currentIndex()
  952. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  953. self.box_combo.setCurrentIndex(0)
  954. def on_toggle_reference(self):
  955. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  956. self.box_combo.hide()
  957. self.box_combo_label.hide()
  958. self.box_combo_type.hide()
  959. self.box_combo_type_label.hide()
  960. else:
  961. self.box_combo.show()
  962. self.box_combo_label.show()
  963. self.box_combo_type.show()
  964. self.box_combo_type_label.show()
  965. def on_offset_choice(self, state):
  966. if state:
  967. self.ncc_offset_label.show()
  968. self.ncc_offset_spinner.show()
  969. else:
  970. self.ncc_offset_label.hide()
  971. self.ncc_offset_spinner.hide()
  972. def on_order_changed(self, order):
  973. if order != 'no':
  974. self.build_ui()
  975. def on_rest_machining_check(self, state):
  976. if state:
  977. self.ncc_order_radio.set_value('rev')
  978. self.ncc_order_label.setDisabled(True)
  979. self.ncc_order_radio.setDisabled(True)
  980. else:
  981. self.ncc_order_label.setDisabled(False)
  982. self.ncc_order_radio.setDisabled(False)
  983. def on_tooltable_cellwidget_change(self):
  984. cw = self.sender()
  985. cw_index = self.tools_table.indexAt(cw.pos())
  986. cw_row = cw_index.row()
  987. cw_col = cw_index.column()
  988. current_uid = int(self.tools_table.item(cw_row, 3).text())
  989. # if the sender is in the column with index 2 then we update the tool_type key
  990. if cw_col == 2:
  991. tt = cw.currentText()
  992. typ = 'Iso' if tt == 'V' else "Rough"
  993. self.ncc_tools[current_uid].update({
  994. 'type': typ,
  995. 'tool_type': tt,
  996. })
  997. if cw_col == 4:
  998. op = cw.currentText()
  999. if op == 'iso_op':
  1000. self.milling_type_label.show()
  1001. self.milling_type_radio.show()
  1002. else:
  1003. self.milling_type_label.hide()
  1004. self.milling_type_radio.hide()
  1005. self.ncc_tools[current_uid].update({
  1006. 'operation': op
  1007. })
  1008. def on_tool_type(self, val):
  1009. if val == 'V':
  1010. self.addtool_entry_lbl.setDisabled(True)
  1011. self.addtool_entry.setDisabled(True)
  1012. self.tipdialabel.show()
  1013. self.tipdia_entry.show()
  1014. self.tipanglelabel.show()
  1015. self.tipangle_entry.show()
  1016. else:
  1017. self.addtool_entry_lbl.setDisabled(False)
  1018. self.addtool_entry.setDisabled(False)
  1019. self.tipdialabel.hide()
  1020. self.tipdia_entry.hide()
  1021. self.tipanglelabel.hide()
  1022. self.tipangle_entry.hide()
  1023. def on_calculate_tooldia(self):
  1024. if self.tool_type_radio.get_value() == 'V':
  1025. tip_dia = float(self.tipdia_entry.get_value())
  1026. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1027. cut_z = float(self.cutz_entry.get_value())
  1028. cut_z = -cut_z if cut_z < 0 else cut_z
  1029. # calculated tool diameter so the cut_z parameter is obeyed
  1030. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1031. # update the default_data so it is used in the ncc_tools dict
  1032. self.default_data.update({
  1033. "vtipdia": tip_dia,
  1034. "vtipangle": (tip_angle * 2),
  1035. })
  1036. self.addtool_entry.set_value(tool_dia)
  1037. return tool_dia
  1038. else:
  1039. return float(self.addtool_entry.get_value())
  1040. def on_tool_add(self, dia=None, muted=None):
  1041. self.blockSignals(True)
  1042. self.units = self.app.defaults['units'].upper()
  1043. if dia:
  1044. tool_dia = dia
  1045. else:
  1046. tool_dia = self.on_calculate_tooldia()
  1047. if tool_dia is None:
  1048. self.build_ui()
  1049. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1050. return
  1051. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1052. if tool_dia == 0:
  1053. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1054. "in Float format."))
  1055. return
  1056. # construct a list of all 'tooluid' in the self.tools
  1057. tool_uid_list = []
  1058. for tooluid_key in self.ncc_tools:
  1059. tool_uid_item = int(tooluid_key)
  1060. tool_uid_list.append(tool_uid_item)
  1061. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1062. if not tool_uid_list:
  1063. max_uid = 0
  1064. else:
  1065. max_uid = max(tool_uid_list)
  1066. self.tooluid = int(max_uid + 1)
  1067. tool_dias = []
  1068. for k, v in self.ncc_tools.items():
  1069. for tool_v in v.keys():
  1070. if tool_v == 'tooldia':
  1071. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1072. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1073. if muted is None:
  1074. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  1075. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1076. self.blockSignals(False)
  1077. return
  1078. else:
  1079. if muted is None:
  1080. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1081. self.ncc_tools.update({
  1082. int(self.tooluid): {
  1083. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1084. 'offset': 'Path',
  1085. 'offset_value': 0.0,
  1086. 'type': 'Iso',
  1087. 'tool_type': self.tool_type_radio.get_value(),
  1088. 'operation': 'clear_op',
  1089. 'data': deepcopy(self.default_data),
  1090. 'solid_geometry': []
  1091. }
  1092. })
  1093. self.blockSignals(False)
  1094. self.build_ui()
  1095. def on_tool_edit(self):
  1096. self.blockSignals(True)
  1097. old_tool_dia = ''
  1098. tool_dias = []
  1099. for k, v in self.ncc_tools.items():
  1100. for tool_v in v.keys():
  1101. if tool_v == 'tooldia':
  1102. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1103. for row in range(self.tools_table.rowCount()):
  1104. try:
  1105. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1106. except ValueError:
  1107. # try to convert comma to decimal point. if it's still not working error message and return
  1108. try:
  1109. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1110. except ValueError:
  1111. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1112. self.blockSignals(False)
  1113. return
  1114. tooluid = int(self.tools_table.item(row, 3).text())
  1115. # identify the tool that was edited and get it's tooluid
  1116. if new_tool_dia not in tool_dias:
  1117. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  1118. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1119. self.blockSignals(False)
  1120. self.build_ui()
  1121. return
  1122. else:
  1123. # identify the old tool_dia and restore the text in tool table
  1124. for k, v in self.ncc_tools.items():
  1125. if k == tooluid:
  1126. old_tool_dia = v['tooldia']
  1127. break
  1128. restore_dia_item = self.tools_table.item(row, 1)
  1129. restore_dia_item.setText(str(old_tool_dia))
  1130. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Edit cancelled. "
  1131. "New diameter value is already in the Tool Table."))
  1132. self.blockSignals(False)
  1133. self.build_ui()
  1134. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1135. """
  1136. Will delete a tool in the tool table
  1137. :param rows_to_delete: which rows to delete; can be a list
  1138. :param all_tools: delete all tools in the tool table
  1139. :return:
  1140. """
  1141. self.blockSignals(True)
  1142. deleted_tools_list = []
  1143. if all_tools:
  1144. self.paint_tools.clear()
  1145. self.blockSignals(False)
  1146. self.build_ui()
  1147. return
  1148. if rows_to_delete:
  1149. try:
  1150. for row in rows_to_delete:
  1151. tooluid_del = int(self.tools_table.item(row, 3).text())
  1152. deleted_tools_list.append(tooluid_del)
  1153. except TypeError:
  1154. deleted_tools_list.append(rows_to_delete)
  1155. for t in deleted_tools_list:
  1156. self.ncc_tools.pop(t, None)
  1157. self.blockSignals(False)
  1158. self.build_ui()
  1159. return
  1160. try:
  1161. if self.tools_table.selectedItems():
  1162. for row_sel in self.tools_table.selectedItems():
  1163. row = row_sel.row()
  1164. if row < 0:
  1165. continue
  1166. tooluid_del = int(self.tools_table.item(row, 3).text())
  1167. deleted_tools_list.append(tooluid_del)
  1168. for t in deleted_tools_list:
  1169. self.ncc_tools.pop(t, None)
  1170. except AttributeError:
  1171. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1172. self.blockSignals(False)
  1173. return
  1174. except Exception as e:
  1175. log.debug(str(e))
  1176. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1177. self.blockSignals(False)
  1178. self.build_ui()
  1179. def on_ncc_click(self):
  1180. """
  1181. Slot for clicking signal of the self.generate.ncc_button
  1182. :return: None
  1183. """
  1184. # init values for the next usage
  1185. self.reset_usage()
  1186. self.app.report_usage("on_paint_button_click")
  1187. self.overlap = float(self.ncc_overlap_entry.get_value()) / 100.0
  1188. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  1189. self.connect = self.ncc_connect_cb.get_value()
  1190. self.contour = self.ncc_contour_cb.get_value()
  1191. self.has_offset = self.ncc_choice_offset_cb.isChecked()
  1192. self.rest = self.ncc_rest_cb.get_value()
  1193. self.obj_name = self.object_combo.currentText()
  1194. # Get source object.
  1195. try:
  1196. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  1197. except Exception as e:
  1198. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1199. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1200. if self.ncc_obj is None:
  1201. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1202. return
  1203. # use the selected tools in the tool table; get diameters for non-copper clear
  1204. self.iso_dia_list = list()
  1205. # use the selected tools in the tool table; get diameters for non-copper clear
  1206. self.ncc_dia_list = list()
  1207. if self.tools_table.selectedItems():
  1208. for x in self.tools_table.selectedItems():
  1209. try:
  1210. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1211. except ValueError:
  1212. # try to convert comma to decimal point. if it's still not working error message and return
  1213. try:
  1214. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1215. except ValueError:
  1216. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  1217. "use a number."))
  1218. continue
  1219. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  1220. self.iso_dia_list.append(self.tooldia)
  1221. else:
  1222. self.ncc_dia_list.append(self.tooldia)
  1223. else:
  1224. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1225. return
  1226. self.o_name = '%s_ncc' % self.obj_name
  1227. self.select_method = self.reference_radio.get_value()
  1228. if self.select_method == 'itself':
  1229. self.bound_obj_name = self.object_combo.currentText()
  1230. # Get source object.
  1231. try:
  1232. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1233. except Exception as e:
  1234. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1235. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  1236. self.clear_copper(ncc_obj=self.ncc_obj,
  1237. ncctooldia=self.ncc_dia_list,
  1238. isotooldia=self.iso_dia_list,
  1239. has_offset=self.has_offset,
  1240. outname=self.o_name,
  1241. overlap=self.overlap,
  1242. connect=self.connect,
  1243. contour=self.contour,
  1244. rest=self.rest)
  1245. elif self.select_method == 'area':
  1246. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1247. if self.app.is_legacy is False:
  1248. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1249. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1250. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1251. else:
  1252. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1253. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1254. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1255. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1256. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1257. elif self.select_method == 'box':
  1258. self.bound_obj_name = self.box_combo.currentText()
  1259. # Get source object.
  1260. try:
  1261. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1262. except Exception as e:
  1263. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1264. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1265. self.clear_copper(ncc_obj=self.ncc_obj,
  1266. sel_obj=self.bound_obj,
  1267. ncctooldia=self.ncc_dia_list,
  1268. isotooldia=self.iso_dia_list,
  1269. has_offset=self.has_offset,
  1270. outname=self.o_name,
  1271. overlap=self.overlap,
  1272. connect=self.connect,
  1273. contour=self.contour,
  1274. rest=self.rest)
  1275. # To be called after clicking on the plot.
  1276. def on_mouse_release(self, event):
  1277. if self.app.is_legacy is False:
  1278. event_pos = event.pos
  1279. event_is_dragging = event.is_dragging
  1280. right_button = 2
  1281. else:
  1282. event_pos = (event.xdata, event.ydata)
  1283. event_is_dragging = self.app.plotcanvas.is_dragging
  1284. right_button = 3
  1285. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1286. # do clear area only for left mouse clicks
  1287. if event.button == 1:
  1288. if self.first_click is False:
  1289. self.first_click = True
  1290. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1291. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1292. if self.app.grid_status() == True:
  1293. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1294. else:
  1295. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1296. self.app.delete_selection_shape()
  1297. if self.app.grid_status() == True:
  1298. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1299. else:
  1300. curr_pos = (event_pos[0], event_pos[1])
  1301. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1302. x1, y1 = curr_pos[0], curr_pos[1]
  1303. pt1 = (x0, y0)
  1304. pt2 = (x1, y0)
  1305. pt3 = (x1, y1)
  1306. pt4 = (x0, y1)
  1307. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1308. self.sel_rect.append(new_rectangle)
  1309. # add a temporary shape on canvas
  1310. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1311. self.first_click = False
  1312. return
  1313. elif event.button == right_button and self.mouse_is_dragging == False:
  1314. self.first_click = False
  1315. self.delete_tool_selection_shape()
  1316. if self.app.is_legacy is False:
  1317. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1318. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1319. else:
  1320. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1321. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1322. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1323. self.app.on_mouse_click_over_plot)
  1324. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1325. self.app.on_mouse_move_over_plot)
  1326. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1327. self.app.on_mouse_click_release_over_plot)
  1328. if len(self.sel_rect) == 0:
  1329. return
  1330. self.sel_rect = cascaded_union(self.sel_rect)
  1331. self.clear_copper(ncc_obj=self.ncc_obj,
  1332. sel_obj=self.bound_obj,
  1333. ncctooldia=self.ncc_dia_list,
  1334. isotooldia=self.iso_dia_list,
  1335. has_offset=self.has_offset,
  1336. outname=self.o_name,
  1337. overlap=self.overlap,
  1338. connect=self.connect,
  1339. contour=self.contour,
  1340. rest=self.rest)
  1341. # called on mouse move
  1342. def on_mouse_move(self, event):
  1343. if self.app.is_legacy is False:
  1344. event_pos = event.pos
  1345. event_is_dragging = event.is_dragging
  1346. right_button = 2
  1347. else:
  1348. event_pos = (event.xdata, event.ydata)
  1349. event_is_dragging = self.app.plotcanvas.is_dragging
  1350. right_button = 3
  1351. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1352. # detect mouse dragging motion
  1353. if event_is_dragging is True:
  1354. self.mouse_is_dragging = True
  1355. else:
  1356. self.mouse_is_dragging = False
  1357. # update the cursor position
  1358. if self.app.grid_status() == True:
  1359. # Update cursor
  1360. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1361. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1362. symbol='++', edge_color=self.app.cursor_color_3D,
  1363. edge_width=self.app.defaults["global_cursor_width"],
  1364. size=self.app.defaults["global_cursor_size"])
  1365. # update the positions on status bar
  1366. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1367. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1368. if self.cursor_pos is None:
  1369. self.cursor_pos = (0, 0)
  1370. dx = curr_pos[0] - float(self.cursor_pos[0])
  1371. dy = curr_pos[1] - float(self.cursor_pos[1])
  1372. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1373. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1374. # draw the utility geometry
  1375. if self.first_click:
  1376. self.app.delete_selection_shape()
  1377. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1378. coords=(curr_pos[0], curr_pos[1]))
  1379. def clear_copper(self, ncc_obj,
  1380. sel_obj=None,
  1381. ncctooldia=None,
  1382. isotooldia=None,
  1383. margin=None,
  1384. has_offset=None,
  1385. offset=None,
  1386. select_method=None,
  1387. outname=None,
  1388. overlap=None,
  1389. connect=None,
  1390. contour=None,
  1391. order=None,
  1392. method=None,
  1393. rest=None,
  1394. tools_storage=None,
  1395. plot=True,
  1396. run_threaded=True):
  1397. """
  1398. Clear the excess copper from the entire object.
  1399. :param ncc_obj: ncc cleared object
  1400. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1401. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1402. :param overlap: value by which the paths will overlap
  1403. :param order: if the tools are ordered and how
  1404. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1405. another object
  1406. :param has_offset: True if an offset is needed
  1407. :param offset: distance from the copper features where the copper clearing is stopping
  1408. :param margin: a border around cleared area
  1409. :param outname: name of the resulting object
  1410. :param connect: Connect lines to avoid tool lifts.
  1411. :param contour: Paint around the edges.
  1412. :param method: choice out of 'seed', 'normal', 'lines'
  1413. :param rest: True if to use rest-machining
  1414. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1415. Usage of the different one is related to when this function is called from a TcL command.
  1416. :param plot: if True after the job is finished the result will be plotted, else it will not.
  1417. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1418. run non-threaded for TclShell usage
  1419. :return:
  1420. """
  1421. if run_threaded:
  1422. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1423. else:
  1424. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1425. QtWidgets.QApplication.processEvents()
  1426. # #####################################################################
  1427. # ####### Read the parameters #########################################
  1428. # #####################################################################
  1429. units = self.app.defaults['units']
  1430. log.debug("NCC Tool started. Reading parameters.")
  1431. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  1432. ncc_method = method if method else self.ncc_method_radio.get_value()
  1433. if margin is not None:
  1434. ncc_margin = margin
  1435. else:
  1436. ncc_margin = float(self.ncc_margin_entry.get_value())
  1437. if select_method is not None:
  1438. ncc_select = select_method
  1439. else:
  1440. ncc_select = self.reference_radio.get_value()
  1441. overlap = overlap if overlap is not None else float(self.app.defaults["tools_nccoverlap"]) / 100.0
  1442. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1443. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1444. order = order if order else self.ncc_order_radio.get_value()
  1445. # determine if to use the progressive plotting
  1446. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1447. prog_plot = True
  1448. else:
  1449. prog_plot = False
  1450. if tools_storage is not None:
  1451. tools_storage = tools_storage
  1452. else:
  1453. tools_storage = self.ncc_tools
  1454. ncc_offset = 0.0
  1455. if has_offset is True:
  1456. if offset is not None:
  1457. ncc_offset = offset
  1458. else:
  1459. try:
  1460. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1461. except ValueError:
  1462. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1463. return
  1464. # ######################################################################################################
  1465. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1466. # ######################################################################################################
  1467. sorted_tools = []
  1468. if ncctooldia is not None:
  1469. try:
  1470. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1471. except AttributeError:
  1472. if not isinstance(ncctooldia, list):
  1473. sorted_tools = [float(ncctooldia)]
  1474. else:
  1475. sorted_tools = ncctooldia
  1476. else:
  1477. for row in range(self.tools_table.rowCount()):
  1478. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1479. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1480. # ##############################################################################################################
  1481. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1482. # ##############################################################################################################
  1483. log.debug("NCC Tool. Preparing non-copper polygons.")
  1484. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1485. try:
  1486. if sel_obj is None or sel_obj == 'itself':
  1487. ncc_sel_obj = ncc_obj
  1488. else:
  1489. ncc_sel_obj = sel_obj
  1490. except Exception as e:
  1491. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1492. return 'fail'
  1493. bounding_box = None
  1494. if ncc_select == 'itself':
  1495. geo_n = ncc_sel_obj.solid_geometry
  1496. try:
  1497. if isinstance(geo_n, MultiPolygon):
  1498. env_obj = geo_n.convex_hull
  1499. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1500. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1501. env_obj = cascaded_union(geo_n)
  1502. else:
  1503. env_obj = cascaded_union(geo_n)
  1504. env_obj = env_obj.convex_hull
  1505. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1506. except Exception as e:
  1507. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1508. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1509. return 'fail'
  1510. elif ncc_select == 'area':
  1511. geo_n = cascaded_union(self.sel_rect)
  1512. try:
  1513. __ = iter(geo_n)
  1514. except Exception as e:
  1515. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1516. geo_n = [geo_n]
  1517. geo_buff_list = []
  1518. for poly in geo_n:
  1519. if self.app.abort_flag:
  1520. # graceful abort requested by the user
  1521. raise FlatCAMApp.GracefulException
  1522. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1523. bounding_box = cascaded_union(geo_buff_list)
  1524. elif ncc_select == 'box':
  1525. geo_n = ncc_sel_obj.solid_geometry
  1526. if ncc_sel_obj.kind == 'geometry':
  1527. try:
  1528. __ = iter(geo_n)
  1529. except Exception as e:
  1530. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1531. geo_n = [geo_n]
  1532. geo_buff_list = []
  1533. for poly in geo_n:
  1534. if self.app.abort_flag:
  1535. # graceful abort requested by the user
  1536. raise FlatCAMApp.GracefulException
  1537. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1538. bounding_box = cascaded_union(geo_buff_list)
  1539. elif ncc_sel_obj.kind == 'gerber':
  1540. geo_n = cascaded_union(geo_n).convex_hull
  1541. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1542. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1543. else:
  1544. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1545. return 'fail'
  1546. log.debug("NCC Tool. Finished non-copper polygons.")
  1547. # ########################################################################################################
  1548. # set the name for the future Geometry object
  1549. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1550. # ########################################################################################################
  1551. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1552. if rest_machining_choice is True:
  1553. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1554. else:
  1555. name = outname if outname is not None else self.obj_name + "_ncc"
  1556. # ##########################################################################################
  1557. # Initializes the new geometry object ######################################################
  1558. # ##########################################################################################
  1559. def gen_clear_area(geo_obj, app_obj):
  1560. assert geo_obj.kind == 'geometry', \
  1561. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1562. # provide the app with a way to process the GUI events when in a blocking loop
  1563. if not run_threaded:
  1564. QtWidgets.QApplication.processEvents()
  1565. log.debug("NCC Tool. Normal copper clearing task started.")
  1566. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1567. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1568. # will store the number of tools for which the isolation is broken
  1569. warning_flag = 0
  1570. if order == 'fwd':
  1571. sorted_tools.sort(reverse=False)
  1572. elif order == 'rev':
  1573. sorted_tools.sort(reverse=True)
  1574. else:
  1575. pass
  1576. cleared_geo = []
  1577. # Already cleared area
  1578. cleared = MultiPolygon()
  1579. # flag for polygons not cleared
  1580. app_obj.poly_not_cleared = False
  1581. # Generate area for each tool
  1582. offset = sum(sorted_tools)
  1583. current_uid = int(1)
  1584. try:
  1585. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1586. except TypeError:
  1587. tool = eval(self.app.defaults["tools_ncctools"])
  1588. # ###################################################################################################
  1589. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1590. # ###################################################################################################
  1591. log.debug("NCC Tool. Calculate 'empty' area.")
  1592. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1593. if ncc_obj.kind == 'gerber' and not isotooldia:
  1594. # unfortunately for this function to work time efficient,
  1595. # if the Gerber was loaded without buffering then it require the buffering now.
  1596. if self.app.defaults['gerber_buffering'] == 'no':
  1597. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1598. else:
  1599. sol_geo = ncc_obj.solid_geometry
  1600. if has_offset is True:
  1601. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1602. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1603. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1604. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1605. if empty == 'fail':
  1606. return 'fail'
  1607. if empty.is_empty:
  1608. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1609. _("Could not get the extent of the area to be non copper cleared."))
  1610. return 'fail'
  1611. elif ncc_obj.kind == 'gerber' and isotooldia:
  1612. isolated_geo = []
  1613. # unfortunately for this function to work time efficient,
  1614. # if the Gerber was loaded without buffering then it require the buffering now.
  1615. if self.app.defaults['gerber_buffering'] == 'no':
  1616. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1617. else:
  1618. self.solid_geometry = ncc_obj.solid_geometry
  1619. # if milling type is climb then the move is counter-clockwise around features
  1620. milling_type = self.milling_type_radio.get_value()
  1621. for tool_iso in isotooldia:
  1622. new_geometry = []
  1623. if milling_type == 'cl':
  1624. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1625. else:
  1626. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1627. if isolated_geo == 'fail':
  1628. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1629. else:
  1630. if ncc_margin < tool_iso:
  1631. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1632. "than isolation tool diameter."))
  1633. try:
  1634. for geo_elem in isolated_geo:
  1635. # provide the app with a way to process the GUI events when in a blocking loop
  1636. QtWidgets.QApplication.processEvents()
  1637. if self.app.abort_flag:
  1638. # graceful abort requested by the user
  1639. raise FlatCAMApp.GracefulException
  1640. if isinstance(geo_elem, Polygon):
  1641. for ring in self.poly2rings(geo_elem):
  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, MultiPolygon):
  1646. for poly in geo_elem:
  1647. for ring in self.poly2rings(poly):
  1648. new_geo = ring.intersection(bounding_box)
  1649. if new_geo and not new_geo.is_empty:
  1650. new_geometry.append(new_geo)
  1651. elif isinstance(geo_elem, LineString):
  1652. new_geo = geo_elem.intersection(bounding_box)
  1653. if new_geo:
  1654. if not new_geo.is_empty:
  1655. new_geometry.append(new_geo)
  1656. elif isinstance(geo_elem, MultiLineString):
  1657. for line_elem in geo_elem:
  1658. new_geo = line_elem.intersection(bounding_box)
  1659. if new_geo and not new_geo.is_empty:
  1660. new_geometry.append(new_geo)
  1661. except TypeError:
  1662. if isinstance(isolated_geo, Polygon):
  1663. for ring in self.poly2rings(isolated_geo):
  1664. new_geo = ring.intersection(bounding_box)
  1665. if new_geo:
  1666. if not new_geo.is_empty:
  1667. new_geometry.append(new_geo)
  1668. elif isinstance(isolated_geo, LineString):
  1669. new_geo = isolated_geo.intersection(bounding_box)
  1670. if new_geo and not new_geo.is_empty:
  1671. new_geometry.append(new_geo)
  1672. elif isinstance(isolated_geo, MultiLineString):
  1673. for line_elem in isolated_geo:
  1674. new_geo = line_elem.intersection(bounding_box)
  1675. if new_geo and not new_geo.is_empty:
  1676. new_geometry.append(new_geo)
  1677. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1678. for geo_e in new_geometry:
  1679. if type(geo_e) == MultiLineString:
  1680. warning_flag += 1
  1681. break
  1682. for k, v in tools_storage.items():
  1683. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1684. tool_iso)):
  1685. current_uid = int(k)
  1686. # add the solid_geometry to the current too in self.paint_tools dictionary
  1687. # and then reset the temporary list that stored that solid_geometry
  1688. v['solid_geometry'] = deepcopy(new_geometry)
  1689. v['data']['name'] = name
  1690. break
  1691. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1692. sol_geo = cascaded_union(isolated_geo)
  1693. if has_offset is True:
  1694. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1695. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1696. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1697. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1698. if empty == 'fail':
  1699. return 'fail'
  1700. if empty.is_empty:
  1701. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1702. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  1703. return 'fail'
  1704. elif ncc_obj.kind == 'geometry':
  1705. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1706. if has_offset is True:
  1707. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1708. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1709. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1710. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1711. if empty == 'fail':
  1712. return 'fail'
  1713. if empty.is_empty:
  1714. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1715. _("Could not get the extent of the area to be non copper cleared."))
  1716. return 'fail'
  1717. else:
  1718. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1719. return 'fail'
  1720. if type(empty) is Polygon:
  1721. empty = MultiPolygon([empty])
  1722. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1723. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1724. # COPPER CLEARING #
  1725. cp = None
  1726. for tool in sorted_tools:
  1727. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1728. if self.app.abort_flag:
  1729. # graceful abort requested by the user
  1730. raise FlatCAMApp.GracefulException
  1731. # provide the app with a way to process the GUI events when in a blocking loop
  1732. QtWidgets.QApplication.processEvents()
  1733. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1734. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1735. )
  1736. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1737. cleared_geo[:] = []
  1738. # Get remaining tools offset
  1739. offset -= (tool - 1e-12)
  1740. # Area to clear
  1741. area = empty.buffer(-offset)
  1742. try:
  1743. area = area.difference(cleared)
  1744. except Exception as e:
  1745. continue
  1746. # Transform area to MultiPolygon
  1747. if type(area) is Polygon:
  1748. area = MultiPolygon([area])
  1749. # variables to display the percentage of work done
  1750. geo_len = len(area.geoms)
  1751. old_disp_number = 0
  1752. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1753. if area.geoms:
  1754. if len(area.geoms) > 0:
  1755. pol_nr = 0
  1756. for p in area.geoms:
  1757. # provide the app with a way to process the GUI events when in a blocking loop
  1758. QtWidgets.QApplication.processEvents()
  1759. if self.app.abort_flag:
  1760. # graceful abort requested by the user
  1761. raise FlatCAMApp.GracefulException
  1762. # clean the polygon
  1763. p = p.buffer(0)
  1764. if p is not None and p.is_valid:
  1765. poly_processed = list()
  1766. try:
  1767. for pol in p:
  1768. if pol is not None and isinstance(pol, Polygon):
  1769. if ncc_method == 'standard':
  1770. cp = self.clear_polygon(pol, tool,
  1771. self.grb_circle_steps,
  1772. overlap=overlap, contour=contour,
  1773. connect=connect,
  1774. prog_plot=prog_plot)
  1775. elif ncc_method == 'seed':
  1776. cp = self.clear_polygon2(pol, tool,
  1777. self.grb_circle_steps,
  1778. overlap=overlap, contour=contour,
  1779. connect=connect,
  1780. prog_plot=prog_plot)
  1781. else:
  1782. cp = self.clear_polygon3(pol, tool,
  1783. self.grb_circle_steps,
  1784. overlap=overlap, contour=contour,
  1785. connect=connect,
  1786. prog_plot=prog_plot)
  1787. if cp:
  1788. cleared_geo += list(cp.get_objects())
  1789. poly_processed.append(True)
  1790. else:
  1791. poly_processed.append(False)
  1792. log.warning("Polygon in MultiPolygon can not be cleared.")
  1793. else:
  1794. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  1795. "It is: %s" % str(type(pol)))
  1796. except TypeError:
  1797. if isinstance(p, Polygon):
  1798. if ncc_method == 'standard':
  1799. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  1800. overlap=overlap, contour=contour, connect=connect,
  1801. prog_plot=prog_plot)
  1802. elif ncc_method == 'seed':
  1803. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  1804. overlap=overlap, contour=contour, connect=connect,
  1805. prog_plot=prog_plot)
  1806. else:
  1807. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  1808. overlap=overlap, contour=contour, connect=connect,
  1809. prog_plot=prog_plot)
  1810. if cp:
  1811. cleared_geo += list(cp.get_objects())
  1812. poly_processed.append(True)
  1813. else:
  1814. poly_processed.append(False)
  1815. log.warning("Polygon can not be cleared.")
  1816. else:
  1817. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  1818. p_cleared = poly_processed.count(True)
  1819. p_not_cleared = poly_processed.count(False)
  1820. if p_not_cleared:
  1821. app_obj.poly_not_cleared = True
  1822. if p_cleared == 0:
  1823. continue
  1824. pol_nr += 1
  1825. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1826. # log.debug("Polygons cleared: %d" % pol_nr)
  1827. if old_disp_number < disp_number <= 100:
  1828. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1829. old_disp_number = disp_number
  1830. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1831. # check if there is a geometry at all in the cleared geometry
  1832. if cleared_geo:
  1833. # Overall cleared area
  1834. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1835. tool / 1.999999)
  1836. # clean-up cleared geo
  1837. cleared = cleared.buffer(0)
  1838. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1839. # solid_geometry
  1840. for k, v in tools_storage.items():
  1841. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1842. tool)):
  1843. current_uid = int(k)
  1844. # add the solid_geometry to the current too in self.paint_tools dictionary
  1845. # and then reset the temporary list that stored that solid_geometry
  1846. v['solid_geometry'] = deepcopy(cleared_geo)
  1847. v['data']['name'] = name
  1848. break
  1849. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1850. else:
  1851. log.debug("There are no geometries in the cleared polygon.")
  1852. # clean the progressive plotted shapes if it was used
  1853. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1854. self.temp_shapes.clear(update=True)
  1855. # # delete tools with empty geometry
  1856. # keys_to_delete = []
  1857. # # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1858. # for uid in tools_storage:
  1859. # # if the solid_geometry (type=list) is empty
  1860. # if not tools_storage[uid]['solid_geometry']:
  1861. # keys_to_delete.append(uid)
  1862. #
  1863. # # actual delete of keys from the tools_storage dict
  1864. # for k in keys_to_delete:
  1865. # tools_storage.pop(k, None)
  1866. # delete tools with empty geometry
  1867. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1868. for uid, uid_val in list(tools_storage.items()):
  1869. try:
  1870. # if the solid_geometry (type=list) is empty
  1871. if not uid_val['solid_geometry']:
  1872. tools_storage.pop(uid, None)
  1873. except KeyError:
  1874. tools_storage.pop(uid, None)
  1875. geo_obj.options["cnctooldia"] = str(tool)
  1876. geo_obj.multigeo = True
  1877. geo_obj.tools.clear()
  1878. geo_obj.tools = dict(tools_storage)
  1879. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1880. has_solid_geo = 0
  1881. for tooluid in geo_obj.tools:
  1882. if geo_obj.tools[tooluid]['solid_geometry']:
  1883. has_solid_geo += 1
  1884. if has_solid_geo == 0:
  1885. app_obj.inform.emit('[ERROR] %s' %
  1886. _("There is no NCC Geometry in the file.\n"
  1887. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1888. "Change the painting parameters and try again."))
  1889. return 'fail'
  1890. # check to see if geo_obj.tools is empty
  1891. # it will be updated only if there is a solid_geometry for tools
  1892. if geo_obj.tools:
  1893. if warning_flag == 0:
  1894. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1895. else:
  1896. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1897. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1898. str(warning_flag),
  1899. _("tools")))
  1900. return
  1901. # create the solid_geometry
  1902. geo_obj.solid_geometry = list()
  1903. for tooluid in geo_obj.tools:
  1904. if geo_obj.tools[tooluid]['solid_geometry']:
  1905. try:
  1906. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1907. geo_obj.solid_geometry.append(geo)
  1908. except TypeError:
  1909. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1910. else:
  1911. # I will use this variable for this purpose although it was meant for something else
  1912. # signal that we have no geo in the object therefore don't create it
  1913. app_obj.poly_not_cleared = False
  1914. return "fail"
  1915. # create the solid_geometry
  1916. # geo_obj.solid_geometry = list()
  1917. # for tooluid in geo_obj.tools:
  1918. # if geo_obj.tools[tooluid]['solid_geometry']:
  1919. # try:
  1920. # for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1921. # geo_obj.solid_geometry.append(geo)
  1922. # except TypeError:
  1923. # geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1924. #
  1925. # # Experimental...
  1926. # # print("Indexing...", end=' ')
  1927. # # geo_obj.make_index()
  1928. # if warning_flag == 0:
  1929. # self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1930. # else:
  1931. # self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1932. # _("NCC Tool clear all done but the copper features isolation is broken for"),
  1933. # str(warning_flag),
  1934. # _("tools")))
  1935. # ###########################################################################################
  1936. # Initializes the new geometry object for the case of the rest-machining ####################
  1937. # ###########################################################################################
  1938. def gen_clear_area_rest(geo_obj, app_obj):
  1939. assert geo_obj.kind == 'geometry', \
  1940. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1941. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1942. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1943. # provide the app with a way to process the GUI events when in a blocking loop
  1944. if not run_threaded:
  1945. QtWidgets.QApplication.processEvents()
  1946. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1947. # will store the number of tools for which the isolation is broken
  1948. warning_flag = 0
  1949. sorted_tools.sort(reverse=True)
  1950. cleared_geo = []
  1951. cleared_by_last_tool = []
  1952. rest_geo = []
  1953. current_uid = 1
  1954. try:
  1955. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1956. except TypeError:
  1957. tool = eval(self.app.defaults["tools_ncctools"])
  1958. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1959. app_obj.poly_not_cleared = True
  1960. log.debug("NCC Tool. Calculate 'empty' area.")
  1961. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1962. # ###################################################################################################
  1963. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1964. # ###################################################################################################
  1965. if ncc_obj.kind == 'gerber' and not isotooldia:
  1966. sol_geo = ncc_obj.solid_geometry
  1967. if has_offset is True:
  1968. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1969. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1970. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  1971. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1972. if empty == 'fail':
  1973. return 'fail'
  1974. if empty.is_empty:
  1975. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1976. _("Could not get the extent of the area to be non copper cleared."))
  1977. return 'fail'
  1978. elif ncc_obj.kind == 'gerber' and isotooldia:
  1979. isolated_geo = []
  1980. self.solid_geometry = ncc_obj.solid_geometry
  1981. # if milling type is climb then the move is counter-clockwise around features
  1982. milling_type = self.milling_type_radio.get_value()
  1983. for tool_iso in isotooldia:
  1984. new_geometry = []
  1985. if milling_type == 'cl':
  1986. isolated_geo = self.generate_envelope(tool_iso, 1)
  1987. else:
  1988. isolated_geo = self.generate_envelope(tool_iso, 0)
  1989. if isolated_geo == 'fail':
  1990. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1991. else:
  1992. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1993. "than isolation tool diameter."))
  1994. try:
  1995. for geo_elem in isolated_geo:
  1996. # provide the app with a way to process the GUI events when in a blocking loop
  1997. QtWidgets.QApplication.processEvents()
  1998. if self.app.abort_flag:
  1999. # graceful abort requested by the user
  2000. raise FlatCAMApp.GracefulException
  2001. if isinstance(geo_elem, Polygon):
  2002. for ring in self.poly2rings(geo_elem):
  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, MultiPolygon):
  2007. for poly in geo_elem:
  2008. for ring in self.poly2rings(poly):
  2009. new_geo = ring.intersection(bounding_box)
  2010. if new_geo and not new_geo.is_empty:
  2011. new_geometry.append(new_geo)
  2012. elif isinstance(geo_elem, LineString):
  2013. new_geo = geo_elem.intersection(bounding_box)
  2014. if new_geo:
  2015. if not new_geo.is_empty:
  2016. new_geometry.append(new_geo)
  2017. elif isinstance(geo_elem, MultiLineString):
  2018. for line_elem in geo_elem:
  2019. new_geo = line_elem.intersection(bounding_box)
  2020. if new_geo and not new_geo.is_empty:
  2021. new_geometry.append(new_geo)
  2022. except TypeError:
  2023. try:
  2024. if isinstance(isolated_geo, Polygon):
  2025. for ring in self.poly2rings(isolated_geo):
  2026. new_geo = ring.intersection(bounding_box)
  2027. if new_geo:
  2028. if not new_geo.is_empty:
  2029. new_geometry.append(new_geo)
  2030. elif isinstance(isolated_geo, LineString):
  2031. new_geo = isolated_geo.intersection(bounding_box)
  2032. if new_geo and not new_geo.is_empty:
  2033. new_geometry.append(new_geo)
  2034. elif isinstance(isolated_geo, MultiLineString):
  2035. for line_elem in isolated_geo:
  2036. new_geo = line_elem.intersection(bounding_box)
  2037. if new_geo and not new_geo.is_empty:
  2038. new_geometry.append(new_geo)
  2039. except Exception as e:
  2040. pass
  2041. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2042. for geo_e in new_geometry:
  2043. if type(geo_e) == MultiLineString:
  2044. warning_flag += 1
  2045. break
  2046. for k, v in tools_storage.items():
  2047. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2048. tool_iso)):
  2049. current_uid = int(k)
  2050. # add the solid_geometry to the current too in self.paint_tools dictionary
  2051. # and then reset the temporary list that stored that solid_geometry
  2052. v['solid_geometry'] = deepcopy(new_geometry)
  2053. v['data']['name'] = name
  2054. break
  2055. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2056. sol_geo = cascaded_union(isolated_geo)
  2057. if has_offset is True:
  2058. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2059. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2060. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2061. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2062. if empty == 'fail':
  2063. return 'fail'
  2064. if empty.is_empty:
  2065. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2066. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2067. return 'fail'
  2068. elif ncc_obj.kind == 'geometry':
  2069. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2070. if has_offset is True:
  2071. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2072. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2073. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2074. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2075. if empty == 'fail':
  2076. return 'fail'
  2077. if empty.is_empty:
  2078. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2079. _("Could not get the extent of the area to be non copper cleared."))
  2080. return 'fail'
  2081. else:
  2082. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2083. return
  2084. if self.app.abort_flag:
  2085. # graceful abort requested by the user
  2086. raise FlatCAMApp.GracefulException
  2087. if type(empty) is Polygon:
  2088. empty = MultiPolygon([empty])
  2089. area = empty.buffer(0)
  2090. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2091. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2092. # Generate area for each tool
  2093. while sorted_tools:
  2094. if self.app.abort_flag:
  2095. # graceful abort requested by the user
  2096. raise FlatCAMApp.GracefulException
  2097. tool = sorted_tools.pop(0)
  2098. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2099. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2100. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2101. )
  2102. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2103. tool_used = tool - 1e-12
  2104. cleared_geo[:] = []
  2105. # Area to clear
  2106. for poly in cleared_by_last_tool:
  2107. # provide the app with a way to process the GUI events when in a blocking loop
  2108. QtWidgets.QApplication.processEvents()
  2109. if self.app.abort_flag:
  2110. # graceful abort requested by the user
  2111. raise FlatCAMApp.GracefulException
  2112. try:
  2113. area = area.difference(poly)
  2114. except Exception as e:
  2115. pass
  2116. cleared_by_last_tool[:] = []
  2117. # Transform area to MultiPolygon
  2118. if type(area) is Polygon:
  2119. area = MultiPolygon([area])
  2120. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2121. # and rest_geo it's a list
  2122. allparts = [p.buffer(0) for p in area.geoms]
  2123. allparts += deepcopy(rest_geo)
  2124. rest_geo[:] = []
  2125. area = MultiPolygon(deepcopy(allparts))
  2126. allparts[:] = []
  2127. # variables to display the percentage of work done
  2128. geo_len = len(area.geoms)
  2129. disp_number = 0
  2130. old_disp_number = 0
  2131. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2132. if area.geoms:
  2133. if len(area.geoms) > 0:
  2134. pol_nr = 0
  2135. for p in area.geoms:
  2136. if self.app.abort_flag:
  2137. # graceful abort requested by the user
  2138. raise FlatCAMApp.GracefulException
  2139. # clean the polygon
  2140. p = p.buffer(0)
  2141. if p is not None and p.is_valid:
  2142. # provide the app with a way to process the GUI events when in a blocking loop
  2143. QtWidgets.QApplication.processEvents()
  2144. if isinstance(p, Polygon):
  2145. try:
  2146. if ncc_method == 'standard':
  2147. cp = self.clear_polygon(p, tool_used,
  2148. self.grb_circle_steps,
  2149. overlap=overlap, contour=contour, connect=connect,
  2150. prog_plot=prog_plot)
  2151. elif ncc_method == 'seed':
  2152. cp = self.clear_polygon2(p, tool_used,
  2153. self.grb_circle_steps,
  2154. overlap=overlap, contour=contour, connect=connect,
  2155. prog_plot=prog_plot)
  2156. else:
  2157. cp = self.clear_polygon3(p, tool_used,
  2158. self.grb_circle_steps,
  2159. overlap=overlap, contour=contour, connect=connect,
  2160. prog_plot=prog_plot)
  2161. cleared_geo.append(list(cp.get_objects()))
  2162. except Exception as e:
  2163. log.warning("Polygon can't be cleared. %s" % str(e))
  2164. # this polygon should be added to a list and then try clear it with
  2165. # a smaller tool
  2166. rest_geo.append(p)
  2167. elif isinstance(p, MultiPolygon):
  2168. for poly in p:
  2169. if poly is not None:
  2170. # provide the app with a way to process the GUI events when
  2171. # in a blocking loop
  2172. QtWidgets.QApplication.processEvents()
  2173. try:
  2174. if ncc_method == 'standard':
  2175. cp = self.clear_polygon(poly, tool_used,
  2176. self.grb_circle_steps,
  2177. overlap=overlap, contour=contour,
  2178. connect=connect,
  2179. prog_plot=prog_plot)
  2180. elif ncc_method == 'seed':
  2181. cp = self.clear_polygon2(poly, tool_used,
  2182. self.grb_circle_steps,
  2183. overlap=overlap, contour=contour,
  2184. connect=connect,
  2185. prog_plot=prog_plot)
  2186. else:
  2187. cp = self.clear_polygon3(poly, tool_used,
  2188. self.grb_circle_steps,
  2189. overlap=overlap, contour=contour,
  2190. connect=connect,
  2191. prog_plot=prog_plot)
  2192. cleared_geo.append(list(cp.get_objects()))
  2193. except Exception as e:
  2194. log.warning("Polygon can't be cleared. %s" % str(e))
  2195. # this polygon should be added to a list and then try clear it with
  2196. # a smaller tool
  2197. rest_geo.append(poly)
  2198. pol_nr += 1
  2199. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2200. # log.debug("Polygons cleared: %d" % pol_nr)
  2201. if old_disp_number < disp_number <= 100:
  2202. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2203. old_disp_number = disp_number
  2204. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2205. if self.app.abort_flag:
  2206. # graceful abort requested by the user
  2207. raise FlatCAMApp.GracefulException
  2208. # check if there is a geometry at all in the cleared geometry
  2209. if cleared_geo:
  2210. # Overall cleared area
  2211. cleared_area = list(self.flatten_list(cleared_geo))
  2212. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2213. # for p in cleared_area])
  2214. # here we store the poly's already processed in the original geometry by the current tool
  2215. # into cleared_by_last_tool list
  2216. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2217. # the next tool
  2218. buffer_value = tool_used / 2
  2219. for p in cleared_area:
  2220. if self.app.abort_flag:
  2221. # graceful abort requested by the user
  2222. raise FlatCAMApp.GracefulException
  2223. poly = p.buffer(buffer_value)
  2224. cleared_by_last_tool.append(poly)
  2225. # find the tooluid associated with the current tool_dia so we know
  2226. # where to add the tool solid_geometry
  2227. for k, v in tools_storage.items():
  2228. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2229. tool)):
  2230. current_uid = int(k)
  2231. # add the solid_geometry to the current too in self.paint_tools dictionary
  2232. # and then reset the temporary list that stored that solid_geometry
  2233. v['solid_geometry'] = deepcopy(cleared_area)
  2234. v['data']['name'] = name
  2235. cleared_area[:] = []
  2236. break
  2237. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2238. else:
  2239. log.debug("There are no geometries in the cleared polygon.")
  2240. geo_obj.multigeo = True
  2241. geo_obj.options["cnctooldia"] = str(tool)
  2242. # clean the progressive plotted shapes if it was used
  2243. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  2244. self.temp_shapes.clear(update=True)
  2245. # check to see if geo_obj.tools is empty
  2246. # it will be updated only if there is a solid_geometry for tools
  2247. if geo_obj.tools:
  2248. if warning_flag == 0:
  2249. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2250. else:
  2251. self.app.inform.emit(
  2252. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2253. "isolation is broken for"), str(warning_flag), _("tools")))
  2254. return
  2255. # create the solid_geometry
  2256. geo_obj.solid_geometry = list()
  2257. for tooluid in geo_obj.tools:
  2258. if geo_obj.tools[tooluid]['solid_geometry']:
  2259. try:
  2260. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2261. geo_obj.solid_geometry.append(geo)
  2262. except TypeError:
  2263. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2264. else:
  2265. # I will use this variable for this purpose although it was meant for something else
  2266. # signal that we have no geo in the object therefore don't create it
  2267. app_obj.poly_not_cleared = False
  2268. return "fail"
  2269. # ###########################################################################################
  2270. # Create the Job function and send it to the worker to be processed in another thread #######
  2271. # ###########################################################################################
  2272. def job_thread(app_obj):
  2273. try:
  2274. if rest_machining_choice is True:
  2275. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  2276. else:
  2277. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  2278. except FlatCAMApp.GracefulException:
  2279. if run_threaded:
  2280. proc.done()
  2281. return
  2282. except Exception:
  2283. if run_threaded:
  2284. proc.done()
  2285. traceback.print_stack()
  2286. return
  2287. if run_threaded:
  2288. proc.done()
  2289. else:
  2290. app_obj.proc_container.view.set_idle()
  2291. # focus on Selected Tab
  2292. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2293. if run_threaded:
  2294. # Promise object with the new name
  2295. self.app.collection.promise(name)
  2296. # Background
  2297. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2298. else:
  2299. job_thread(app_obj=self.app)
  2300. def clear_copper_tcl(self, ncc_obj,
  2301. sel_obj=None,
  2302. ncctooldia=None,
  2303. isotooldia=None,
  2304. margin=None,
  2305. has_offset=None,
  2306. offset=None,
  2307. select_method=None,
  2308. outname=None,
  2309. overlap=None,
  2310. connect=None,
  2311. contour=None,
  2312. order=None,
  2313. method=None,
  2314. rest=None,
  2315. tools_storage=None,
  2316. plot=True,
  2317. run_threaded=False):
  2318. """
  2319. Clear the excess copper from the entire object. To be used only in a TCL command.
  2320. :param ncc_obj: ncc cleared object
  2321. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2322. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2323. :param overlap: value by which the paths will overlap
  2324. :param order: if the tools are ordered and how
  2325. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2326. another object
  2327. :param has_offset: True if an offset is needed
  2328. :param offset: distance from the copper features where the copper clearing is stopping
  2329. :param margin: a border around cleared area
  2330. :param outname: name of the resulting object
  2331. :param connect: Connect lines to avoid tool lifts.
  2332. :param contour: Paint around the edges.
  2333. :param method: choice out of 'seed', 'normal', 'lines'
  2334. :param rest: True if to use rest-machining
  2335. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2336. Usage of the different one is related to when this function is called from a TcL command.
  2337. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2338. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  2339. run non-threaded for TclShell usage
  2340. :return:
  2341. """
  2342. if run_threaded:
  2343. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2344. else:
  2345. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2346. QtWidgets.QApplication.processEvents()
  2347. # #####################################################################
  2348. # ####### Read the parameters #########################################
  2349. # #####################################################################
  2350. units = self.app.defaults['units']
  2351. log.debug("NCC Tool started. Reading parameters.")
  2352. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2353. ncc_method = method
  2354. ncc_margin = margin
  2355. ncc_select = select_method
  2356. overlap = overlap
  2357. connect = connect
  2358. contour = contour
  2359. order = order
  2360. if tools_storage is not None:
  2361. tools_storage = tools_storage
  2362. else:
  2363. tools_storage = self.ncc_tools
  2364. ncc_offset = 0.0
  2365. if has_offset is True:
  2366. ncc_offset = offset
  2367. # ######################################################################################################
  2368. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2369. # ######################################################################################################
  2370. sorted_tools = []
  2371. try:
  2372. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2373. except AttributeError:
  2374. if not isinstance(ncctooldia, list):
  2375. sorted_tools = [float(ncctooldia)]
  2376. else:
  2377. sorted_tools = ncctooldia
  2378. # ##############################################################################################################
  2379. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2380. # ##############################################################################################################
  2381. log.debug("NCC Tool. Preparing non-copper polygons.")
  2382. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2383. try:
  2384. if sel_obj is None or sel_obj == 'itself':
  2385. ncc_sel_obj = ncc_obj
  2386. else:
  2387. ncc_sel_obj = sel_obj
  2388. except Exception as e:
  2389. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2390. return 'fail'
  2391. bounding_box = None
  2392. if ncc_select == 'itself':
  2393. geo_n = ncc_sel_obj.solid_geometry
  2394. try:
  2395. if isinstance(geo_n, MultiPolygon):
  2396. env_obj = geo_n.convex_hull
  2397. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2398. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2399. env_obj = cascaded_union(geo_n)
  2400. else:
  2401. env_obj = cascaded_union(geo_n)
  2402. env_obj = env_obj.convex_hull
  2403. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2404. except Exception as e:
  2405. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2406. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2407. return 'fail'
  2408. elif ncc_select == 'area':
  2409. geo_n = cascaded_union(self.sel_rect)
  2410. try:
  2411. __ = iter(geo_n)
  2412. except Exception as e:
  2413. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2414. geo_n = [geo_n]
  2415. geo_buff_list = []
  2416. for poly in geo_n:
  2417. if self.app.abort_flag:
  2418. # graceful abort requested by the user
  2419. raise FlatCAMApp.GracefulException
  2420. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2421. bounding_box = cascaded_union(geo_buff_list)
  2422. elif ncc_select == 'box':
  2423. geo_n = ncc_sel_obj.solid_geometry
  2424. if ncc_sel_obj.kind == 'geometry':
  2425. try:
  2426. __ = iter(geo_n)
  2427. except Exception as e:
  2428. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  2429. geo_n = [geo_n]
  2430. geo_buff_list = []
  2431. for poly in geo_n:
  2432. if self.app.abort_flag:
  2433. # graceful abort requested by the user
  2434. raise FlatCAMApp.GracefulException
  2435. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2436. bounding_box = cascaded_union(geo_buff_list)
  2437. elif ncc_sel_obj.kind == 'gerber':
  2438. geo_n = cascaded_union(geo_n).convex_hull
  2439. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2440. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2441. else:
  2442. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2443. return 'fail'
  2444. log.debug("NCC Tool. Finished non-copper polygons.")
  2445. # ########################################################################################################
  2446. # set the name for the future Geometry object
  2447. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2448. # ########################################################################################################
  2449. rest_machining_choice = rest
  2450. if rest_machining_choice is True:
  2451. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2452. else:
  2453. name = outname if outname is not None else self.obj_name + "_ncc"
  2454. # ##########################################################################################
  2455. # Initializes the new geometry object ######################################################
  2456. # ##########################################################################################
  2457. def gen_clear_area(geo_obj, app_obj):
  2458. assert geo_obj.kind == 'geometry', \
  2459. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2460. # provide the app with a way to process the GUI events when in a blocking loop
  2461. if not run_threaded:
  2462. QtWidgets.QApplication.processEvents()
  2463. log.debug("NCC Tool. Normal copper clearing task started.")
  2464. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2465. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2466. # will store the number of tools for which the isolation is broken
  2467. warning_flag = 0
  2468. if order == 'fwd':
  2469. sorted_tools.sort(reverse=False)
  2470. elif order == 'rev':
  2471. sorted_tools.sort(reverse=True)
  2472. else:
  2473. pass
  2474. cleared_geo = []
  2475. # Already cleared area
  2476. cleared = MultiPolygon()
  2477. # flag for polygons not cleared
  2478. app_obj.poly_not_cleared = False
  2479. # Generate area for each tool
  2480. offset = sum(sorted_tools)
  2481. current_uid = int(1)
  2482. try:
  2483. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2484. except TypeError:
  2485. tool = eval(self.app.defaults["tools_ncctools"])
  2486. # ###################################################################################################
  2487. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2488. # ###################################################################################################
  2489. log.debug("NCC Tool. Calculate 'empty' area.")
  2490. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2491. if ncc_obj.kind == 'gerber' and not isotooldia:
  2492. # unfortunately for this function to work time efficient,
  2493. # if the Gerber was loaded without buffering then it require the buffering now.
  2494. if self.app.defaults['gerber_buffering'] == 'no':
  2495. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2496. else:
  2497. sol_geo = ncc_obj.solid_geometry
  2498. if has_offset is True:
  2499. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2500. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2501. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2502. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2503. if empty == 'fail':
  2504. return 'fail'
  2505. if empty.is_empty:
  2506. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2507. _("Could not get the extent of the area to be non copper cleared."))
  2508. return 'fail'
  2509. elif ncc_obj.kind == 'gerber' and isotooldia:
  2510. isolated_geo = []
  2511. # unfortunately for this function to work time efficient,
  2512. # if the Gerber was loaded without buffering then it require the buffering now.
  2513. if self.app.defaults['gerber_buffering'] == 'no':
  2514. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2515. else:
  2516. self.solid_geometry = ncc_obj.solid_geometry
  2517. # if milling type is climb then the move is counter-clockwise around features
  2518. milling_type = self.app.defaults["tools_nccmilling_type"]
  2519. for tool_iso in isotooldia:
  2520. new_geometry = []
  2521. if milling_type == 'cl':
  2522. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2523. else:
  2524. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2525. if isolated_geo == 'fail':
  2526. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2527. else:
  2528. if ncc_margin < tool_iso:
  2529. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2530. "than isolation tool diameter."))
  2531. try:
  2532. for geo_elem in isolated_geo:
  2533. # provide the app with a way to process the GUI events when in a blocking loop
  2534. QtWidgets.QApplication.processEvents()
  2535. if self.app.abort_flag:
  2536. # graceful abort requested by the user
  2537. raise FlatCAMApp.GracefulException
  2538. if isinstance(geo_elem, Polygon):
  2539. for ring in self.poly2rings(geo_elem):
  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, MultiPolygon):
  2544. for poly in geo_elem:
  2545. for ring in self.poly2rings(poly):
  2546. new_geo = ring.intersection(bounding_box)
  2547. if new_geo and not new_geo.is_empty:
  2548. new_geometry.append(new_geo)
  2549. elif isinstance(geo_elem, LineString):
  2550. new_geo = geo_elem.intersection(bounding_box)
  2551. if new_geo:
  2552. if not new_geo.is_empty:
  2553. new_geometry.append(new_geo)
  2554. elif isinstance(geo_elem, MultiLineString):
  2555. for line_elem in geo_elem:
  2556. new_geo = line_elem.intersection(bounding_box)
  2557. if new_geo and not new_geo.is_empty:
  2558. new_geometry.append(new_geo)
  2559. except TypeError:
  2560. if isinstance(isolated_geo, Polygon):
  2561. for ring in self.poly2rings(isolated_geo):
  2562. new_geo = ring.intersection(bounding_box)
  2563. if new_geo:
  2564. if not new_geo.is_empty:
  2565. new_geometry.append(new_geo)
  2566. elif isinstance(isolated_geo, LineString):
  2567. new_geo = isolated_geo.intersection(bounding_box)
  2568. if new_geo and not new_geo.is_empty:
  2569. new_geometry.append(new_geo)
  2570. elif isinstance(isolated_geo, MultiLineString):
  2571. for line_elem in isolated_geo:
  2572. new_geo = line_elem.intersection(bounding_box)
  2573. if new_geo and not new_geo.is_empty:
  2574. new_geometry.append(new_geo)
  2575. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2576. for geo_e in new_geometry:
  2577. if type(geo_e) == MultiLineString:
  2578. warning_flag += 1
  2579. break
  2580. for k, v in tools_storage.items():
  2581. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2582. tool_iso)):
  2583. current_uid = int(k)
  2584. # add the solid_geometry to the current too in self.paint_tools dictionary
  2585. # and then reset the temporary list that stored that solid_geometry
  2586. v['solid_geometry'] = deepcopy(new_geometry)
  2587. v['data']['name'] = name
  2588. break
  2589. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2590. sol_geo = cascaded_union(isolated_geo)
  2591. if has_offset is True:
  2592. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2593. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2594. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2595. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2596. if empty == 'fail':
  2597. return 'fail'
  2598. if empty.is_empty:
  2599. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2600. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2601. return 'fail'
  2602. elif ncc_obj.kind == 'geometry':
  2603. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2604. if has_offset is True:
  2605. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2606. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2607. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2608. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2609. if empty == 'fail':
  2610. return 'fail'
  2611. if empty.is_empty:
  2612. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2613. _("Could not get the extent of the area to be non copper cleared."))
  2614. return 'fail'
  2615. else:
  2616. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2617. return 'fail'
  2618. if type(empty) is Polygon:
  2619. empty = MultiPolygon([empty])
  2620. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2621. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2622. # COPPER CLEARING #
  2623. cp = None
  2624. for tool in sorted_tools:
  2625. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2626. if self.app.abort_flag:
  2627. # graceful abort requested by the user
  2628. raise FlatCAMApp.GracefulException
  2629. # provide the app with a way to process the GUI events when in a blocking loop
  2630. QtWidgets.QApplication.processEvents()
  2631. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2632. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2633. )
  2634. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2635. cleared_geo[:] = []
  2636. # Get remaining tools offset
  2637. offset -= (tool - 1e-12)
  2638. # Area to clear
  2639. area = empty.buffer(-offset)
  2640. try:
  2641. area = area.difference(cleared)
  2642. except Exception as e:
  2643. continue
  2644. # Transform area to MultiPolygon
  2645. if type(area) is Polygon:
  2646. area = MultiPolygon([area])
  2647. # variables to display the percentage of work done
  2648. geo_len = len(area.geoms)
  2649. old_disp_number = 0
  2650. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2651. if area.geoms:
  2652. if len(area.geoms) > 0:
  2653. pol_nr = 0
  2654. for p in area.geoms:
  2655. # provide the app with a way to process the GUI events when in a blocking loop
  2656. QtWidgets.QApplication.processEvents()
  2657. if self.app.abort_flag:
  2658. # graceful abort requested by the user
  2659. raise FlatCAMApp.GracefulException
  2660. # clean the polygon
  2661. p = p.buffer(0)
  2662. if p is not None and p.is_valid:
  2663. poly_processed = list()
  2664. try:
  2665. for pol in p:
  2666. if pol is not None and isinstance(pol, Polygon):
  2667. if ncc_method == 'standard':
  2668. cp = self.clear_polygon(pol, tool,
  2669. self.grb_circle_steps,
  2670. overlap=overlap, contour=contour,
  2671. connect=connect,
  2672. prog_plot=False)
  2673. elif ncc_method == 'seed':
  2674. cp = self.clear_polygon2(pol, tool,
  2675. self.grb_circle_steps,
  2676. overlap=overlap, contour=contour,
  2677. connect=connect,
  2678. prog_plot=False)
  2679. else:
  2680. cp = self.clear_polygon3(pol, tool,
  2681. self.grb_circle_steps,
  2682. overlap=overlap, contour=contour,
  2683. connect=connect,
  2684. prog_plot=False)
  2685. if cp:
  2686. cleared_geo += list(cp.get_objects())
  2687. poly_processed.append(True)
  2688. else:
  2689. poly_processed.append(False)
  2690. log.warning("Polygon in MultiPolygon can not be cleared.")
  2691. else:
  2692. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2693. "It is: %s" % str(type(pol)))
  2694. except TypeError:
  2695. if isinstance(p, Polygon):
  2696. if ncc_method == 'standard':
  2697. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  2698. overlap=overlap, contour=contour, connect=connect,
  2699. prog_plot=False)
  2700. elif ncc_method == 'seed':
  2701. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  2702. overlap=overlap, contour=contour, connect=connect,
  2703. prog_plot=False)
  2704. else:
  2705. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  2706. overlap=overlap, contour=contour, connect=connect,
  2707. prog_plot=False)
  2708. if cp:
  2709. cleared_geo += list(cp.get_objects())
  2710. poly_processed.append(True)
  2711. else:
  2712. poly_processed.append(False)
  2713. log.warning("Polygon can not be cleared.")
  2714. else:
  2715. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2716. p_cleared = poly_processed.count(True)
  2717. p_not_cleared = poly_processed.count(False)
  2718. if p_not_cleared:
  2719. app_obj.poly_not_cleared = True
  2720. if p_cleared == 0:
  2721. continue
  2722. pol_nr += 1
  2723. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2724. # log.debug("Polygons cleared: %d" % pol_nr)
  2725. if old_disp_number < disp_number <= 100:
  2726. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2727. old_disp_number = disp_number
  2728. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2729. # check if there is a geometry at all in the cleared geometry
  2730. if cleared_geo:
  2731. # Overall cleared area
  2732. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2733. tool / 1.999999)
  2734. # clean-up cleared geo
  2735. cleared = cleared.buffer(0)
  2736. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2737. # solid_geometry
  2738. for k, v in tools_storage.items():
  2739. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2740. tool)):
  2741. current_uid = int(k)
  2742. # add the solid_geometry to the current too in self.paint_tools dictionary
  2743. # and then reset the temporary list that stored that solid_geometry
  2744. v['solid_geometry'] = deepcopy(cleared_geo)
  2745. v['data']['name'] = name
  2746. break
  2747. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2748. else:
  2749. log.debug("There are no geometries in the cleared polygon.")
  2750. # delete tools with empty geometry
  2751. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2752. for uid, uid_val in list(tools_storage.items()):
  2753. try:
  2754. # if the solid_geometry (type=list) is empty
  2755. if not uid_val['solid_geometry']:
  2756. tools_storage.pop(uid, None)
  2757. except KeyError:
  2758. tools_storage.pop(uid, None)
  2759. geo_obj.options["cnctooldia"] = str(tool)
  2760. geo_obj.multigeo = True
  2761. geo_obj.tools.clear()
  2762. geo_obj.tools = dict(tools_storage)
  2763. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2764. has_solid_geo = 0
  2765. for tooluid in geo_obj.tools:
  2766. if geo_obj.tools[tooluid]['solid_geometry']:
  2767. has_solid_geo += 1
  2768. if has_solid_geo == 0:
  2769. app_obj.inform.emit('[ERROR] %s' %
  2770. _("There is no NCC Geometry in the file.\n"
  2771. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2772. "Change the painting parameters and try again."))
  2773. return 'fail'
  2774. # check to see if geo_obj.tools is empty
  2775. # it will be updated only if there is a solid_geometry for tools
  2776. if geo_obj.tools:
  2777. if warning_flag == 0:
  2778. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2779. else:
  2780. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2781. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2782. str(warning_flag),
  2783. _("tools")))
  2784. return
  2785. # create the solid_geometry
  2786. geo_obj.solid_geometry = list()
  2787. for tooluid in geo_obj.tools:
  2788. if geo_obj.tools[tooluid]['solid_geometry']:
  2789. try:
  2790. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2791. geo_obj.solid_geometry.append(geo)
  2792. except TypeError:
  2793. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2794. else:
  2795. # I will use this variable for this purpose although it was meant for something else
  2796. # signal that we have no geo in the object therefore don't create it
  2797. app_obj.poly_not_cleared = False
  2798. return "fail"
  2799. # ###########################################################################################
  2800. # Initializes the new geometry object for the case of the rest-machining ####################
  2801. # ###########################################################################################
  2802. def gen_clear_area_rest(geo_obj, app_obj):
  2803. assert geo_obj.kind == 'geometry', \
  2804. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2805. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2806. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2807. # provide the app with a way to process the GUI events when in a blocking loop
  2808. if not run_threaded:
  2809. QtWidgets.QApplication.processEvents()
  2810. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2811. # will store the number of tools for which the isolation is broken
  2812. warning_flag = 0
  2813. sorted_tools.sort(reverse=True)
  2814. cleared_geo = []
  2815. cleared_by_last_tool = []
  2816. rest_geo = []
  2817. current_uid = 1
  2818. try:
  2819. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2820. except TypeError:
  2821. tool = eval(self.app.defaults["tools_ncctools"])
  2822. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2823. app_obj.poly_not_cleared = True
  2824. log.debug("NCC Tool. Calculate 'empty' area.")
  2825. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2826. # ###################################################################################################
  2827. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2828. # ###################################################################################################
  2829. if ncc_obj.kind == 'gerber' and not isotooldia:
  2830. sol_geo = ncc_obj.solid_geometry
  2831. if has_offset is True:
  2832. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2833. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2834. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2835. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2836. if empty == 'fail':
  2837. return 'fail'
  2838. if empty.is_empty:
  2839. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2840. _("Could not get the extent of the area to be non copper cleared."))
  2841. return 'fail'
  2842. elif ncc_obj.kind == 'gerber' and isotooldia:
  2843. isolated_geo = []
  2844. self.solid_geometry = ncc_obj.solid_geometry
  2845. # if milling type is climb then the move is counter-clockwise around features
  2846. milling_type = self.app.defaults["tools_nccmilling_type"]
  2847. for tool_iso in isotooldia:
  2848. new_geometry = []
  2849. if milling_type == 'cl':
  2850. isolated_geo = self.generate_envelope(tool_iso, 1)
  2851. else:
  2852. isolated_geo = self.generate_envelope(tool_iso, 0)
  2853. if isolated_geo == 'fail':
  2854. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2855. else:
  2856. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2857. "than isolation tool diameter."))
  2858. try:
  2859. for geo_elem in isolated_geo:
  2860. # provide the app with a way to process the GUI events when in a blocking loop
  2861. QtWidgets.QApplication.processEvents()
  2862. if self.app.abort_flag:
  2863. # graceful abort requested by the user
  2864. raise FlatCAMApp.GracefulException
  2865. if isinstance(geo_elem, Polygon):
  2866. for ring in self.poly2rings(geo_elem):
  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, MultiPolygon):
  2871. for poly in geo_elem:
  2872. for ring in self.poly2rings(poly):
  2873. new_geo = ring.intersection(bounding_box)
  2874. if new_geo and not new_geo.is_empty:
  2875. new_geometry.append(new_geo)
  2876. elif isinstance(geo_elem, LineString):
  2877. new_geo = geo_elem.intersection(bounding_box)
  2878. if new_geo:
  2879. if not new_geo.is_empty:
  2880. new_geometry.append(new_geo)
  2881. elif isinstance(geo_elem, MultiLineString):
  2882. for line_elem in geo_elem:
  2883. new_geo = line_elem.intersection(bounding_box)
  2884. if new_geo and not new_geo.is_empty:
  2885. new_geometry.append(new_geo)
  2886. except TypeError:
  2887. try:
  2888. if isinstance(isolated_geo, Polygon):
  2889. for ring in self.poly2rings(isolated_geo):
  2890. new_geo = ring.intersection(bounding_box)
  2891. if new_geo:
  2892. if not new_geo.is_empty:
  2893. new_geometry.append(new_geo)
  2894. elif isinstance(isolated_geo, LineString):
  2895. new_geo = isolated_geo.intersection(bounding_box)
  2896. if new_geo and not new_geo.is_empty:
  2897. new_geometry.append(new_geo)
  2898. elif isinstance(isolated_geo, MultiLineString):
  2899. for line_elem in isolated_geo:
  2900. new_geo = line_elem.intersection(bounding_box)
  2901. if new_geo and not new_geo.is_empty:
  2902. new_geometry.append(new_geo)
  2903. except Exception as e:
  2904. pass
  2905. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2906. for geo_e in new_geometry:
  2907. if type(geo_e) == MultiLineString:
  2908. warning_flag += 1
  2909. break
  2910. for k, v in tools_storage.items():
  2911. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2912. tool_iso)):
  2913. current_uid = int(k)
  2914. # add the solid_geometry to the current too in self.paint_tools dictionary
  2915. # and then reset the temporary list that stored that solid_geometry
  2916. v['solid_geometry'] = deepcopy(new_geometry)
  2917. v['data']['name'] = name
  2918. break
  2919. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2920. sol_geo = cascaded_union(isolated_geo)
  2921. if has_offset is True:
  2922. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2923. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2924. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2925. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2926. if empty == 'fail':
  2927. return 'fail'
  2928. if empty.is_empty:
  2929. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2930. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2931. return 'fail'
  2932. elif ncc_obj.kind == 'geometry':
  2933. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2934. if has_offset is True:
  2935. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2936. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2937. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2938. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2939. if empty == 'fail':
  2940. return 'fail'
  2941. if empty.is_empty:
  2942. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2943. _("Could not get the extent of the area to be non copper cleared."))
  2944. return 'fail'
  2945. else:
  2946. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2947. return
  2948. if self.app.abort_flag:
  2949. # graceful abort requested by the user
  2950. raise FlatCAMApp.GracefulException
  2951. if type(empty) is Polygon:
  2952. empty = MultiPolygon([empty])
  2953. area = empty.buffer(0)
  2954. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2955. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2956. # Generate area for each tool
  2957. while sorted_tools:
  2958. if self.app.abort_flag:
  2959. # graceful abort requested by the user
  2960. raise FlatCAMApp.GracefulException
  2961. tool = sorted_tools.pop(0)
  2962. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2963. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2964. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2965. )
  2966. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2967. tool_used = tool - 1e-12
  2968. cleared_geo[:] = []
  2969. # Area to clear
  2970. for poly in cleared_by_last_tool:
  2971. # provide the app with a way to process the GUI events when in a blocking loop
  2972. QtWidgets.QApplication.processEvents()
  2973. if self.app.abort_flag:
  2974. # graceful abort requested by the user
  2975. raise FlatCAMApp.GracefulException
  2976. try:
  2977. area = area.difference(poly)
  2978. except Exception as e:
  2979. pass
  2980. cleared_by_last_tool[:] = []
  2981. # Transform area to MultiPolygon
  2982. if type(area) is Polygon:
  2983. area = MultiPolygon([area])
  2984. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2985. # and rest_geo it's a list
  2986. allparts = [p.buffer(0) for p in area.geoms]
  2987. allparts += deepcopy(rest_geo)
  2988. rest_geo[:] = []
  2989. area = MultiPolygon(deepcopy(allparts))
  2990. allparts[:] = []
  2991. # variables to display the percentage of work done
  2992. geo_len = len(area.geoms)
  2993. disp_number = 0
  2994. old_disp_number = 0
  2995. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2996. if area.geoms:
  2997. if len(area.geoms) > 0:
  2998. pol_nr = 0
  2999. for p in area.geoms:
  3000. if self.app.abort_flag:
  3001. # graceful abort requested by the user
  3002. raise FlatCAMApp.GracefulException
  3003. # clean the polygon
  3004. p = p.buffer(0)
  3005. if p is not None and p.is_valid:
  3006. # provide the app with a way to process the GUI events when in a blocking loop
  3007. QtWidgets.QApplication.processEvents()
  3008. if isinstance(p, Polygon):
  3009. try:
  3010. if ncc_method == 'standard':
  3011. cp = self.clear_polygon(p, tool_used,
  3012. self.grb_circle_steps,
  3013. overlap=overlap, contour=contour, connect=connect,
  3014. prog_plot=False)
  3015. elif ncc_method == 'seed':
  3016. cp = self.clear_polygon2(p, tool_used,
  3017. self.grb_circle_steps,
  3018. overlap=overlap, contour=contour, connect=connect,
  3019. prog_plot=False)
  3020. else:
  3021. cp = self.clear_polygon3(p, tool_used,
  3022. self.grb_circle_steps,
  3023. overlap=overlap, contour=contour, connect=connect,
  3024. prog_plot=False)
  3025. cleared_geo.append(list(cp.get_objects()))
  3026. except Exception as e:
  3027. log.warning("Polygon can't be cleared. %s" % str(e))
  3028. # this polygon should be added to a list and then try clear it with
  3029. # a smaller tool
  3030. rest_geo.append(p)
  3031. elif isinstance(p, MultiPolygon):
  3032. for poly in p:
  3033. if poly is not None:
  3034. # provide the app with a way to process the GUI events when
  3035. # in a blocking loop
  3036. QtWidgets.QApplication.processEvents()
  3037. try:
  3038. if ncc_method == 'standard':
  3039. cp = self.clear_polygon(poly, tool_used,
  3040. self.grb_circle_steps,
  3041. overlap=overlap, contour=contour,
  3042. connect=connect,
  3043. prog_plot=False)
  3044. elif ncc_method == 'seed':
  3045. cp = self.clear_polygon2(poly, tool_used,
  3046. self.grb_circle_steps,
  3047. overlap=overlap, contour=contour,
  3048. connect=connect,
  3049. prog_plot=False)
  3050. else:
  3051. cp = self.clear_polygon3(poly, tool_used,
  3052. self.grb_circle_steps,
  3053. overlap=overlap, contour=contour,
  3054. connect=connect,
  3055. prog_plot=False)
  3056. cleared_geo.append(list(cp.get_objects()))
  3057. except Exception as e:
  3058. log.warning("Polygon can't be cleared. %s" % str(e))
  3059. # this polygon should be added to a list and then try clear it with
  3060. # a smaller tool
  3061. rest_geo.append(poly)
  3062. pol_nr += 1
  3063. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3064. # log.debug("Polygons cleared: %d" % pol_nr)
  3065. if old_disp_number < disp_number <= 100:
  3066. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3067. old_disp_number = disp_number
  3068. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3069. if self.app.abort_flag:
  3070. # graceful abort requested by the user
  3071. raise FlatCAMApp.GracefulException
  3072. # check if there is a geometry at all in the cleared geometry
  3073. if cleared_geo:
  3074. # Overall cleared area
  3075. cleared_area = list(self.flatten_list(cleared_geo))
  3076. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  3077. # for p in cleared_area])
  3078. # here we store the poly's already processed in the original geometry by the current tool
  3079. # into cleared_by_last_tool list
  3080. # this will be sutracted from the original geometry_to_be_cleared and make data for
  3081. # the next tool
  3082. buffer_value = tool_used / 2
  3083. for p in cleared_area:
  3084. if self.app.abort_flag:
  3085. # graceful abort requested by the user
  3086. raise FlatCAMApp.GracefulException
  3087. poly = p.buffer(buffer_value)
  3088. cleared_by_last_tool.append(poly)
  3089. # find the tooluid associated with the current tool_dia so we know
  3090. # where to add the tool solid_geometry
  3091. for k, v in tools_storage.items():
  3092. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  3093. tool)):
  3094. current_uid = int(k)
  3095. # add the solid_geometry to the current too in self.paint_tools dictionary
  3096. # and then reset the temporary list that stored that solid_geometry
  3097. v['solid_geometry'] = deepcopy(cleared_area)
  3098. v['data']['name'] = name
  3099. cleared_area[:] = []
  3100. break
  3101. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  3102. else:
  3103. log.debug("There are no geometries in the cleared polygon.")
  3104. geo_obj.multigeo = True
  3105. geo_obj.options["cnctooldia"] = str(tool)
  3106. # check to see if geo_obj.tools is empty
  3107. # it will be updated only if there is a solid_geometry for tools
  3108. if geo_obj.tools:
  3109. if warning_flag == 0:
  3110. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  3111. else:
  3112. self.app.inform.emit(
  3113. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  3114. "isolation is broken for"), str(warning_flag), _("tools")))
  3115. return
  3116. # create the solid_geometry
  3117. geo_obj.solid_geometry = list()
  3118. for tooluid in geo_obj.tools:
  3119. if geo_obj.tools[tooluid]['solid_geometry']:
  3120. try:
  3121. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  3122. geo_obj.solid_geometry.append(geo)
  3123. except TypeError:
  3124. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  3125. else:
  3126. # I will use this variable for this purpose although it was meant for something else
  3127. # signal that we have no geo in the object therefore don't create it
  3128. app_obj.poly_not_cleared = False
  3129. return "fail"
  3130. # ###########################################################################################
  3131. # Create the Job function and send it to the worker to be processed in another thread #######
  3132. # ###########################################################################################
  3133. def job_thread(app_obj):
  3134. try:
  3135. if rest_machining_choice is True:
  3136. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  3137. else:
  3138. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  3139. except FlatCAMApp.GracefulException:
  3140. if run_threaded:
  3141. proc.done()
  3142. return
  3143. except Exception:
  3144. if run_threaded:
  3145. proc.done()
  3146. traceback.print_stack()
  3147. return
  3148. if run_threaded:
  3149. proc.done()
  3150. else:
  3151. app_obj.proc_container.view.set_idle()
  3152. # focus on Selected Tab
  3153. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3154. if run_threaded:
  3155. # Promise object with the new name
  3156. self.app.collection.promise(name)
  3157. # Background
  3158. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3159. else:
  3160. job_thread(app_obj=self.app)
  3161. def get_ncc_empty_area(self, target, boundary=None):
  3162. """
  3163. Returns the complement of target geometry within
  3164. the given boundary polygon. If not specified, it defaults to
  3165. the rectangular bounding box of target geometry.
  3166. """
  3167. if isinstance(target, Polygon):
  3168. geo_len = 1
  3169. else:
  3170. geo_len = len(target)
  3171. pol_nr = 0
  3172. old_disp_number = 0
  3173. if boundary is None:
  3174. boundary = target.envelope
  3175. else:
  3176. boundary = boundary
  3177. try:
  3178. ret_val = boundary.difference(target)
  3179. except Exception as e:
  3180. try:
  3181. for el in target:
  3182. # provide the app with a way to process the GUI events when in a blocking loop
  3183. QtWidgets.QApplication.processEvents()
  3184. if self.app.abort_flag:
  3185. # graceful abort requested by the user
  3186. raise FlatCAMApp.GracefulException
  3187. boundary = boundary.difference(el)
  3188. pol_nr += 1
  3189. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3190. if old_disp_number < disp_number <= 100:
  3191. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3192. old_disp_number = disp_number
  3193. return boundary
  3194. except Exception as e:
  3195. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3196. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  3197. "Reload the Gerber file after this change."))
  3198. return 'fail'
  3199. return ret_val
  3200. def reset_fields(self):
  3201. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3202. def reset_usage(self):
  3203. self.obj_name = ""
  3204. self.ncc_obj = None
  3205. self.bound_obj = None
  3206. self.first_click = False
  3207. self.cursor_pos = None
  3208. self.mouse_is_dragging = False
  3209. self.sel_rect = []
  3210. @staticmethod
  3211. def poly2rings(poly):
  3212. return [poly.exterior] + [interior for interior in poly.interiors]
  3213. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  3214. # isolation_geometry produces an envelope that is going on the left of the geometry
  3215. # (the copper features). To leave the least amount of burrs on the features
  3216. # the tool needs to travel on the right side of the features (this is called conventional milling)
  3217. # the first pass is the one cutting all of the features, so it needs to be reversed
  3218. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  3219. # to cut on the right side of the left over copper i.e on the left side of the features.
  3220. try:
  3221. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  3222. except Exception as e:
  3223. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  3224. return 'fail'
  3225. if invert:
  3226. try:
  3227. try:
  3228. pl = []
  3229. for p in geom:
  3230. if p is not None:
  3231. if isinstance(p, Polygon):
  3232. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3233. elif isinstance(p, LinearRing):
  3234. pl.append(Polygon(p.coords[::-1]))
  3235. geom = MultiPolygon(pl)
  3236. except TypeError:
  3237. if isinstance(geom, Polygon) and geom is not None:
  3238. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3239. elif isinstance(geom, LinearRing) and geom is not None:
  3240. geom = Polygon(geom.coords[::-1])
  3241. else:
  3242. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  3243. type(geom))
  3244. except Exception as e:
  3245. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  3246. return 'fail'
  3247. return geom