ToolNonCopperClear.py 179 KB

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