ToolNonCopperClear.py 130 KB

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