ToolNonCopperClear.py 103 KB

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