ToolNonCopperClear.py 129 KB

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