14

I need to clip several regions reg: like Rectangle, Polygon, Ellipse... My goal isn't to plot the clipping but to have a representation of each new region.

I searched if there was any package or function to perform polygon clipping at least, but I couldn't find any lead.

My main question is:

  • Is there an already implemented algorithm in mathematica to perform polygon or region clipping ?

else:

  • Should I better link an external polygon clipping library (such as Clipper, Boost.Geometry or CGAL) with mathematica to do so ?

Edit:

To illustrate what I aim for:

Overlapping Rectangle

I have 5 rectangles that are overlapping, I would like to have:

Non-overlapping Regions

I have now 8 regions that aren't intersecting/overlapping with others.

A.M.
  • 141
  • 3

1 Answers1

7

Using boolean operations to test every possible combination of area intersections:

r1 = Disk[{0, 0}, 1];
r2 = Disk[{1/8, 0}, {1/2, 3/2}];
r3 = Rectangle[{1/4, 0}, {2, 1}];
regions={r1,r2,r3};
Graphics[{Opacity[.5], {{Red, r1}, {Green, r2}, {Blue, r3}}}]

enter image description here

range = {{-2,2},{-2,2}};
(*warning RegionPlot throws errors
    if nothing is in the plot range*)
sub[set_, r_] := 
 Module[{
   in = Flatten@Position[set, 1], 
   out = Flatten@Position[set, 0]}, 
  If[Union@set === {1}, RegionIntersection @@ r, 
   RegionDifference[
      BooleanRegion[And, r[[in]]], 
      BooleanRegion[Or, r[[out]]]]]]
c = Tuples[{0, 1}, Length@regions][[2 ;;]]; (*dont include first tuple {0,0,..}*)
subregions = Select[sub[#, regions] & /@ c, Area@# > 0 &];
s = MapThread[RegionPlot[#1, PlotStyle -> #2, PlotRange -> range] &,
   {subregions, 
    Table[Hue[RandomReal[{0, 2/3}]], {Length@subregions}]}];
Grid[{s, c}]
Show[s, PlotRange -> range]

enter image description here

enter image description here

notice there are disconnected sub regions that happen when a single region is split by the others. Kind of stumped on how to split those automatically into separate regions.

edit per comment from @JasonB we can get all the discrete regions, but it requires generating mesh regions:

  ConnectedMeshComponents@DiscretizeRegion[#] & /@ subregions

enter image description here

edit: the example

regions = {Rectangle[{5, -15}, {35, 15}], 
   Rectangle[{25, -20}, {45, 20}], Rectangle[{20, -5}, {35, 5}], 
   Rectangle[{30, 10}, {45, 20}], Rectangle[{35, -20}, {45, -5}]};
range = {{0, 50}, {-30, 30}}

enter image description here

george2079
  • 38,913
  • 1
  • 43
  • 110