ToolNonCopperClear.py 134 KB

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