ToolCutOut.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from AppTool import AppTool
  9. from AppGUI.GUIElements import FCDoubleSpinner, FCCheckBox, RadioSet, FCComboBox, OptionalInputSection, FCButton
  10. from shapely.geometry import box, MultiPolygon, Polygon, LineString, LinearRing
  11. from shapely.ops import cascaded_union, unary_union
  12. import shapely.affinity as affinity
  13. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  14. from numpy import Inf
  15. from copy import deepcopy
  16. import math
  17. import logging
  18. import gettext
  19. import AppTranslation as fcTranslate
  20. import builtins
  21. fcTranslate.apply_language('strings')
  22. if '_' not in builtins.__dict__:
  23. _ = gettext.gettext
  24. log = logging.getLogger('base')
  25. settings = QtCore.QSettings("Open Source", "FlatCAM")
  26. if settings.contains("machinist"):
  27. machinist_setting = settings.value('machinist', type=int)
  28. else:
  29. machinist_setting = 0
  30. class CutOut(AppTool):
  31. toolName = _("Cutout PCB")
  32. def __init__(self, app):
  33. AppTool.__init__(self, app)
  34. self.app = app
  35. self.canvas = app.plotcanvas
  36. self.decimals = self.app.decimals
  37. # Title
  38. title_label = QtWidgets.QLabel("%s" % self.toolName)
  39. title_label.setStyleSheet("""
  40. QLabel
  41. {
  42. font-size: 16px;
  43. font-weight: bold;
  44. }
  45. """)
  46. self.layout.addWidget(title_label)
  47. self.layout.addWidget(QtWidgets.QLabel(''))
  48. # Form Layout
  49. grid0 = QtWidgets.QGridLayout()
  50. grid0.setColumnStretch(0, 0)
  51. grid0.setColumnStretch(1, 1)
  52. self.layout.addLayout(grid0)
  53. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  54. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  55. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  56. # Object kind
  57. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  58. self.kindlabel.setToolTip(
  59. _("Choice of what kind the object we want to cutout is.<BR>"
  60. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  61. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  62. "out of many individual PCB outlines.")
  63. )
  64. self.obj_kind_combo = RadioSet([
  65. {"label": _("Single"), "value": "single"},
  66. {"label": _("Panel"), "value": "panel"},
  67. ])
  68. grid0.addWidget(self.kindlabel, 1, 0)
  69. grid0.addWidget(self.obj_kind_combo, 1, 1)
  70. # Type of object to be cutout
  71. self.type_obj_radio = RadioSet([
  72. {"label": _("Gerber"), "value": "grb"},
  73. {"label": _("Geometry"), "value": "geo"},
  74. ])
  75. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  76. self.type_obj_combo_label.setToolTip(
  77. _("Specify the type of object to be cutout.\n"
  78. "It can be of type: Gerber or Geometry.\n"
  79. "What is selected here will dictate the kind\n"
  80. "of objects that will populate the 'Object' combobox.")
  81. )
  82. grid0.addWidget(self.type_obj_combo_label, 2, 0)
  83. grid0.addWidget(self.type_obj_radio, 2, 1)
  84. # Object to be cutout
  85. self.obj_combo = FCComboBox()
  86. self.obj_combo.setModel(self.app.collection)
  87. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  88. self.obj_combo.is_last = True
  89. grid0.addWidget(self.obj_combo, 3, 0, 1, 2)
  90. separator_line = QtWidgets.QFrame()
  91. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  92. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  93. grid0.addWidget(separator_line, 4, 0, 1, 2)
  94. grid0.addWidget(QtWidgets.QLabel(''), 5, 0, 1, 2)
  95. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  96. grid0.addWidget(self.param_label, 6, 0, 1, 2)
  97. # Tool Diameter
  98. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  99. self.dia.set_precision(self.decimals)
  100. self.dia.set_range(0.0000, 9999.9999)
  101. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Diameter"))
  102. self.dia_label.setToolTip(
  103. _("Diameter of the tool used to cutout\n"
  104. "the PCB shape out of the surrounding material.")
  105. )
  106. grid0.addWidget(self.dia_label, 8, 0)
  107. grid0.addWidget(self.dia, 8, 1)
  108. # Cut Z
  109. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  110. cutzlabel.setToolTip(
  111. _(
  112. "Cutting depth (negative)\n"
  113. "below the copper surface."
  114. )
  115. )
  116. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  117. self.cutz_entry.set_precision(self.decimals)
  118. if machinist_setting == 0:
  119. self.cutz_entry.setRange(-9999.9999, -0.00001)
  120. else:
  121. self.cutz_entry.setRange(-9999.9999, 9999.9999)
  122. self.cutz_entry.setSingleStep(0.1)
  123. grid0.addWidget(cutzlabel, 9, 0)
  124. grid0.addWidget(self.cutz_entry, 9, 1)
  125. # Multi-pass
  126. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  127. self.mpass_cb.setToolTip(
  128. _(
  129. "Use multiple passes to limit\n"
  130. "the cut depth in each pass. Will\n"
  131. "cut multiple times until Cut Z is\n"
  132. "reached."
  133. )
  134. )
  135. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  136. self.maxdepth_entry.set_precision(self.decimals)
  137. self.maxdepth_entry.setRange(0, 9999.9999)
  138. self.maxdepth_entry.setSingleStep(0.1)
  139. self.maxdepth_entry.setToolTip(
  140. _(
  141. "Depth of each pass (positive)."
  142. )
  143. )
  144. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  145. grid0.addWidget(self.mpass_cb, 10, 0)
  146. grid0.addWidget(self.maxdepth_entry, 10, 1)
  147. # Margin
  148. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  149. self.margin.set_range(-9999.9999, 9999.9999)
  150. self.margin.setSingleStep(0.1)
  151. self.margin.set_precision(self.decimals)
  152. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  153. self.margin_label.setToolTip(
  154. _("Margin over bounds. A positive value here\n"
  155. "will make the cutout of the PCB further from\n"
  156. "the actual PCB border")
  157. )
  158. grid0.addWidget(self.margin_label, 11, 0)
  159. grid0.addWidget(self.margin, 11, 1)
  160. # Gapsize
  161. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  162. self.gapsize.set_precision(self.decimals)
  163. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  164. self.gapsize_label.setToolTip(
  165. _("The size of the bridge gaps in the cutout\n"
  166. "used to keep the board connected to\n"
  167. "the surrounding material (the one \n"
  168. "from which the PCB is cutout).")
  169. )
  170. grid0.addWidget(self.gapsize_label, 13, 0)
  171. grid0.addWidget(self.gapsize, 13, 1)
  172. # How gaps wil be rendered:
  173. # lr - left + right
  174. # tb - top + bottom
  175. # 4 - left + right +top + bottom
  176. # 2lr - 2*left + 2*right
  177. # 2tb - 2*top + 2*bottom
  178. # 8 - 2*left + 2*right +2*top + 2*bottom
  179. # Surrounding convex box shape
  180. self.convex_box = FCCheckBox('%s' % _("Convex Shape"))
  181. # self.convex_box_label = QtWidgets.QLabel('%s' % _("Convex Sh."))
  182. self.convex_box.setToolTip(
  183. _("Create a convex shape surrounding the entire PCB.\n"
  184. "Used only if the source object type is Gerber.")
  185. )
  186. grid0.addWidget(self.convex_box, 15, 0, 1, 2)
  187. separator_line = QtWidgets.QFrame()
  188. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  189. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  190. grid0.addWidget(separator_line, 16, 0, 1, 2)
  191. grid0.addWidget(QtWidgets.QLabel(''), 17, 0, 1, 2)
  192. # Title2
  193. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  194. title_param_label.setToolTip(
  195. _("This section handle creation of automatic bridge gaps.")
  196. )
  197. grid0.addWidget(title_param_label, 18, 0, 1, 2)
  198. # Gaps
  199. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  200. gaps_label.setToolTip(
  201. _("Number of gaps used for the Automatic cutout.\n"
  202. "There can be maximum 8 bridges/gaps.\n"
  203. "The choices are:\n"
  204. "- None - no gaps\n"
  205. "- lr - left + right\n"
  206. "- tb - top + bottom\n"
  207. "- 4 - left + right +top + bottom\n"
  208. "- 2lr - 2*left + 2*right\n"
  209. "- 2tb - 2*top + 2*bottom\n"
  210. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  211. )
  212. # gaps_label.setMinimumWidth(60)
  213. self.gaps = FCComboBox()
  214. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  215. for it in gaps_items:
  216. self.gaps.addItem(it)
  217. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  218. grid0.addWidget(gaps_label, 19, 0)
  219. grid0.addWidget(self.gaps, 19, 1)
  220. # Buttons
  221. self.ff_cutout_object_btn = FCButton(_("Generate Freeform Geometry"))
  222. self.ff_cutout_object_btn.setToolTip(
  223. _("Cutout the selected object.\n"
  224. "The cutout shape can be of any shape.\n"
  225. "Useful when the PCB has a non-rectangular shape.")
  226. )
  227. self.ff_cutout_object_btn.setStyleSheet("""
  228. QPushButton
  229. {
  230. font-weight: bold;
  231. }
  232. """)
  233. grid0.addWidget(self.ff_cutout_object_btn, 20, 0, 1, 2)
  234. self.rect_cutout_object_btn = FCButton(_("Generate Rectangular Geometry"))
  235. self.rect_cutout_object_btn.setToolTip(
  236. _("Cutout the selected object.\n"
  237. "The resulting cutout shape is\n"
  238. "always a rectangle shape and it will be\n"
  239. "the bounding box of the Object.")
  240. )
  241. self.rect_cutout_object_btn.setStyleSheet("""
  242. QPushButton
  243. {
  244. font-weight: bold;
  245. }
  246. """)
  247. grid0.addWidget(self.rect_cutout_object_btn, 21, 0, 1, 2)
  248. separator_line = QtWidgets.QFrame()
  249. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  250. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  251. grid0.addWidget(separator_line, 22, 0, 1, 2)
  252. # Title5
  253. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  254. title_manual_label.setToolTip(
  255. _("This section handle creation of manual bridge gaps.\n"
  256. "This is done by mouse clicking on the perimeter of the\n"
  257. "Geometry object that is used as a cutout object. ")
  258. )
  259. grid0.addWidget(title_manual_label, 23, 0, 1, 2)
  260. # Manual Geo Object
  261. self.man_object_combo = FCComboBox()
  262. self.man_object_combo.setModel(self.app.collection)
  263. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  264. self.man_object_combo.is_last = True
  265. self.man_object_combo.obj_type = "Geometry"
  266. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geometry Object"))
  267. self.man_object_label.setToolTip(
  268. _("Geometry object used to create the manual cutout.")
  269. )
  270. # self.man_object_label.setMinimumWidth(60)
  271. grid0.addWidget(self.man_object_label, 25, 0, 1, 2)
  272. grid0.addWidget(self.man_object_combo, 26, 0, 1, 2)
  273. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  274. self.man_geo_creation_btn.setToolTip(
  275. _("If the object to be cutout is a Gerber\n"
  276. "first create a Geometry that surrounds it,\n"
  277. "to be used as the cutout, if one doesn't exist yet.\n"
  278. "Select the source Gerber file in the top object combobox.")
  279. )
  280. self.man_geo_creation_btn.setStyleSheet("""
  281. QPushButton
  282. {
  283. font-weight: bold;
  284. }
  285. """)
  286. grid0.addWidget(self.man_geo_creation_btn, 28, 0, 1, 2)
  287. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  288. self.man_gaps_creation_btn.setToolTip(
  289. _("Use the left mouse button (LMB) click\n"
  290. "to create a bridge gap to separate the PCB from\n"
  291. "the surrounding material.\n"
  292. "The LMB click has to be done on the perimeter of\n"
  293. "the Geometry object used as a cutout geometry.")
  294. )
  295. self.man_gaps_creation_btn.setStyleSheet("""
  296. QPushButton
  297. {
  298. font-weight: bold;
  299. }
  300. """)
  301. grid0.addWidget(self.man_gaps_creation_btn, 30, 0, 1, 2)
  302. self.layout.addStretch()
  303. # ## Reset Tool
  304. self.reset_button = FCButton(_("Reset Tool"))
  305. self.reset_button.setToolTip(
  306. _("Will reset the tool parameters.")
  307. )
  308. self.reset_button.setStyleSheet("""
  309. QPushButton
  310. {
  311. font-weight: bold;
  312. }
  313. """)
  314. self.layout.addWidget(self.reset_button)
  315. self.cutting_gapsize = 0.0
  316. self.cutting_dia = 0.0
  317. # true if we want to repeat the gap without clicking again on the button
  318. self.repeat_gap = False
  319. self.flat_geometry = []
  320. # this is the Geometry object generated in this class to be used for adding manual gaps
  321. self.man_cutout_obj = None
  322. # if mouse is dragging set the object True
  323. self.mouse_is_dragging = False
  324. # event handlers references
  325. self.kp = None
  326. self.mm = None
  327. self.mr = None
  328. # hold the mouse position here
  329. self.x_pos = None
  330. self.y_pos = None
  331. # store the default data for the resulting Geometry Object
  332. self.default_data = {}
  333. # Signals
  334. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  335. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  336. self.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  337. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  338. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  339. self.reset_button.clicked.connect(self.set_tool_ui)
  340. def on_type_obj_changed(self, val):
  341. obj_type = {'grb': 0, 'geo': 2}[val]
  342. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  343. self.obj_combo.setCurrentIndex(0)
  344. self.obj_combo.obj_type = {"grb": "Gerber", "geo": "Geometry"}[val]
  345. def run(self, toggle=True):
  346. self.app.defaults.report_usage("ToolCutOut()")
  347. if toggle:
  348. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  349. if self.app.ui.splitter.sizes()[0] == 0:
  350. self.app.ui.splitter.setSizes([1, 1])
  351. else:
  352. try:
  353. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  354. # if tab is populated with the tool but it does not have the focus, focus on it
  355. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  356. # focus on Tool Tab
  357. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  358. else:
  359. self.app.ui.splitter.setSizes([0, 1])
  360. except AttributeError:
  361. pass
  362. else:
  363. if self.app.ui.splitter.sizes()[0] == 0:
  364. self.app.ui.splitter.setSizes([1, 1])
  365. AppTool.run(self)
  366. self.set_tool_ui()
  367. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  368. def install(self, icon=None, separator=None, **kwargs):
  369. AppTool.install(self, icon, separator, shortcut='Alt+X', **kwargs)
  370. def set_tool_ui(self):
  371. self.reset_fields()
  372. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  373. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  374. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  375. self.cutz_entry.set_value(float(self.app.defaults["tools_cutout_z"]))
  376. self.mpass_cb.set_value(float(self.app.defaults["tools_cutout_mdepth"]))
  377. self.maxdepth_entry.set_value(float(self.app.defaults["tools_cutout_depthperpass"]))
  378. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  379. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  380. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  381. self.type_obj_radio.set_value('grb')
  382. self.default_data.update({
  383. "plot": True,
  384. "cutz": float(self.app.defaults["geometry_cutz"]),
  385. "multidepth": self.app.defaults["geometry_multidepth"],
  386. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  387. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  388. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  389. "travelz": float(self.app.defaults["geometry_travelz"]),
  390. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  391. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  392. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  393. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  394. "dwell": self.app.defaults["geometry_dwell"],
  395. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  396. "ppname_g": self.app.defaults["geometry_ppname_g"],
  397. "extracut": self.app.defaults["geometry_extracut"],
  398. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  399. "toolchange": self.app.defaults["geometry_toolchange"],
  400. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  401. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  402. "startz": self.app.defaults["geometry_startz"],
  403. "endz": float(self.app.defaults["geometry_endz"]),
  404. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  405. "area_shape": self.app.defaults["geometry_area_shape"],
  406. "area_strategy": self.app.defaults["geometry_area_strategy"],
  407. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  408. # NCC
  409. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  410. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  411. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  412. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  413. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  414. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  415. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  416. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  417. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  418. # Paint
  419. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  420. "tools_paintmargin": float(self.app.defaults["tools_paintmargin"]),
  421. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  422. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  423. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  424. # Isolation Tool
  425. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  426. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  427. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  428. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  429. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  430. })
  431. def on_freeform_cutout(self):
  432. log.debug("Cutout.on_freeform_cutout() was launched ...")
  433. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  434. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  435. # obj_.subtract_polygon(pts)
  436. name = self.obj_combo.currentText()
  437. # Get source object.
  438. try:
  439. cutout_obj = self.app.collection.get_by_name(str(name))
  440. except Exception as e:
  441. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  442. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  443. return "Could not retrieve object: %s" % name
  444. if cutout_obj is None:
  445. self.app.inform.emit('[ERROR_NOTCL] %s' %
  446. _("There is no object selected for Cutout.\nSelect one and try again."))
  447. return
  448. dia = float(self.dia.get_value())
  449. if 0 in {dia}:
  450. self.app.inform.emit('[WARNING_NOTCL] %s' %
  451. _("Tool Diameter is zero value. Change it to a positive real number."))
  452. return "Tool Diameter is zero value. Change it to a positive real number."
  453. try:
  454. kind = self.obj_kind_combo.get_value()
  455. except ValueError:
  456. return
  457. margin = float(self.margin.get_value())
  458. gapsize = float(self.gapsize.get_value())
  459. try:
  460. gaps = self.gaps.get_value()
  461. except TypeError:
  462. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  463. return
  464. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  465. self.app.inform.emit('[WARNING_NOTCL] %s' %
  466. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  467. "Fill in a correct value and retry. "))
  468. return
  469. if cutout_obj.multigeo is True:
  470. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  471. "Optionally, this Multi-geo Geometry can be converted to "
  472. "Single-geo Geometry,\n"
  473. "and after that perform Cutout."))
  474. return
  475. convex_box = self.convex_box.get_value()
  476. gapsize = gapsize / 2 + (dia / 2)
  477. def geo_init(geo_obj, app_obj):
  478. solid_geo = []
  479. if cutout_obj.kind == 'gerber':
  480. if isinstance(cutout_obj.solid_geometry, list):
  481. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  482. try:
  483. if convex_box:
  484. object_geo = cutout_obj.solid_geometry.convex_hull
  485. else:
  486. object_geo = cutout_obj.solid_geometry
  487. except Exception as err:
  488. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  489. object_geo = cutout_obj.solid_geometry
  490. else:
  491. object_geo = cutout_obj.solid_geometry
  492. def cutout_handler(geom):
  493. # Get min and max data for each object as we just cut rectangles across X or Y
  494. xxmin, yymin, xxmax, yymax = recursive_bounds(geom)
  495. px = 0.5 * (xxmin + xxmax) + margin
  496. py = 0.5 * (yymin + yymax) + margin
  497. lenx = (xxmax - xxmin) + (margin * 2)
  498. leny = (yymax - yymin) + (margin * 2)
  499. proc_geometry = []
  500. if gaps == 'None':
  501. pass
  502. else:
  503. if gaps == '8' or gaps == '2LR':
  504. geom = self.subtract_poly_from_geo(geom,
  505. xxmin - gapsize, # botleft_x
  506. py - gapsize + leny / 4, # botleft_y
  507. xxmax + gapsize, # topright_x
  508. py + gapsize + leny / 4) # topright_y
  509. geom = self.subtract_poly_from_geo(geom,
  510. xxmin - gapsize,
  511. py - gapsize - leny / 4,
  512. xxmax + gapsize,
  513. py + gapsize - leny / 4)
  514. if gaps == '8' or gaps == '2TB':
  515. geom = self.subtract_poly_from_geo(geom,
  516. px - gapsize + lenx / 4,
  517. yymin - gapsize,
  518. px + gapsize + lenx / 4,
  519. yymax + gapsize)
  520. geom = self.subtract_poly_from_geo(geom,
  521. px - gapsize - lenx / 4,
  522. yymin - gapsize,
  523. px + gapsize - lenx / 4,
  524. yymax + gapsize)
  525. if gaps == '4' or gaps == 'LR':
  526. geom = self.subtract_poly_from_geo(geom,
  527. xxmin - gapsize,
  528. py - gapsize,
  529. xxmax + gapsize,
  530. py + gapsize)
  531. if gaps == '4' or gaps == 'TB':
  532. geom = self.subtract_poly_from_geo(geom,
  533. px - gapsize,
  534. yymin - gapsize,
  535. px + gapsize,
  536. yymax + gapsize)
  537. try:
  538. for g in geom:
  539. proc_geometry.append(g)
  540. except TypeError:
  541. proc_geometry.append(geom)
  542. return proc_geometry
  543. if kind == 'single':
  544. object_geo = unary_union(object_geo)
  545. # for geo in object_geo:
  546. if cutout_obj.kind == 'gerber':
  547. if isinstance(object_geo, MultiPolygon):
  548. x0, y0, x1, y1 = object_geo.bounds
  549. object_geo = box(x0, y0, x1, y1)
  550. if margin >= 0:
  551. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  552. else:
  553. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  554. geo = geo_buf.exterior
  555. else:
  556. geo = object_geo
  557. solid_geo = cutout_handler(geom=geo)
  558. else:
  559. try:
  560. __ = iter(object_geo)
  561. except TypeError:
  562. object_geo = [object_geo]
  563. for geom_struct in object_geo:
  564. if cutout_obj.kind == 'gerber':
  565. if margin >= 0:
  566. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  567. else:
  568. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  569. geom_struct = geom_struct_buff.interiors
  570. solid_geo += cutout_handler(geom=geom_struct)
  571. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  572. geo_obj.solid_geometry = deepcopy(solid_geo)
  573. geo_obj.options['xmin'] = xmin
  574. geo_obj.options['ymin'] = ymin
  575. geo_obj.options['xmax'] = xmax
  576. geo_obj.options['ymax'] = ymax
  577. geo_obj.options['cnctooldia'] = str(dia)
  578. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  579. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  580. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  581. geo_obj.tools.update({
  582. 1: {
  583. 'tooldia': str(dia),
  584. 'offset': 'Path',
  585. 'offset_value': 0.0,
  586. 'type': _('Rough'),
  587. 'tool_type': 'C1',
  588. 'data': self.default_data,
  589. 'solid_geometry': geo_obj.solid_geometry
  590. }
  591. })
  592. geo_obj.multigeo = True
  593. geo_obj.tools[1]['data']['name'] = outname
  594. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  595. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  596. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  597. outname = cutout_obj.options["name"] + "_cutout"
  598. self.app.app_obj.new_object('geometry', outname, geo_init)
  599. cutout_obj.plot()
  600. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  601. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  602. self.app.should_we_save = True
  603. def on_rectangular_cutout(self):
  604. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  605. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  606. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  607. # obj_.subtract_polygon(pts)
  608. name = self.obj_combo.currentText()
  609. # Get source object.
  610. try:
  611. cutout_obj = self.app.collection.get_by_name(str(name))
  612. except Exception as e:
  613. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  614. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  615. return "Could not retrieve object: %s" % name
  616. if cutout_obj is None:
  617. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  618. dia = float(self.dia.get_value())
  619. if 0 in {dia}:
  620. self.app.inform.emit('[ERROR_NOTCL] %s' %
  621. _("Tool Diameter is zero value. Change it to a positive real number."))
  622. return "Tool Diameter is zero value. Change it to a positive real number."
  623. try:
  624. kind = self.obj_kind_combo.get_value()
  625. except ValueError:
  626. return
  627. margin = float(self.margin.get_value())
  628. gapsize = float(self.gapsize.get_value())
  629. try:
  630. gaps = self.gaps.get_value()
  631. except TypeError:
  632. self.app.inform.emit('[WARNING_NOTCL] %s' %
  633. _("Number of gaps value is missing. Add it and retry."))
  634. return
  635. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  636. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  637. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  638. "Fill in a correct value and retry. "))
  639. return
  640. if cutout_obj.multigeo is True:
  641. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  642. "Optionally, this Multi-geo Geometry can be converted to "
  643. "Single-geo Geometry,\n"
  644. "and after that perform Cutout."))
  645. return
  646. # Get min and max data for each object as we just cut rectangles across X or Y
  647. gapsize = gapsize / 2 + (dia / 2)
  648. def geo_init(geo_obj, app_obj):
  649. solid_geo = []
  650. object_geo = cutout_obj.solid_geometry
  651. def cutout_rect_handler(geom):
  652. proc_geometry = []
  653. px = 0.5 * (xmin + xmax) + margin
  654. py = 0.5 * (ymin + ymax) + margin
  655. lenx = (xmax - xmin) + (margin * 2)
  656. leny = (ymax - ymin) + (margin * 2)
  657. if gaps == 'None':
  658. pass
  659. else:
  660. if gaps == '8' or gaps == '2LR':
  661. geom = self.subtract_poly_from_geo(geom,
  662. xmin - gapsize, # botleft_x
  663. py - gapsize + leny / 4, # botleft_y
  664. xmax + gapsize, # topright_x
  665. py + gapsize + leny / 4) # topright_y
  666. geom = self.subtract_poly_from_geo(geom,
  667. xmin - gapsize,
  668. py - gapsize - leny / 4,
  669. xmax + gapsize,
  670. py + gapsize - leny / 4)
  671. if gaps == '8' or gaps == '2TB':
  672. geom = self.subtract_poly_from_geo(geom,
  673. px - gapsize + lenx / 4,
  674. ymin - gapsize,
  675. px + gapsize + lenx / 4,
  676. ymax + gapsize)
  677. geom = self.subtract_poly_from_geo(geom,
  678. px - gapsize - lenx / 4,
  679. ymin - gapsize,
  680. px + gapsize - lenx / 4,
  681. ymax + gapsize)
  682. if gaps == '4' or gaps == 'LR':
  683. geom = self.subtract_poly_from_geo(geom,
  684. xmin - gapsize,
  685. py - gapsize,
  686. xmax + gapsize,
  687. py + gapsize)
  688. if gaps == '4' or gaps == 'TB':
  689. geom = self.subtract_poly_from_geo(geom,
  690. px - gapsize,
  691. ymin - gapsize,
  692. px + gapsize,
  693. ymax + gapsize)
  694. try:
  695. for g in geom:
  696. proc_geometry.append(g)
  697. except TypeError:
  698. proc_geometry.append(geom)
  699. return proc_geometry
  700. if kind == 'single':
  701. # fuse the lines
  702. object_geo = unary_union(object_geo)
  703. xmin, ymin, xmax, ymax = object_geo.bounds
  704. geo = box(xmin, ymin, xmax, ymax)
  705. # if Gerber create a buffer at a distance
  706. # if Geometry then cut through the geometry
  707. if cutout_obj.kind == 'gerber':
  708. if margin >= 0:
  709. geo = geo.buffer(margin + abs(dia / 2))
  710. else:
  711. geo = geo.buffer(margin - abs(dia / 2))
  712. solid_geo = cutout_rect_handler(geom=geo)
  713. else:
  714. if cutout_obj.kind == 'geometry':
  715. try:
  716. __ = iter(object_geo)
  717. except TypeError:
  718. object_geo = [object_geo]
  719. for geom_struct in object_geo:
  720. geom_struct = unary_union(geom_struct)
  721. xmin, ymin, xmax, ymax = geom_struct.bounds
  722. geom_struct = box(xmin, ymin, xmax, ymax)
  723. solid_geo += cutout_rect_handler(geom=geom_struct)
  724. elif cutout_obj.kind == 'gerber' and margin >= 0:
  725. try:
  726. __ = iter(object_geo)
  727. except TypeError:
  728. object_geo = [object_geo]
  729. for geom_struct in object_geo:
  730. geom_struct = unary_union(geom_struct)
  731. xmin, ymin, xmax, ymax = geom_struct.bounds
  732. geom_struct = box(xmin, ymin, xmax, ymax)
  733. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  734. solid_geo += cutout_rect_handler(geom=geom_struct)
  735. elif cutout_obj.kind == 'gerber' and margin < 0:
  736. self.app.inform.emit('[WARNING_NOTCL] %s' %
  737. _("Rectangular cutout with negative margin is not possible."))
  738. return "fail"
  739. geo_obj.options['cnctooldia'] = str(dia)
  740. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  741. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  742. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  743. geo_obj.solid_geometry = deepcopy(solid_geo)
  744. geo_obj.tools.update({
  745. 1: {
  746. 'tooldia': str(dia),
  747. 'offset': 'Path',
  748. 'offset_value': 0.0,
  749. 'type': _('Rough'),
  750. 'tool_type': 'C1',
  751. 'data': self.default_data,
  752. 'solid_geometry': geo_obj.solid_geometry
  753. }
  754. })
  755. geo_obj.multigeo = True
  756. geo_obj.tools[1]['data']['name'] = outname
  757. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  758. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  759. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  760. outname = cutout_obj.options["name"] + "_cutout"
  761. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  762. if ret != 'fail':
  763. # cutout_obj.plot()
  764. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  765. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  766. self.app.should_we_save = True
  767. def on_manual_gap_click(self):
  768. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  769. self.app.geo_editor.tool_shape.enabled = True
  770. self.cutting_dia = float(self.dia.get_value())
  771. if 0 in {self.cutting_dia}:
  772. self.app.inform.emit('[ERROR_NOTCL] %s' %
  773. _("Tool Diameter is zero value. Change it to a positive real number."))
  774. return
  775. self.cutting_gapsize = float(self.gapsize.get_value())
  776. name = self.man_object_combo.currentText()
  777. # Get Geometry source object to be used as target for Manual adding Gaps
  778. try:
  779. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  780. except Exception as e:
  781. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  782. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  783. return
  784. if self.app.is_legacy is False:
  785. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  786. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  787. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  788. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  789. else:
  790. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  791. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  792. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  793. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  794. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  795. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  796. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  797. def on_manual_cutout(self, click_pos):
  798. name = self.man_object_combo.currentText()
  799. # Get source object.
  800. try:
  801. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  802. except Exception as e:
  803. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  804. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  805. return "Could not retrieve object: %s" % name
  806. if self.man_cutout_obj is None:
  807. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  808. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  809. return
  810. # use the snapped position as reference
  811. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  812. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  813. self.man_cutout_obj.subtract_polygon(cut_poly)
  814. self.man_cutout_obj.plot()
  815. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  816. self.app.should_we_save = True
  817. def on_manual_geo(self):
  818. name = self.obj_combo.currentText()
  819. # Get source object.
  820. try:
  821. cutout_obj = self.app.collection.get_by_name(str(name))
  822. except Exception as e:
  823. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  824. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  825. return "Could not retrieve object: %s" % name
  826. if cutout_obj is None:
  827. self.app.inform.emit('[ERROR_NOTCL] %s' %
  828. _("There is no Gerber object selected for Cutout.\n"
  829. "Select one and try again."))
  830. return
  831. if cutout_obj.kind != 'gerber':
  832. self.app.inform.emit('[ERROR_NOTCL] %s' %
  833. _("The selected object has to be of Gerber type.\n"
  834. "Select a Gerber file and try again."))
  835. return
  836. dia = float(self.dia.get_value())
  837. if 0 in {dia}:
  838. self.app.inform.emit('[ERROR_NOTCL] %s' %
  839. _("Tool Diameter is zero value. Change it to a positive real number."))
  840. return "Tool Diameter is zero value. Change it to a positive real number."
  841. try:
  842. kind = self.obj_kind_combo.get_value()
  843. except ValueError:
  844. return
  845. margin = float(self.margin.get_value())
  846. convex_box = self.convex_box.get_value()
  847. def geo_init(geo_obj, app_obj):
  848. geo_union = unary_union(cutout_obj.solid_geometry)
  849. if convex_box:
  850. geo = geo_union.convex_hull
  851. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  852. elif kind == 'single':
  853. if isinstance(geo_union, Polygon) or \
  854. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  855. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  856. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  857. elif isinstance(geo_union, MultiPolygon):
  858. x0, y0, x1, y1 = geo_union.bounds
  859. geo = box(x0, y0, x1, y1)
  860. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  861. else:
  862. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  863. (_("Geometry not supported for cutout"), type(geo_union)))
  864. return 'fail'
  865. else:
  866. geo = geo_union
  867. geo = geo.buffer(margin + abs(dia / 2))
  868. if isinstance(geo, Polygon):
  869. geo_obj.solid_geometry = geo.exterior
  870. elif isinstance(geo, MultiPolygon):
  871. solid_geo = []
  872. for poly in geo:
  873. solid_geo.append(poly.exterior)
  874. geo_obj.solid_geometry = deepcopy(solid_geo)
  875. geo_obj.options['cnctooldia'] = str(dia)
  876. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  877. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  878. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  879. geo_obj.tools.update({
  880. 1: {
  881. 'tooldia': str(dia),
  882. 'offset': 'Path',
  883. 'offset_value': 0.0,
  884. 'type': _('Rough'),
  885. 'tool_type': 'C1',
  886. 'data': self.default_data,
  887. 'solid_geometry': geo_obj.solid_geometry
  888. }
  889. })
  890. geo_obj.multigeo = True
  891. geo_obj.tools[1]['data']['name'] = outname
  892. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  893. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  894. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  895. outname = cutout_obj.options["name"] + "_cutout"
  896. self.app.app_obj.new_object('geometry', outname, geo_init)
  897. def cutting_geo(self, pos):
  898. self.cutting_dia = float(self.dia.get_value())
  899. self.cutting_gapsize = float(self.gapsize.get_value())
  900. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  901. # cutting area definition
  902. orig_x = pos[0]
  903. orig_y = pos[1]
  904. xmin = orig_x - offset
  905. ymin = orig_y - offset
  906. xmax = orig_x + offset
  907. ymax = orig_y + offset
  908. cut_poly = box(xmin, ymin, xmax, ymax)
  909. return cut_poly
  910. # To be called after clicking on the plot.
  911. def on_mouse_click_release(self, event):
  912. if self.app.is_legacy is False:
  913. event_pos = event.pos
  914. # event_is_dragging = event.is_dragging
  915. right_button = 2
  916. else:
  917. event_pos = (event.xdata, event.ydata)
  918. # event_is_dragging = self.app.plotcanvas.is_dragging
  919. right_button = 3
  920. try:
  921. x = float(event_pos[0])
  922. y = float(event_pos[1])
  923. except TypeError:
  924. return
  925. event_pos = (x, y)
  926. # do paint single only for left mouse clicks
  927. if event.button == 1:
  928. self.app.inform.emit(_("Making manual bridge gap..."))
  929. pos = self.app.plotcanvas.translate_coords(event_pos)
  930. self.on_manual_cutout(click_pos=pos)
  931. # if RMB then we exit
  932. elif event.button == right_button and self.mouse_is_dragging is False:
  933. if self.app.is_legacy is False:
  934. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  935. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  936. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  937. else:
  938. self.app.plotcanvas.graph_event_disconnect(self.kp)
  939. self.app.plotcanvas.graph_event_disconnect(self.mm)
  940. self.app.plotcanvas.graph_event_disconnect(self.mr)
  941. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  942. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  943. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  944. self.app.on_mouse_click_release_over_plot)
  945. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  946. # Remove any previous utility shape
  947. self.app.geo_editor.tool_shape.clear(update=True)
  948. self.app.geo_editor.tool_shape.enabled = False
  949. def on_mouse_move(self, event):
  950. self.app.on_mouse_move_over_plot(event=event)
  951. if self.app.is_legacy is False:
  952. event_pos = event.pos
  953. event_is_dragging = event.is_dragging
  954. # right_button = 2
  955. else:
  956. event_pos = (event.xdata, event.ydata)
  957. event_is_dragging = self.app.plotcanvas.is_dragging
  958. # right_button = 3
  959. try:
  960. x = float(event_pos[0])
  961. y = float(event_pos[1])
  962. except TypeError:
  963. return
  964. event_pos = (x, y)
  965. pos = self.canvas.translate_coords(event_pos)
  966. event.xdata, event.ydata = pos[0], pos[1]
  967. if event_is_dragging is True:
  968. self.mouse_is_dragging = True
  969. else:
  970. self.mouse_is_dragging = False
  971. try:
  972. x = float(event.xdata)
  973. y = float(event.ydata)
  974. except TypeError:
  975. return
  976. if self.app.grid_status():
  977. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  978. else:
  979. snap_x, snap_y = x, y
  980. self.x_pos, self.y_pos = snap_x, snap_y
  981. # #################################################
  982. # ### This section makes the cutting geo to #######
  983. # ### rotate if it intersects the target geo ######
  984. # #################################################
  985. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  986. man_geo = self.man_cutout_obj.solid_geometry
  987. def get_angle(geo):
  988. line = cut_geo.intersection(geo)
  989. try:
  990. pt1_x = line.coords[0][0]
  991. pt1_y = line.coords[0][1]
  992. pt2_x = line.coords[1][0]
  993. pt2_y = line.coords[1][1]
  994. dx = pt1_x - pt2_x
  995. dy = pt1_y - pt2_y
  996. if dx == 0 or dy == 0:
  997. angle = 0
  998. else:
  999. radian = math.atan(dx / dy)
  1000. angle = radian * 180 / math.pi
  1001. except Exception:
  1002. angle = 0
  1003. return angle
  1004. try:
  1005. rot_angle = 0
  1006. for geo_el in man_geo:
  1007. if isinstance(geo_el, Polygon):
  1008. work_geo = geo_el.exterior
  1009. if cut_geo.intersects(work_geo):
  1010. rot_angle = get_angle(geo=work_geo)
  1011. else:
  1012. rot_angle = 0
  1013. else:
  1014. rot_angle = 0
  1015. if cut_geo.intersects(geo_el):
  1016. rot_angle = get_angle(geo=geo_el)
  1017. if rot_angle != 0:
  1018. break
  1019. except TypeError:
  1020. if isinstance(man_geo, Polygon):
  1021. work_geo = man_geo.exterior
  1022. if cut_geo.intersects(work_geo):
  1023. rot_angle = get_angle(geo=work_geo)
  1024. else:
  1025. rot_angle = 0
  1026. else:
  1027. rot_angle = 0
  1028. if cut_geo.intersects(man_geo):
  1029. rot_angle = get_angle(geo=man_geo)
  1030. # rotate only if there is an angle to rotate to
  1031. if rot_angle != 0:
  1032. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  1033. # Remove any previous utility shape
  1034. self.app.geo_editor.tool_shape.clear(update=True)
  1035. self.draw_utility_geometry(geo=cut_geo)
  1036. def draw_utility_geometry(self, geo):
  1037. self.app.geo_editor.tool_shape.add(
  1038. shape=geo,
  1039. color=(self.app.defaults["global_draw_color"] + '80'),
  1040. update=False,
  1041. layer=0,
  1042. tolerance=None)
  1043. self.app.geo_editor.tool_shape.redraw()
  1044. def on_key_press(self, event):
  1045. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1046. if type(event) is int:
  1047. key = event
  1048. # events from the GUI are of type QKeyEvent
  1049. elif type(event) == QtGui.QKeyEvent:
  1050. key = event.key()
  1051. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1052. key = event.key
  1053. key = QtGui.QKeySequence(key)
  1054. # check for modifiers
  1055. key_string = key.toString().lower()
  1056. if '+' in key_string:
  1057. mod, __, key_text = key_string.rpartition('+')
  1058. if mod.lower() == 'ctrl':
  1059. # modifiers = QtCore.Qt.ControlModifier
  1060. pass
  1061. elif mod.lower() == 'alt':
  1062. # modifiers = QtCore.Qt.AltModifier
  1063. pass
  1064. elif mod.lower() == 'shift':
  1065. # modifiers = QtCore.Qt.ShiftModifier
  1066. pass
  1067. else:
  1068. # modifiers = QtCore.Qt.NoModifier
  1069. pass
  1070. key = QtGui.QKeySequence(key_text)
  1071. # events from Vispy are of type KeyEvent
  1072. else:
  1073. key = event.key
  1074. # Escape = Deselect All
  1075. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1076. if self.app.is_legacy is False:
  1077. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1078. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1079. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1080. else:
  1081. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1082. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1083. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1084. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1085. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1086. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1087. self.app.on_mouse_click_release_over_plot)
  1088. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1089. # Remove any previous utility shape
  1090. self.app.geo_editor.tool_shape.clear(update=True)
  1091. self.app.geo_editor.tool_shape.enabled = False
  1092. # Grid toggle
  1093. if key == QtCore.Qt.Key_G or key == 'G':
  1094. self.app.ui.grid_snap_btn.trigger()
  1095. # Jump to coords
  1096. if key == QtCore.Qt.Key_J or key == 'J':
  1097. l_x, l_y = self.app.on_jump_to()
  1098. self.app.geo_editor.tool_shape.clear(update=True)
  1099. geo = self.cutting_geo(pos=(l_x, l_y))
  1100. self.draw_utility_geometry(geo=geo)
  1101. @staticmethod
  1102. def subtract_poly_from_geo(solid_geo, x0, y0, x1, y1):
  1103. """
  1104. Subtract polygon made from points from the given object.
  1105. This only operates on the paths in the original geometry,
  1106. i.e. it converts polygons into paths.
  1107. :param x0: x coord for lower left vertex of the polygon.
  1108. :param y0: y coord for lower left vertex of the polygon.
  1109. :param x1: x coord for upper right vertex of the polygon.
  1110. :param y1: y coord for upper right vertex of the polygon.
  1111. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  1112. :return: none
  1113. """
  1114. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1115. # pathonly should be allways True, otherwise polygons are not subtracted
  1116. flat_geometry = flatten(geometry=solid_geo)
  1117. log.debug("%d paths" % len(flat_geometry))
  1118. polygon = Polygon(points)
  1119. toolgeo = cascaded_union(polygon)
  1120. diffs = []
  1121. for target in flat_geometry:
  1122. if type(target) == LineString or type(target) == LinearRing:
  1123. diffs.append(target.difference(toolgeo))
  1124. else:
  1125. log.warning("Not implemented.")
  1126. return unary_union(diffs)
  1127. def reset_fields(self):
  1128. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1129. def flatten(geometry):
  1130. """
  1131. Creates a list of non-iterable linear geometry objects.
  1132. Polygons are expanded into its exterior and interiors.
  1133. Results are placed in self.flat_geometry
  1134. :param geometry: Shapely type or list or list of list of such.
  1135. """
  1136. flat_geo = []
  1137. try:
  1138. for geo in geometry:
  1139. if type(geo) == Polygon:
  1140. flat_geo.append(geo.exterior)
  1141. for subgeo in geo.interiors:
  1142. flat_geo.append(subgeo)
  1143. else:
  1144. flat_geo.append(geo)
  1145. except TypeError:
  1146. if type(geometry) == Polygon:
  1147. flat_geo.append(geometry.exterior)
  1148. for subgeo in geometry.interiors:
  1149. flat_geo.append(subgeo)
  1150. else:
  1151. flat_geo.append(geometry)
  1152. return flat_geo
  1153. def recursive_bounds(geometry):
  1154. """
  1155. Return the bounds of the biggest bounding box in geometry, one that include all.
  1156. :param geometry: a iterable object that holds geometry
  1157. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1158. """
  1159. # now it can get bounds for nested lists of objects
  1160. def bounds_rec(obj):
  1161. try:
  1162. minx = Inf
  1163. miny = Inf
  1164. maxx = -Inf
  1165. maxy = -Inf
  1166. for k in obj:
  1167. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1168. minx = min(minx, minx_)
  1169. miny = min(miny, miny_)
  1170. maxx = max(maxx, maxx_)
  1171. maxy = max(maxy, maxy_)
  1172. return minx, miny, maxx, maxy
  1173. except TypeError:
  1174. # it's a Shapely object, return it's bounds
  1175. return obj.bounds
  1176. return bounds_rec(geometry)