ToolNonCopperClear.py 131 KB

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