ToolNonCopperClear.py 182 KB

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