ToolNonCopperClear.py 151 KB

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