ToolNonCopperClear.py 133 KB

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