ToolNonCopperClear.py 128 KB

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