ToolCutOut.py 48 KB

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