ToolNonCopperClear.py 131 KB

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