ToolNonCopperClear.py 151 KB

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