ToolCutOut.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. from FlatCAMTool import FlatCAMTool
  2. from ObjectCollection import *
  3. from FlatCAMApp import *
  4. from shapely.geometry import box
  5. from shapely.ops import cascaded_union, unary_union
  6. import gettext
  7. import FlatCAMTranslation as fcTranslate
  8. import builtins
  9. fcTranslate.apply_language('strings')
  10. if '_' not in builtins.__dict__:
  11. _ = gettext.gettext
  12. class CutOut(FlatCAMTool):
  13. toolName = _("Cutout PCB")
  14. def __init__(self, app):
  15. FlatCAMTool.__init__(self, app)
  16. self.app = app
  17. self.canvas = app.plotcanvas
  18. # Title
  19. title_label = QtWidgets.QLabel("%s" % self.toolName)
  20. title_label.setStyleSheet("""
  21. QLabel
  22. {
  23. font-size: 16px;
  24. font-weight: bold;
  25. }
  26. """)
  27. self.layout.addWidget(title_label)
  28. # Form Layout
  29. form_layout = QtWidgets.QFormLayout()
  30. self.layout.addLayout(form_layout)
  31. # Type of object to be cutout
  32. self.type_obj_combo = QtWidgets.QComboBox()
  33. self.type_obj_combo.addItem("Gerber")
  34. self.type_obj_combo.addItem("Excellon")
  35. self.type_obj_combo.addItem("Geometry")
  36. # we get rid of item1 ("Excellon") as it is not suitable for creating film
  37. self.type_obj_combo.view().setRowHidden(1, True)
  38. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  39. # self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  40. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  41. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  42. self.type_obj_combo_label.setToolTip(
  43. _("Specify the type of object to be cutout.\n"
  44. "It can be of type: Gerber or Geometry.\n"
  45. "What is selected here will dictate the kind\n"
  46. "of objects that will populate the 'Object' combobox.")
  47. )
  48. self.type_obj_combo_label.setMinimumWidth(60)
  49. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  50. # Object to be cutout
  51. self.obj_combo = QtWidgets.QComboBox()
  52. self.obj_combo.setModel(self.app.collection)
  53. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  54. self.obj_combo.setCurrentIndex(1)
  55. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  56. self.object_label.setToolTip(
  57. _("Object to be cutout. ")
  58. )
  59. form_layout.addRow(self.object_label, self.obj_combo)
  60. # Object kind
  61. self.kindlabel = QtWidgets.QLabel('%s:' % _('Obj kind'))
  62. self.kindlabel.setToolTip(
  63. _("Choice of what kind the object we want to cutout is.<BR>"
  64. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  65. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  66. "out of many individual PCB outlines.")
  67. )
  68. self.obj_kind_combo = RadioSet([
  69. {"label": _("Single"), "value": "single"},
  70. {"label": _("Panel"), "value": "panel"},
  71. ])
  72. form_layout.addRow(self.kindlabel, self.obj_kind_combo)
  73. # Tool Diameter
  74. self.dia = FCEntry()
  75. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool dia"))
  76. self.dia_label.setToolTip(
  77. _("Diameter of the tool used to cutout\n"
  78. "the PCB shape out of the surrounding material.")
  79. )
  80. form_layout.addRow(self.dia_label, self.dia)
  81. # Margin
  82. self.margin = FCEntry()
  83. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin:"))
  84. self.margin_label.setToolTip(
  85. _("Margin over bounds. A positive value here\n"
  86. "will make the cutout of the PCB further from\n"
  87. "the actual PCB border")
  88. )
  89. form_layout.addRow(self.margin_label, self.margin)
  90. # Gapsize
  91. self.gapsize = FCEntry()
  92. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size:"))
  93. self.gapsize_label.setToolTip(
  94. _("The size of the bridge gaps in the cutout\n"
  95. "used to keep the board connected to\n"
  96. "the surrounding material (the one \n"
  97. "from which the PCB is cutout).")
  98. )
  99. form_layout.addRow(self.gapsize_label, self.gapsize)
  100. # How gaps wil be rendered:
  101. # lr - left + right
  102. # tb - top + bottom
  103. # 4 - left + right +top + bottom
  104. # 2lr - 2*left + 2*right
  105. # 2tb - 2*top + 2*bottom
  106. # 8 - 2*left + 2*right +2*top + 2*bottom
  107. # Surrounding convex box shape
  108. self.convex_box = FCCheckBox()
  109. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Sh."))
  110. self.convex_box_label.setToolTip(
  111. _("Create a convex shape surrounding the entire PCB.\n"
  112. "Used only if the source object type is Gerber.")
  113. )
  114. form_layout.addRow(self.convex_box_label, self.convex_box)
  115. # Title2
  116. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  117. title_param_label.setToolTip(
  118. _("This section handle creation of automatic bridge gaps.")
  119. )
  120. self.layout.addWidget(title_param_label)
  121. # Form Layout
  122. form_layout_2 = QtWidgets.QFormLayout()
  123. self.layout.addLayout(form_layout_2)
  124. # Gaps
  125. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  126. gaps_label.setToolTip(
  127. _("Number of gaps used for the Automatic cutout.\n"
  128. "There can be maximum 8 bridges/gaps.\n"
  129. "The choices are:\n"
  130. "- None - no gaps\n"
  131. "- lr - left + right\n"
  132. "- tb - top + bottom\n"
  133. "- 4 - left + right +top + bottom\n"
  134. "- 2lr - 2*left + 2*right\n"
  135. "- 2tb - 2*top + 2*bottom\n"
  136. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  137. )
  138. gaps_label.setMinimumWidth(60)
  139. self.gaps = FCComboBox()
  140. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  141. for it in gaps_items:
  142. self.gaps.addItem(it)
  143. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  144. form_layout_2.addRow(gaps_label, self.gaps)
  145. # Buttons
  146. hlay = QtWidgets.QHBoxLayout()
  147. self.layout.addLayout(hlay)
  148. title_ff_label = QtWidgets.QLabel("<b>%s:</b>" % _('FreeForm'))
  149. title_ff_label.setToolTip(
  150. _("The cutout shape can be of ny shape.\n"
  151. "Useful when the PCB has a non-rectangular shape.")
  152. )
  153. hlay.addWidget(title_ff_label)
  154. hlay.addStretch()
  155. self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  156. self.ff_cutout_object_btn.setToolTip(
  157. _("Cutout the selected object.\n"
  158. "The cutout shape can be of any shape.\n"
  159. "Useful when the PCB has a non-rectangular shape.")
  160. )
  161. hlay.addWidget(self.ff_cutout_object_btn)
  162. hlay2 = QtWidgets.QHBoxLayout()
  163. self.layout.addLayout(hlay2)
  164. title_rct_label = QtWidgets.QLabel("<b>%s:</b>" % _('Rectangular'))
  165. title_rct_label.setToolTip(
  166. _("The resulting cutout shape is\n"
  167. "always a rectangle shape and it will be\n"
  168. "the bounding box of the Object.")
  169. )
  170. hlay2.addWidget(title_rct_label)
  171. hlay2.addStretch()
  172. self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  173. self.rect_cutout_object_btn.setToolTip(
  174. _("Cutout the selected object.\n"
  175. "The resulting cutout shape is\n"
  176. "always a rectangle shape and it will be\n"
  177. "the bounding box of the Object.")
  178. )
  179. hlay2.addWidget(self.rect_cutout_object_btn)
  180. # Title5
  181. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  182. title_manual_label.setToolTip(
  183. _("This section handle creation of manual bridge gaps.\n"
  184. "This is done by mouse clicking on the perimeter of the\n"
  185. "Geometry object that is used as a cutout object. ")
  186. )
  187. self.layout.addWidget(title_manual_label)
  188. # Form Layout
  189. form_layout_3 = QtWidgets.QFormLayout()
  190. self.layout.addLayout(form_layout_3)
  191. # Manual Geo Object
  192. self.man_object_combo = QtWidgets.QComboBox()
  193. self.man_object_combo.setModel(self.app.collection)
  194. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  195. self.man_object_combo.setCurrentIndex(1)
  196. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geo Obj"))
  197. self.man_object_label.setToolTip(
  198. _("Geometry object used to create the manual cutout.")
  199. )
  200. self.man_object_label.setMinimumWidth(60)
  201. # e_lab_0 = QtWidgets.QLabel('')
  202. form_layout_3.addRow(self.man_object_label, self.man_object_combo)
  203. # form_layout_3.addRow(e_lab_0)
  204. hlay3 = QtWidgets.QHBoxLayout()
  205. self.layout.addLayout(hlay3)
  206. self.man_geo_label = QtWidgets.QLabel('%s:' % _("Manual Geo"))
  207. self.man_geo_label.setToolTip(
  208. _("If the object to be cutout is a Gerber\n"
  209. "first create a Geometry that surrounds it,\n"
  210. "to be used as the cutout, if one doesn't exist yet.\n"
  211. "Select the source Gerber file in the top object combobox.")
  212. )
  213. hlay3.addWidget(self.man_geo_label)
  214. hlay3.addStretch()
  215. self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Geo"))
  216. self.man_geo_creation_btn.setToolTip(
  217. _("If the object to be cutout is a Gerber\n"
  218. "first create a Geometry that surrounds it,\n"
  219. "to be used as the cutout, if one doesn't exist yet.\n"
  220. "Select the source Gerber file in the top object combobox.")
  221. )
  222. hlay3.addWidget(self.man_geo_creation_btn)
  223. hlay4 = QtWidgets.QHBoxLayout()
  224. self.layout.addLayout(hlay4)
  225. self.man_bridge_gaps_label = QtWidgets.QLabel('%s:' % _("Manual Add Bridge Gaps"))
  226. self.man_bridge_gaps_label.setToolTip(
  227. _("Use the left mouse button (LMB) click\n"
  228. "to create a bridge gap to separate the PCB from\n"
  229. "the surrounding material.")
  230. )
  231. hlay4.addWidget(self.man_bridge_gaps_label)
  232. hlay4.addStretch()
  233. self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Generate Gap"))
  234. self.man_gaps_creation_btn.setToolTip(
  235. _("Use the left mouse button (LMB) click\n"
  236. "to create a bridge gap to separate the PCB from\n"
  237. "the surrounding material.\n"
  238. "The LMB click has to be done on the perimeter of\n"
  239. "the Geometry object used as a cutout geometry.")
  240. )
  241. hlay4.addWidget(self.man_gaps_creation_btn)
  242. self.layout.addStretch()
  243. self.cutting_gapsize = 0.0
  244. self.cutting_dia = 0.0
  245. # true if we want to repeat the gap without clicking again on the button
  246. self.repeat_gap = False
  247. self.flat_geometry = []
  248. # this is the Geometry object generated in this class to be used for adding manual gaps
  249. self.man_cutout_obj = None
  250. # if mouse is dragging set the object True
  251. self.mouse_is_dragging = False
  252. # hold the mouse position here
  253. self.x_pos = None
  254. self.y_pos = None
  255. # Signals
  256. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  257. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  258. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  259. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  260. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  261. def on_type_obj_index_changed(self, index):
  262. obj_type = self.type_obj_combo.currentIndex()
  263. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  264. self.obj_combo.setCurrentIndex(0)
  265. def run(self, toggle=True):
  266. self.app.report_usage("ToolCutOut()")
  267. if toggle:
  268. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  269. if self.app.ui.splitter.sizes()[0] == 0:
  270. self.app.ui.splitter.setSizes([1, 1])
  271. else:
  272. try:
  273. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  274. # if tab is populated with the tool but it does not have the focus, focus on it
  275. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  276. # focus on Tool Tab
  277. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  278. else:
  279. self.app.ui.splitter.setSizes([0, 1])
  280. except AttributeError:
  281. pass
  282. else:
  283. if self.app.ui.splitter.sizes()[0] == 0:
  284. self.app.ui.splitter.setSizes([1, 1])
  285. FlatCAMTool.run(self)
  286. self.set_tool_ui()
  287. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  288. def install(self, icon=None, separator=None, **kwargs):
  289. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  290. def set_tool_ui(self):
  291. self.reset_fields()
  292. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  293. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  294. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  295. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  296. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  297. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  298. def on_freeform_cutout(self):
  299. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  300. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  301. # obj_.subtract_polygon(pts)
  302. name = self.obj_combo.currentText()
  303. # Get source object.
  304. try:
  305. cutout_obj = self.app.collection.get_by_name(str(name))
  306. except Exception as e:
  307. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  308. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  309. return "Could not retrieve object: %s" % name
  310. if cutout_obj is None:
  311. self.app.inform.emit('[ERROR_NOTCL] %s' %
  312. _("There is no object selected for Cutout.\nSelect one and try again."))
  313. return
  314. try:
  315. dia = float(self.dia.get_value())
  316. except ValueError:
  317. # try to convert comma to decimal point. if it's still not working error message and return
  318. try:
  319. dia = float(self.dia.get_value().replace(',', '.'))
  320. except ValueError:
  321. self.app.inform.emit('[WARNING_NOTCL] %s' %
  322. _("Tool diameter value is missing or wrong format. Add it and retry."))
  323. return
  324. if 0 in {dia}:
  325. self.app.inform.emit('[WARNING_NOTCL] %s' %
  326. _("Tool Diameter is zero value. Change it to a positive real number."))
  327. return "Tool Diameter is zero value. Change it to a positive real number."
  328. try:
  329. kind = self.obj_kind_combo.get_value()
  330. except ValueError:
  331. return
  332. try:
  333. margin = float(self.margin.get_value())
  334. except ValueError:
  335. # try to convert comma to decimal point. if it's still not working error message and return
  336. try:
  337. margin = float(self.margin.get_value().replace(',', '.'))
  338. except ValueError:
  339. self.app.inform.emit('[WARNING_NOTCL] %s' %
  340. _("Margin value is missing or wrong format. Add it and retry."))
  341. return
  342. try:
  343. gapsize = float(self.gapsize.get_value())
  344. except ValueError:
  345. # try to convert comma to decimal point. if it's still not working error message and return
  346. try:
  347. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  348. except ValueError:
  349. self.app.inform.emit('[WARNING_NOTCL] %s' %
  350. _("Gap size value is missing or wrong format. Add it and retry."))
  351. return
  352. try:
  353. gaps = self.gaps.get_value()
  354. except TypeError:
  355. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  356. return
  357. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  358. self.app.inform.emit('[WARNING_NOTCL] %s' %
  359. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  360. "Fill in a correct value and retry. "))
  361. return
  362. if cutout_obj.multigeo is True:
  363. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  364. "Optionally, this Multi-geo Geometry can be converted to "
  365. "Single-geo Geometry,\n"
  366. "and after that perform Cutout."))
  367. return
  368. convex_box = self.convex_box.get_value()
  369. gapsize = gapsize / 2 + (dia / 2)
  370. def geo_init(geo_obj, app_obj):
  371. solid_geo = []
  372. if isinstance(cutout_obj, FlatCAMGerber):
  373. if convex_box:
  374. object_geo = cutout_obj.solid_geometry.convex_hull
  375. else:
  376. object_geo = cutout_obj.solid_geometry
  377. else:
  378. object_geo = cutout_obj.solid_geometry
  379. def cutout_handler(geom):
  380. # Get min and max data for each object as we just cut rectangles across X or Y
  381. xmin, ymin, xmax, ymax = recursive_bounds(geom)
  382. px = 0.5 * (xmin + xmax) + margin
  383. py = 0.5 * (ymin + ymax) + margin
  384. lenx = (xmax - xmin) + (margin * 2)
  385. leny = (ymax - ymin) + (margin * 2)
  386. proc_geometry = []
  387. if gaps == 'None':
  388. pass
  389. else:
  390. if gaps == '8' or gaps == '2LR':
  391. geom = self.subtract_poly_from_geo(geom,
  392. xmin - gapsize, # botleft_x
  393. py - gapsize + leny / 4, # botleft_y
  394. xmax + gapsize, # topright_x
  395. py + gapsize + leny / 4) # topright_y
  396. geom = self.subtract_poly_from_geo(geom,
  397. xmin - gapsize,
  398. py - gapsize - leny / 4,
  399. xmax + gapsize,
  400. py + gapsize - leny / 4)
  401. if gaps == '8' or gaps == '2TB':
  402. geom = self.subtract_poly_from_geo(geom,
  403. px - gapsize + lenx / 4,
  404. ymin - gapsize,
  405. px + gapsize + lenx / 4,
  406. ymax + gapsize)
  407. geom = self.subtract_poly_from_geo(geom,
  408. px - gapsize - lenx / 4,
  409. ymin - gapsize,
  410. px + gapsize - lenx / 4,
  411. ymax + gapsize)
  412. if gaps == '4' or gaps == 'LR':
  413. geom = self.subtract_poly_from_geo(geom,
  414. xmin - gapsize,
  415. py - gapsize,
  416. xmax + gapsize,
  417. py + gapsize)
  418. if gaps == '4' or gaps == 'TB':
  419. geom = self.subtract_poly_from_geo(geom,
  420. px - gapsize,
  421. ymin - gapsize,
  422. px + gapsize,
  423. ymax + gapsize)
  424. try:
  425. for g in geom:
  426. proc_geometry.append(g)
  427. except TypeError:
  428. proc_geometry.append(geom)
  429. return proc_geometry
  430. if kind == 'single':
  431. object_geo = unary_union(object_geo)
  432. # for geo in object_geo:
  433. if isinstance(cutout_obj, FlatCAMGerber):
  434. if isinstance(object_geo, MultiPolygon):
  435. x0, y0, x1, y1 = object_geo.bounds
  436. object_geo = box(x0, y0, x1, y1)
  437. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  438. geo = geo_buf.exterior
  439. else:
  440. geo = object_geo
  441. solid_geo = cutout_handler(geom=geo)
  442. else:
  443. try:
  444. __ = iter(object_geo)
  445. except TypeError:
  446. object_geo = [object_geo]
  447. for geom_struct in object_geo:
  448. if isinstance(cutout_obj, FlatCAMGerber):
  449. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  450. solid_geo += cutout_handler(geom=geom_struct)
  451. geo_obj.solid_geometry = deepcopy(solid_geo)
  452. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  453. geo_obj.options['xmin'] = xmin
  454. geo_obj.options['ymin'] = ymin
  455. geo_obj.options['xmax'] = xmax
  456. geo_obj.options['ymax'] = ymax
  457. geo_obj.options['cnctooldia'] = str(dia)
  458. outname = cutout_obj.options["name"] + "_cutout"
  459. self.app.new_object('geometry', outname, geo_init)
  460. cutout_obj.plot()
  461. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  462. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  463. self.app.should_we_save = True
  464. def on_rectangular_cutout(self):
  465. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  466. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  467. # obj_.subtract_polygon(pts)
  468. name = self.obj_combo.currentText()
  469. # Get source object.
  470. try:
  471. cutout_obj = self.app.collection.get_by_name(str(name))
  472. except Exception as e:
  473. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  474. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  475. return "Could not retrieve object: %s" % name
  476. if cutout_obj is None:
  477. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found: %s"), cutout_obj))
  478. try:
  479. dia = float(self.dia.get_value())
  480. except ValueError:
  481. # try to convert comma to decimal point. if it's still not working error message and return
  482. try:
  483. dia = float(self.dia.get_value().replace(',', '.'))
  484. except ValueError:
  485. self.app.inform.emit('[WARNING_NOTCL] %s' %
  486. _("Tool diameter value is missing or wrong format. Add it and retry."))
  487. return
  488. if 0 in {dia}:
  489. self.app.inform.emit('[ERROR_NOTCL] %s' %
  490. _("Tool Diameter is zero value. Change it to a positive real number."))
  491. return "Tool Diameter is zero value. Change it to a positive real number."
  492. try:
  493. kind = self.obj_kind_combo.get_value()
  494. except ValueError:
  495. return
  496. try:
  497. margin = float(self.margin.get_value())
  498. except ValueError:
  499. # try to convert comma to decimal point. if it's still not working error message and return
  500. try:
  501. margin = float(self.margin.get_value().replace(',', '.'))
  502. except ValueError:
  503. self.app.inform.emit('[WARNING_NOTCL] %s' %
  504. _("Margin value is missing or wrong format. Add it and retry."))
  505. return
  506. try:
  507. gapsize = float(self.gapsize.get_value())
  508. except ValueError:
  509. # try to convert comma to decimal point. if it's still not working error message and return
  510. try:
  511. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  512. except ValueError:
  513. self.app.inform.emit('[WARNING_NOTCL] %s' %
  514. _("Gap size value is missing or wrong format. Add it and retry."))
  515. return
  516. try:
  517. gaps = self.gaps.get_value()
  518. except TypeError:
  519. self.app.inform.emit('[WARNING_NOTCL] %s' %
  520. _("Number of gaps value is missing. Add it and retry."))
  521. return
  522. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  523. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  524. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  525. "Fill in a correct value and retry. "))
  526. return
  527. if cutout_obj.multigeo is True:
  528. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  529. "Optionally, this Multi-geo Geometry can be converted to "
  530. "Single-geo Geometry,\n"
  531. "and after that perform Cutout."))
  532. return
  533. # Get min and max data for each object as we just cut rectangles across X or Y
  534. gapsize = gapsize / 2 + (dia / 2)
  535. def geo_init(geo_obj, app_obj):
  536. solid_geo = []
  537. object_geo = cutout_obj.solid_geometry
  538. def cutout_rect_handler(geom):
  539. proc_geometry = []
  540. px = 0.5 * (xmin + xmax) + margin
  541. py = 0.5 * (ymin + ymax) + margin
  542. lenx = (xmax - xmin) + (margin * 2)
  543. leny = (ymax - ymin) + (margin * 2)
  544. if gaps == 'None':
  545. pass
  546. else:
  547. if gaps == '8' or gaps == '2LR':
  548. geom = self.subtract_poly_from_geo(geom,
  549. xmin - gapsize, # botleft_x
  550. py - gapsize + leny / 4, # botleft_y
  551. xmax + gapsize, # topright_x
  552. py + gapsize + leny / 4) # topright_y
  553. geom = self.subtract_poly_from_geo(geom,
  554. xmin - gapsize,
  555. py - gapsize - leny / 4,
  556. xmax + gapsize,
  557. py + gapsize - leny / 4)
  558. if gaps == '8' or gaps == '2TB':
  559. geom = self.subtract_poly_from_geo(geom,
  560. px - gapsize + lenx / 4,
  561. ymin - gapsize,
  562. px + gapsize + lenx / 4,
  563. ymax + gapsize)
  564. geom = self.subtract_poly_from_geo(geom,
  565. px - gapsize - lenx / 4,
  566. ymin - gapsize,
  567. px + gapsize - lenx / 4,
  568. ymax + gapsize)
  569. if gaps == '4' or gaps == 'LR':
  570. geom = self.subtract_poly_from_geo(geom,
  571. xmin - gapsize,
  572. py - gapsize,
  573. xmax + gapsize,
  574. py + gapsize)
  575. if gaps == '4' or gaps == 'TB':
  576. geom = self.subtract_poly_from_geo(geom,
  577. px - gapsize,
  578. ymin - gapsize,
  579. px + gapsize,
  580. ymax + gapsize)
  581. try:
  582. for g in geom:
  583. proc_geometry.append(g)
  584. except TypeError:
  585. proc_geometry.append(geom)
  586. return proc_geometry
  587. if kind == 'single':
  588. object_geo = unary_union(object_geo)
  589. xmin, ymin, xmax, ymax = object_geo.bounds
  590. geo = box(xmin, ymin, xmax, ymax)
  591. # if Gerber create a buffer at a distance
  592. # if Geometry then cut through the geometry
  593. if isinstance(cutout_obj, FlatCAMGerber):
  594. geo = geo.buffer(margin + abs(dia / 2))
  595. solid_geo = cutout_rect_handler(geom=geo)
  596. else:
  597. try:
  598. __ = iter(object_geo)
  599. except TypeError:
  600. object_geo = [object_geo]
  601. for geom_struct in object_geo:
  602. geom_struct = unary_union(geom_struct)
  603. xmin, ymin, xmax, ymax = geom_struct.bounds
  604. geom_struct = box(xmin, ymin, xmax, ymax)
  605. if isinstance(cutout_obj, FlatCAMGerber):
  606. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  607. solid_geo += cutout_rect_handler(geom=geom_struct)
  608. geo_obj.solid_geometry = deepcopy(solid_geo)
  609. geo_obj.options['cnctooldia'] = str(dia)
  610. outname = cutout_obj.options["name"] + "_cutout"
  611. self.app.new_object('geometry', outname, geo_init)
  612. # cutout_obj.plot()
  613. self.app.inform.emit('[success] %s' %
  614. _("Any form CutOut operation finished."))
  615. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  616. self.app.should_we_save = True
  617. def on_manual_gap_click(self):
  618. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  619. self.app.geo_editor.tool_shape.enabled = True
  620. try:
  621. self.cutting_dia = float(self.dia.get_value())
  622. except ValueError:
  623. # try to convert comma to decimal point. if it's still not working error message and return
  624. try:
  625. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  626. except ValueError:
  627. self.app.inform.emit('[WARNING_NOTCL] %s' %
  628. _("Tool diameter value is missing or wrong format. Add it and retry."))
  629. return
  630. if 0 in {self.cutting_dia}:
  631. self.app.inform.emit('[ERROR_NOTCL] %s' %
  632. _("Tool Diameter is zero value. Change it to a positive real number."))
  633. return "Tool Diameter is zero value. Change it to a positive real number."
  634. try:
  635. self.cutting_gapsize = float(self.gapsize.get_value())
  636. except ValueError:
  637. # try to convert comma to decimal point. if it's still not working error message and return
  638. try:
  639. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  640. except ValueError:
  641. self.app.inform.emit('[WARNING_NOTCL] %s' %
  642. _("Gap size value is missing or wrong format. Add it and retry."))
  643. return
  644. name = self.man_object_combo.currentText()
  645. # Get Geometry source object to be used as target for Manual adding Gaps
  646. try:
  647. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  648. except Exception as e:
  649. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  650. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  651. return "Could not retrieve object: %s" % name
  652. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  653. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  654. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  655. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  656. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  657. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  658. self.app.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release)
  659. def on_manual_cutout(self, click_pos):
  660. name = self.man_object_combo.currentText()
  661. # Get source object.
  662. try:
  663. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  664. except Exception as e:
  665. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  666. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  667. return "Could not retrieve object: %s" % name
  668. if self.man_cutout_obj is None:
  669. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  670. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  671. return
  672. # use the snapped position as reference
  673. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  674. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  675. self.man_cutout_obj.subtract_polygon(cut_poly)
  676. self.man_cutout_obj.plot()
  677. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  678. self.app.should_we_save = True
  679. def on_manual_geo(self):
  680. name = self.obj_combo.currentText()
  681. # Get source object.
  682. try:
  683. cutout_obj = self.app.collection.get_by_name(str(name))
  684. except Exception as e:
  685. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  686. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  687. return "Could not retrieve object: %s" % name
  688. if cutout_obj is None:
  689. self.app.inform.emit('[ERROR_NOTCL] %s' %
  690. _("There is no Gerber object selected for Cutout.\n"
  691. "Select one and try again."))
  692. return
  693. if not isinstance(cutout_obj, FlatCAMGerber):
  694. self.app.inform.emit('[ERROR_NOTCL] %s' %
  695. _("The selected object has to be of Gerber type.\n"
  696. "Select a Gerber file and try again."))
  697. return
  698. try:
  699. dia = float(self.dia.get_value())
  700. except ValueError:
  701. # try to convert comma to decimal point. if it's still not working error message and return
  702. try:
  703. dia = float(self.dia.get_value().replace(',', '.'))
  704. except ValueError:
  705. self.app.inform.emit('[WARNING_NOTCL] %s' %
  706. _("Tool diameter value is missing or wrong format. Add it and retry."))
  707. return
  708. if 0 in {dia}:
  709. self.app.inform.emit('[ERROR_NOTCL] %s' %
  710. _("Tool Diameter is zero value. Change it to a positive real number."))
  711. return "Tool Diameter is zero value. Change it to a positive real number."
  712. try:
  713. kind = self.obj_kind_combo.get_value()
  714. except ValueError:
  715. return
  716. try:
  717. margin = float(self.margin.get_value())
  718. except ValueError:
  719. # try to convert comma to decimal point. if it's still not working error message and return
  720. try:
  721. margin = float(self.margin.get_value().replace(',', '.'))
  722. except ValueError:
  723. self.app.inform.emit('[WARNING_NOTCL] %s' %
  724. _("Margin value is missing or wrong format. Add it and retry."))
  725. return
  726. convex_box = self.convex_box.get_value()
  727. def geo_init(geo_obj, app_obj):
  728. geo_union = unary_union(cutout_obj.solid_geometry)
  729. if convex_box:
  730. geo = geo_union.convex_hull
  731. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  732. elif kind == 'single':
  733. if isinstance(geo_union, Polygon) or \
  734. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  735. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  736. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  737. elif isinstance(geo_union, MultiPolygon):
  738. x0, y0, x1, y1 = geo_union.bounds
  739. geo = box(x0, y0, x1, y1)
  740. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  741. else:
  742. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  743. (_("Geometry not supported for cutout"), type(geo_union)))
  744. return 'fail'
  745. else:
  746. geo = geo_union
  747. geo = geo.buffer(margin + abs(dia / 2))
  748. if isinstance(geo, Polygon):
  749. geo_obj.solid_geometry = geo.exterior
  750. elif isinstance(geo, MultiPolygon):
  751. solid_geo = []
  752. for poly in geo:
  753. solid_geo.append(poly.exterior)
  754. geo_obj.solid_geometry = deepcopy(solid_geo)
  755. geo_obj.options['cnctooldia'] = str(dia)
  756. outname = cutout_obj.options["name"] + "_cutout"
  757. self.app.new_object('geometry', outname, geo_init)
  758. def cutting_geo(self, pos):
  759. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  760. # cutting area definition
  761. orig_x = pos[0]
  762. orig_y = pos[1]
  763. xmin = orig_x - offset
  764. ymin = orig_y - offset
  765. xmax = orig_x + offset
  766. ymax = orig_y + offset
  767. cut_poly = box(xmin, ymin, xmax, ymax)
  768. return cut_poly
  769. # To be called after clicking on the plot.
  770. def on_mouse_click_release(self, event):
  771. # do paint single only for left mouse clicks
  772. if event.button == 1:
  773. self.app.inform.emit(_("Making manual bridge gap..."))
  774. pos = self.app.plotcanvas.translate_coords(event.pos)
  775. self.on_manual_cutout(click_pos=pos)
  776. # self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  777. # self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  778. # self.app.plotcanvas.vis_disconnect('mouse_release', self.on_mouse_click_release)
  779. # self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  780. # self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  781. # self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  782. # self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  783. # self.app.geo_editor.tool_shape.clear(update=True)
  784. # self.app.geo_editor.tool_shape.enabled = False
  785. # self.gapFinished.emit()
  786. # if RMB then we exit
  787. elif event.button == 2 and self.mouse_is_dragging is False:
  788. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  789. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  790. self.app.plotcanvas.vis_disconnect('mouse_release', self.on_mouse_click_release)
  791. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  792. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  793. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  794. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  795. # Remove any previous utility shape
  796. self.app.geo_editor.tool_shape.clear(update=True)
  797. self.app.geo_editor.tool_shape.enabled = False
  798. def on_mouse_move(self, event):
  799. self.app.on_mouse_move_over_plot(event=event)
  800. pos = self.canvas.translate_coords(event.pos)
  801. event.xdata, event.ydata = pos[0], pos[1]
  802. if event.is_dragging is True:
  803. self.mouse_is_dragging = True
  804. else:
  805. self.mouse_is_dragging = False
  806. try:
  807. x = float(event.xdata)
  808. y = float(event.ydata)
  809. except TypeError:
  810. return
  811. if self.app.grid_status() == True:
  812. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  813. else:
  814. snap_x, snap_y = x, y
  815. self.x_pos, self.y_pos = snap_x, snap_y
  816. # #################################################
  817. # ### This section makes the cutting geo to #######
  818. # ### rotate if it intersects the target geo ######
  819. # #################################################
  820. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  821. man_geo = self.man_cutout_obj.solid_geometry
  822. def get_angle(geo):
  823. line = cut_geo.intersection(geo)
  824. try:
  825. pt1_x = line.coords[0][0]
  826. pt1_y = line.coords[0][1]
  827. pt2_x = line.coords[1][0]
  828. pt2_y = line.coords[1][1]
  829. dx = pt1_x - pt2_x
  830. dy = pt1_y - pt2_y
  831. if dx == 0 or dy == 0:
  832. angle = 0
  833. else:
  834. radian = math.atan(dx / dy)
  835. angle = radian * 180 / math.pi
  836. except Exception as e:
  837. angle = 0
  838. return angle
  839. try:
  840. rot_angle = 0
  841. for geo_el in man_geo:
  842. if isinstance(geo_el, Polygon):
  843. work_geo = geo_el.exterior
  844. if cut_geo.intersects(work_geo):
  845. rot_angle = get_angle(geo=work_geo)
  846. else:
  847. rot_angle = 0
  848. else:
  849. rot_angle = 0
  850. if cut_geo.intersects(geo_el):
  851. rot_angle = get_angle(geo=geo_el)
  852. if rot_angle != 0:
  853. break
  854. except TypeError:
  855. if isinstance(man_geo, Polygon):
  856. work_geo = man_geo.exterior
  857. if cut_geo.intersects(work_geo):
  858. rot_angle = get_angle(geo=work_geo)
  859. else:
  860. rot_angle = 0
  861. else:
  862. rot_angle = 0
  863. if cut_geo.intersects(man_geo):
  864. rot_angle = get_angle(geo=man_geo)
  865. # rotate only if there is an angle to rotate to
  866. if rot_angle != 0:
  867. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  868. # Remove any previous utility shape
  869. self.app.geo_editor.tool_shape.clear(update=True)
  870. self.draw_utility_geometry(geo=cut_geo)
  871. def draw_utility_geometry(self, geo):
  872. self.app.geo_editor.tool_shape.add(
  873. shape=geo,
  874. color=(self.app.defaults["global_draw_color"] + '80'),
  875. update=False,
  876. layer=0,
  877. tolerance=None)
  878. self.app.geo_editor.tool_shape.redraw()
  879. def on_key_press(self, event):
  880. # events out of the self.app.collection view (it's about Project Tab) are of type int
  881. if type(event) is int:
  882. key = event
  883. # events from the GUI are of type QKeyEvent
  884. elif type(event) == QtGui.QKeyEvent:
  885. key = event.key()
  886. # events from Vispy are of type KeyEvent
  887. else:
  888. key = event.key
  889. # Escape = Deselect All
  890. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  891. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  892. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  893. self.app.plotcanvas.vis_disconnect('mouse_release', self.on_mouse_click_release)
  894. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  895. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  896. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  897. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  898. # Remove any previous utility shape
  899. self.app.geo_editor.tool_shape.clear(update=True)
  900. self.app.geo_editor.tool_shape.enabled = False
  901. # Grid toggle
  902. if key == QtCore.Qt.Key_G or key == 'G':
  903. self.app.ui.grid_snap_btn.trigger()
  904. # Jump to coords
  905. if key == QtCore.Qt.Key_J or key == 'J':
  906. l_x, l_y = self.app.on_jump_to()
  907. self.app.geo_editor.tool_shape.clear(update=True)
  908. geo = self.cutting_geo(pos=(l_x, l_y))
  909. self.draw_utility_geometry(geo=geo)
  910. def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
  911. """
  912. Subtract polygon made from points from the given object.
  913. This only operates on the paths in the original geometry,
  914. i.e. it converts polygons into paths.
  915. :param x0: x coord for lower left vertice of the polygon.
  916. :param y0: y coord for lower left vertice of the polygon.
  917. :param x1: x coord for upper right vertice of the polygon.
  918. :param y1: y coord for upper right vertice of the polygon.
  919. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  920. :return: none
  921. """
  922. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  923. # pathonly should be allways True, otherwise polygons are not subtracted
  924. flat_geometry = flatten(geometry=solid_geo)
  925. log.debug("%d paths" % len(flat_geometry))
  926. polygon = Polygon(points)
  927. toolgeo = cascaded_union(polygon)
  928. diffs = []
  929. for target in flat_geometry:
  930. if type(target) == LineString or type(target) == LinearRing:
  931. diffs.append(target.difference(toolgeo))
  932. else:
  933. log.warning("Not implemented.")
  934. return unary_union(diffs)
  935. def reset_fields(self):
  936. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  937. def flatten(geometry):
  938. """
  939. Creates a list of non-iterable linear geometry objects.
  940. Polygons are expanded into its exterior and interiors.
  941. Results are placed in self.flat_geometry
  942. :param geometry: Shapely type or list or list of list of such.
  943. """
  944. flat_geo = []
  945. try:
  946. for geo in geometry:
  947. if type(geo) == Polygon:
  948. flat_geo.append(geo.exterior)
  949. for subgeo in geo.interiors:
  950. flat_geo.append(subgeo)
  951. else:
  952. flat_geo.append(geo)
  953. except TypeError:
  954. if type(geometry) == Polygon:
  955. flat_geo.append(geometry.exterior)
  956. for subgeo in geometry.interiors:
  957. flat_geo.append(subgeo)
  958. else:
  959. flat_geo.append(geometry)
  960. return flat_geo
  961. def recursive_bounds(geometry):
  962. """
  963. Returns coordinates of rectangular bounds
  964. of geometry: (xmin, ymin, xmax, ymax).
  965. """
  966. # now it can get bounds for nested lists of objects
  967. def bounds_rec(obj):
  968. try:
  969. minx = Inf
  970. miny = Inf
  971. maxx = -Inf
  972. maxy = -Inf
  973. for k in obj:
  974. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  975. minx = min(minx, minx_)
  976. miny = min(miny, miny_)
  977. maxx = max(maxx, maxx_)
  978. maxy = max(maxy, maxy_)
  979. return minx, miny, maxx, maxy
  980. except TypeError:
  981. # it's a Shapely object, return it's bounds
  982. return obj.bounds
  983. return bounds_rec(geometry)