ToolCutOut.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. self.app.ui.splitter.setSizes([0, 1])
  271. except AttributeError:
  272. pass
  273. else:
  274. if self.app.ui.splitter.sizes()[0] == 0:
  275. self.app.ui.splitter.setSizes([1, 1])
  276. FlatCAMTool.run(self)
  277. self.set_tool_ui()
  278. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  279. def install(self, icon=None, separator=None, **kwargs):
  280. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  281. def set_tool_ui(self):
  282. self.reset_fields()
  283. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  284. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  285. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  286. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  287. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  288. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  289. self.gapFinished.connect(self.on_gap_finished)
  290. def on_freeform_cutout(self):
  291. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  292. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  293. # obj_.subtract_polygon(pts)
  294. name = self.obj_combo.currentText()
  295. # Get source object.
  296. try:
  297. cutout_obj = self.app.collection.get_by_name(str(name))
  298. except Exception as e:
  299. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  300. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  301. return "Could not retrieve object: %s" % name
  302. if cutout_obj is None:
  303. self.app.inform.emit(_("[ERROR_NOTCL] There is no object selected for Cutout.\nSelect one and try again."))
  304. return
  305. try:
  306. dia = float(self.dia.get_value())
  307. except ValueError:
  308. # try to convert comma to decimal point. if it's still not working error message and return
  309. try:
  310. dia = float(self.dia.get_value().replace(',', '.'))
  311. except ValueError:
  312. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  313. "Add it and retry."))
  314. return
  315. if 0 in {dia}:
  316. self.app.inform.emit(_("[WARNING_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  317. return "Tool Diameter is zero value. Change it to a positive real number."
  318. try:
  319. kind = self.obj_kind_combo.get_value()
  320. except ValueError:
  321. return
  322. try:
  323. margin = float(self.margin.get_value())
  324. except ValueError:
  325. # try to convert comma to decimal point. if it's still not working error message and return
  326. try:
  327. margin = float(self.margin.get_value().replace(',', '.'))
  328. except ValueError:
  329. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  330. "Add it and retry."))
  331. return
  332. try:
  333. gapsize = float(self.gapsize.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. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  338. except ValueError:
  339. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  340. "Add it and retry."))
  341. return
  342. try:
  343. gaps = self.gaps.get_value()
  344. except TypeError:
  345. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  346. return
  347. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  348. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: "
  349. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  350. "Fill in a correct value and retry. "))
  351. return
  352. if cutout_obj.multigeo is True:
  353. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  354. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  355. "and after that perform Cutout."))
  356. return
  357. convex_box = self.convex_box.get_value()
  358. gapsize = gapsize / 2 + (dia / 2)
  359. def geo_init(geo_obj, app_obj):
  360. solid_geo = []
  361. if isinstance(cutout_obj, FlatCAMGerber):
  362. if convex_box:
  363. object_geo = cutout_obj.solid_geometry.convex_hull
  364. else:
  365. object_geo = cutout_obj.solid_geometry
  366. else:
  367. object_geo = cutout_obj.solid_geometry
  368. def cutout_handler(geom):
  369. # Get min and max data for each object as we just cut rectangles across X or Y
  370. xmin, ymin, xmax, ymax = recursive_bounds(geom)
  371. px = 0.5 * (xmin + xmax) + margin
  372. py = 0.5 * (ymin + ymax) + margin
  373. lenx = (xmax - xmin) + (margin * 2)
  374. leny = (ymax - ymin) + (margin * 2)
  375. proc_geometry = []
  376. if gaps == 'None':
  377. pass
  378. else:
  379. if gaps == '8' or gaps == '2LR':
  380. geom = self.subtract_poly_from_geo(geom,
  381. xmin - gapsize, # botleft_x
  382. py - gapsize + leny / 4, # botleft_y
  383. xmax + gapsize, # topright_x
  384. py + gapsize + leny / 4) # topright_y
  385. geom = self.subtract_poly_from_geo(geom,
  386. xmin - gapsize,
  387. py - gapsize - leny / 4,
  388. xmax + gapsize,
  389. py + gapsize - leny / 4)
  390. if gaps == '8' or gaps == '2TB':
  391. geom = self.subtract_poly_from_geo(geom,
  392. px - gapsize + lenx / 4,
  393. ymin - gapsize,
  394. px + gapsize + lenx / 4,
  395. ymax + gapsize)
  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. if gaps == '4' or gaps == 'LR':
  402. geom = self.subtract_poly_from_geo(geom,
  403. xmin - gapsize,
  404. py - gapsize,
  405. xmax + gapsize,
  406. py + gapsize)
  407. if gaps == '4' or gaps == 'TB':
  408. geom = self.subtract_poly_from_geo(geom,
  409. px - gapsize,
  410. ymin - gapsize,
  411. px + gapsize,
  412. ymax + gapsize)
  413. try:
  414. for g in geom:
  415. proc_geometry.append(g)
  416. except TypeError:
  417. proc_geometry.append(geom)
  418. return proc_geometry
  419. if kind == 'single':
  420. object_geo = unary_union(object_geo)
  421. # for geo in object_geo:
  422. if isinstance(cutout_obj, FlatCAMGerber):
  423. if isinstance(object_geo, MultiPolygon):
  424. x0, y0, x1, y1 = object_geo.bounds
  425. object_geo = box(x0, y0, x1, y1)
  426. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  427. geo = geo_buf.exterior
  428. else:
  429. geo = object_geo
  430. solid_geo = cutout_handler(geom=geo)
  431. else:
  432. try:
  433. __ = iter(object_geo)
  434. except TypeError:
  435. object_geo = [object_geo]
  436. for geom_struct in object_geo:
  437. if isinstance(cutout_obj, FlatCAMGerber):
  438. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  439. solid_geo += cutout_handler(geom=geom_struct)
  440. geo_obj.solid_geometry = deepcopy(solid_geo)
  441. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  442. geo_obj.options['xmin'] = xmin
  443. geo_obj.options['ymin'] = ymin
  444. geo_obj.options['xmax'] = xmax
  445. geo_obj.options['ymax'] = ymax
  446. geo_obj.options['cnctooldia'] = str(dia)
  447. outname = cutout_obj.options["name"] + "_cutout"
  448. self.app.new_object('geometry', outname, geo_init)
  449. cutout_obj.plot()
  450. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  451. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  452. self.app.should_we_save = True
  453. def on_rectangular_cutout(self):
  454. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  455. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  456. # obj_.subtract_polygon(pts)
  457. name = self.obj_combo.currentText()
  458. # Get source object.
  459. try:
  460. cutout_obj = self.app.collection.get_by_name(str(name))
  461. except Exception as e:
  462. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  463. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  464. return "Could not retrieve object: %s" % name
  465. if cutout_obj is None:
  466. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % cutout_obj)
  467. try:
  468. dia = float(self.dia.get_value())
  469. except ValueError:
  470. # try to convert comma to decimal point. if it's still not working error message and return
  471. try:
  472. dia = float(self.dia.get_value().replace(',', '.'))
  473. except ValueError:
  474. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  475. "Add it and retry."))
  476. return
  477. if 0 in {dia}:
  478. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  479. return "Tool Diameter is zero value. Change it to a positive real number."
  480. try:
  481. kind = self.obj_kind_combo.get_value()
  482. except ValueError:
  483. return
  484. try:
  485. margin = float(self.margin.get_value())
  486. except ValueError:
  487. # try to convert comma to decimal point. if it's still not working error message and return
  488. try:
  489. margin = float(self.margin.get_value().replace(',', '.'))
  490. except ValueError:
  491. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  492. "Add it and retry."))
  493. return
  494. try:
  495. gapsize = float(self.gapsize.get_value())
  496. except ValueError:
  497. # try to convert comma to decimal point. if it's still not working error message and return
  498. try:
  499. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  500. except ValueError:
  501. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  502. "Add it and retry."))
  503. return
  504. try:
  505. gaps = self.gaps.get_value()
  506. except TypeError:
  507. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  508. return
  509. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  510. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: "
  511. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  512. "Fill in a correct value and retry. "))
  513. return
  514. if cutout_obj.multigeo is True:
  515. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  516. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  517. "and after that perform Cutout."))
  518. return
  519. # Get min and max data for each object as we just cut rectangles across X or Y
  520. gapsize = gapsize / 2 + (dia / 2)
  521. def geo_init(geo_obj, app_obj):
  522. solid_geo = []
  523. object_geo = cutout_obj.solid_geometry
  524. def cutout_rect_handler(geom):
  525. proc_geometry = []
  526. px = 0.5 * (xmin + xmax) + margin
  527. py = 0.5 * (ymin + ymax) + margin
  528. lenx = (xmax - xmin) + (margin * 2)
  529. leny = (ymax - ymin) + (margin * 2)
  530. if gaps == 'None':
  531. pass
  532. else:
  533. if gaps == '8' or gaps == '2LR':
  534. geom = self.subtract_poly_from_geo(geom,
  535. xmin - gapsize, # botleft_x
  536. py - gapsize + leny / 4, # botleft_y
  537. xmax + gapsize, # topright_x
  538. py + gapsize + leny / 4) # topright_y
  539. geom = self.subtract_poly_from_geo(geom,
  540. xmin - gapsize,
  541. py - gapsize - leny / 4,
  542. xmax + gapsize,
  543. py + gapsize - leny / 4)
  544. if gaps == '8' or gaps == '2TB':
  545. geom = self.subtract_poly_from_geo(geom,
  546. px - gapsize + lenx / 4,
  547. ymin - gapsize,
  548. px + gapsize + lenx / 4,
  549. ymax + gapsize)
  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. if gaps == '4' or gaps == 'LR':
  556. geom = self.subtract_poly_from_geo(geom,
  557. xmin - gapsize,
  558. py - gapsize,
  559. xmax + gapsize,
  560. py + gapsize)
  561. if gaps == '4' or gaps == 'TB':
  562. geom = self.subtract_poly_from_geo(geom,
  563. px - gapsize,
  564. ymin - gapsize,
  565. px + gapsize,
  566. ymax + gapsize)
  567. try:
  568. for g in geom:
  569. proc_geometry.append(g)
  570. except TypeError:
  571. proc_geometry.append(geom)
  572. return proc_geometry
  573. if kind == 'single':
  574. object_geo = unary_union(object_geo)
  575. xmin, ymin, xmax, ymax = object_geo.bounds
  576. geo = box(xmin, ymin, xmax, ymax)
  577. # if Gerber create a buffer at a distance
  578. # if Geometry then cut through the geometry
  579. if isinstance(cutout_obj, FlatCAMGerber):
  580. geo = geo.buffer(margin + abs(dia / 2))
  581. solid_geo = cutout_rect_handler(geom=geo)
  582. else:
  583. try:
  584. __ = iter(object_geo)
  585. except TypeError:
  586. object_geo = [object_geo]
  587. for geom_struct in object_geo:
  588. geom_struct = unary_union(geom_struct)
  589. xmin, ymin, xmax, ymax = geom_struct.bounds
  590. geom_struct = box(xmin, ymin, xmax, ymax)
  591. if isinstance(cutout_obj, FlatCAMGerber):
  592. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  593. solid_geo += cutout_rect_handler(geom=geom_struct)
  594. geo_obj.solid_geometry = deepcopy(solid_geo)
  595. geo_obj.options['cnctooldia'] = str(dia)
  596. outname = cutout_obj.options["name"] + "_cutout"
  597. self.app.new_object('geometry', outname, geo_init)
  598. # cutout_obj.plot()
  599. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  600. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  601. self.app.should_we_save = True
  602. def on_manual_gap_click(self):
  603. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  604. self.app.geo_editor.tool_shape.enabled = True
  605. try:
  606. self.cutting_dia = float(self.dia.get_value())
  607. except ValueError:
  608. # try to convert comma to decimal point. if it's still not working error message and return
  609. try:
  610. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  611. except ValueError:
  612. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  613. "Add it and retry."))
  614. return
  615. if 0 in {self.cutting_dia}:
  616. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  617. return "Tool Diameter is zero value. Change it to a positive real number."
  618. try:
  619. self.cutting_gapsize = float(self.gapsize.get_value())
  620. except ValueError:
  621. # try to convert comma to decimal point. if it's still not working error message and return
  622. try:
  623. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  624. except ValueError:
  625. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  626. "Add it and retry."))
  627. return
  628. name = self.man_object_combo.currentText()
  629. # Get Geometry source object to be used as target for Manual adding Gaps
  630. try:
  631. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  632. except Exception as e:
  633. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  634. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  635. return "Could not retrieve object: %s" % name
  636. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  637. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  638. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  639. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  640. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  641. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  642. self.app.plotcanvas.vis_connect('mouse_release', self.doit)
  643. # To be called after clicking on the plot.
  644. def doit(self, event):
  645. # do paint single only for left mouse clicks
  646. if event.button == 1:
  647. self.app.inform.emit(_("Making manual bridge gap..."))
  648. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  649. self.on_manual_cutout(click_pos=pos)
  650. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  651. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  652. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  653. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  654. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  655. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  656. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  657. self.app.geo_editor.tool_shape.clear(update=True)
  658. self.app.geo_editor.tool_shape.enabled = False
  659. self.gapFinished.emit()
  660. # if RMB then we exit
  661. elif event.button == 2:
  662. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  663. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  664. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  665. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  666. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  667. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  668. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  669. # Remove any previous utility shape
  670. self.app.geo_editor.tool_shape.clear(update=True)
  671. self.app.geo_editor.tool_shape.enabled = False
  672. def on_manual_cutout(self, click_pos):
  673. name = self.man_object_combo.currentText()
  674. # Get source object.
  675. try:
  676. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  677. except Exception as e:
  678. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  679. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  680. return "Could not retrieve object: %s" % name
  681. if self.man_cutout_obj is None:
  682. self.app.inform.emit(
  683. _("[ERROR_NOTCL] Geometry object for manual cutout not found: %s") % self.man_cutout_obj)
  684. return
  685. # use the snapped position as reference
  686. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  687. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  688. self.man_cutout_obj.subtract_polygon(cut_poly)
  689. self.man_cutout_obj.plot()
  690. self.app.inform.emit(_("[success] Added manual Bridge Gap."))
  691. self.app.should_we_save = True
  692. def on_gap_finished(self):
  693. # if CTRL key modifier is pressed then repeat the bridge gap cut
  694. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  695. if key_modifier == Qt.ControlModifier:
  696. self.on_manual_gap_click()
  697. def on_manual_geo(self):
  698. name = self.obj_combo.currentText()
  699. # Get source object.
  700. try:
  701. cutout_obj = self.app.collection.get_by_name(str(name))
  702. except Exception as e:
  703. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  704. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Gerber object: %s") % name)
  705. return "Could not retrieve object: %s" % name
  706. if cutout_obj is None:
  707. self.app.inform.emit(_("[ERROR_NOTCL] There is no Gerber object selected for Cutout.\n"
  708. "Select one and try again."))
  709. return
  710. if not isinstance(cutout_obj, FlatCAMGerber):
  711. self.app.inform.emit(_("[ERROR_NOTCL] The selected object has to be of Gerber type.\n"
  712. "Select a Gerber file and try again."))
  713. return
  714. try:
  715. dia = float(self.dia.get_value())
  716. except ValueError:
  717. # try to convert comma to decimal point. if it's still not working error message and return
  718. try:
  719. dia = float(self.dia.get_value().replace(',', '.'))
  720. except ValueError:
  721. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  722. "Add it and retry."))
  723. return
  724. if 0 in {dia}:
  725. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  726. return "Tool Diameter is zero value. Change it to a positive real number."
  727. try:
  728. kind = self.obj_kind_combo.get_value()
  729. except ValueError:
  730. return
  731. try:
  732. margin = float(self.margin.get_value())
  733. except ValueError:
  734. # try to convert comma to decimal point. if it's still not working error message and return
  735. try:
  736. margin = float(self.margin.get_value().replace(',', '.'))
  737. except ValueError:
  738. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  739. "Add it and retry."))
  740. return
  741. convex_box = self.convex_box.get_value()
  742. def geo_init(geo_obj, app_obj):
  743. geo_union = unary_union(cutout_obj.solid_geometry)
  744. if convex_box:
  745. geo = geo_union.convex_hull
  746. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  747. elif kind == 'single':
  748. if isinstance(geo_union, Polygon) or \
  749. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  750. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  751. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  752. elif isinstance(geo_union, MultiPolygon):
  753. x0, y0, x1, y1 = geo_union.bounds
  754. geo = box(x0, y0, x1, y1)
  755. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  756. else:
  757. self.app.inform.emit(_("[ERROR_NOTCL] Geometry not supported for cutout: %s") % type(geo_union))
  758. return 'fail'
  759. else:
  760. geo = geo_union
  761. geo = geo.buffer(margin + abs(dia / 2))
  762. if isinstance(geo, Polygon):
  763. geo_obj.solid_geometry = geo.exterior
  764. elif isinstance(geo, MultiPolygon):
  765. solid_geo = []
  766. for poly in geo:
  767. solid_geo.append(poly.exterior)
  768. geo_obj.solid_geometry = deepcopy(solid_geo)
  769. geo_obj.options['cnctooldia'] = str(dia)
  770. outname = cutout_obj.options["name"] + "_cutout"
  771. self.app.new_object('geometry', outname, geo_init)
  772. def cutting_geo(self, pos):
  773. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  774. # cutting area definition
  775. orig_x = pos[0]
  776. orig_y = pos[1]
  777. xmin = orig_x - offset
  778. ymin = orig_y - offset
  779. xmax = orig_x + offset
  780. ymax = orig_y + offset
  781. cut_poly = box(xmin, ymin, xmax, ymax)
  782. return cut_poly
  783. def on_mouse_move(self, event):
  784. self.app.on_mouse_move_over_plot(event=event)
  785. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  786. event.xdata, event.ydata = pos[0], pos[1]
  787. try:
  788. x = float(event.xdata)
  789. y = float(event.ydata)
  790. except TypeError:
  791. return
  792. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  793. # #################################################
  794. # ### This section makes the cutting geo to #######
  795. # ### rotate if it intersects the target geo ######
  796. # #################################################
  797. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  798. man_geo = self.man_cutout_obj.solid_geometry
  799. def get_angle(geo):
  800. line = cut_geo.intersection(geo)
  801. try:
  802. pt1_x = line.coords[0][0]
  803. pt1_y = line.coords[0][1]
  804. pt2_x = line.coords[1][0]
  805. pt2_y = line.coords[1][1]
  806. dx = pt1_x - pt2_x
  807. dy = pt1_y - pt2_y
  808. if dx == 0 or dy == 0:
  809. angle = 0
  810. else:
  811. radian = math.atan(dx / dy)
  812. angle = radian * 180 / math.pi
  813. except Exception as e:
  814. angle = 0
  815. return angle
  816. try:
  817. rot_angle = 0
  818. for geo_el in man_geo:
  819. if isinstance(geo_el, Polygon):
  820. work_geo = geo_el.exterior
  821. if cut_geo.intersects(work_geo):
  822. rot_angle = get_angle(geo=work_geo)
  823. else:
  824. rot_angle = 0
  825. else:
  826. rot_angle = 0
  827. if cut_geo.intersects(geo_el):
  828. rot_angle = get_angle(geo=geo_el)
  829. if rot_angle != 0:
  830. break
  831. except TypeError:
  832. if isinstance(man_geo, Polygon):
  833. work_geo = man_geo.exterior
  834. if cut_geo.intersects(work_geo):
  835. rot_angle = get_angle(geo=work_geo)
  836. else:
  837. rot_angle = 0
  838. else:
  839. rot_angle = 0
  840. if cut_geo.intersects(man_geo):
  841. rot_angle = get_angle(geo=man_geo)
  842. # rotate only if there is an angle to rotate to
  843. if rot_angle != 0:
  844. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  845. # Remove any previous utility shape
  846. self.app.geo_editor.tool_shape.clear(update=True)
  847. self.draw_utility_geometry(geo=cut_geo)
  848. def draw_utility_geometry(self, geo):
  849. self.app.geo_editor.tool_shape.add(
  850. shape=geo,
  851. color=(self.app.defaults["global_draw_color"] + '80'),
  852. update=False,
  853. layer=0,
  854. tolerance=None)
  855. self.app.geo_editor.tool_shape.redraw()
  856. def on_key_press(self, event):
  857. # events out of the self.app.collection view (it's about Project Tab) are of type int
  858. if type(event) is int:
  859. key = event
  860. # events from the GUI are of type QKeyEvent
  861. elif type(event) == QtGui.QKeyEvent:
  862. key = event.key()
  863. # events from Vispy are of type KeyEvent
  864. else:
  865. key = event.key
  866. # Escape = Deselect All
  867. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  868. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  869. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  870. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  871. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  872. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  873. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  874. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  875. # Remove any previous utility shape
  876. self.app.geo_editor.tool_shape.clear(update=True)
  877. self.app.geo_editor.tool_shape.enabled = False
  878. def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
  879. """
  880. Subtract polygon made from points from the given object.
  881. This only operates on the paths in the original geometry,
  882. i.e. it converts polygons into paths.
  883. :param x0: x coord for lower left vertice of the polygon.
  884. :param y0: y coord for lower left vertice of the polygon.
  885. :param x1: x coord for upper right vertice of the polygon.
  886. :param y1: y coord for upper right vertice of the polygon.
  887. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  888. :return: none
  889. """
  890. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  891. # pathonly should be allways True, otherwise polygons are not subtracted
  892. flat_geometry = flatten(geometry=solid_geo)
  893. log.debug("%d paths" % len(flat_geometry))
  894. polygon = Polygon(points)
  895. toolgeo = cascaded_union(polygon)
  896. diffs = []
  897. for target in flat_geometry:
  898. if type(target) == LineString or type(target) == LinearRing:
  899. diffs.append(target.difference(toolgeo))
  900. else:
  901. log.warning("Not implemented.")
  902. return unary_union(diffs)
  903. def reset_fields(self):
  904. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  905. def flatten(geometry):
  906. """
  907. Creates a list of non-iterable linear geometry objects.
  908. Polygons are expanded into its exterior and interiors.
  909. Results are placed in self.flat_geometry
  910. :param geometry: Shapely type or list or list of list of such.
  911. """
  912. flat_geo = []
  913. try:
  914. for geo in geometry:
  915. if type(geo) == Polygon:
  916. flat_geo.append(geo.exterior)
  917. for subgeo in geo.interiors:
  918. flat_geo.append(subgeo)
  919. else:
  920. flat_geo.append(geo)
  921. except TypeError:
  922. if type(geometry) == Polygon:
  923. flat_geo.append(geometry.exterior)
  924. for subgeo in geometry.interiors:
  925. flat_geo.append(subgeo)
  926. else:
  927. flat_geo.append(geometry)
  928. return flat_geo
  929. def recursive_bounds(geometry):
  930. """
  931. Returns coordinates of rectangular bounds
  932. of geometry: (xmin, ymin, xmax, ymax).
  933. """
  934. # now it can get bounds for nested lists of objects
  935. def bounds_rec(obj):
  936. try:
  937. minx = Inf
  938. miny = Inf
  939. maxx = -Inf
  940. maxy = -Inf
  941. for k in obj:
  942. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  943. minx = min(minx, minx_)
  944. miny = min(miny, miny_)
  945. maxx = max(maxx, maxx_)
  946. maxy = max(maxy, maxy_)
  947. return minx, miny, maxx, maxy
  948. except TypeError:
  949. # it's a Shapely object, return it's bounds
  950. return obj.bounds
  951. return bounds_rec(geometry)