ToolNonCopperClear.py 148 KB

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