ToolNonCopperClear.py 117 KB

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