You can do it iteratively and create a set of connected components (instead of always only one connected component):
- Put all the polygons in the "open" list. Initialize the list of components to empty.
- Until open is empty:
- Remove the polygon p from the open and set the flag to true.
- Repeat on change true:
- set changed to false
- for each polygon q in open:
- If q crosses p, remove q from open, change to true and set p to the union of p and q.
- add p to the components.
At the end, the components will consist of all disjoint, connected components that can be formed by a union of the input polygons. In your placed pattern, it should create one polygon.
This is not the most efficient approach (see the algorithms in the link posted by Ricky Bobby), but it has the advantage of simplicity. If you are not dealing with hundreds of polygons, it should work just fine.
PS As @japreiss points out, a union can have holes, even if none of the input polygons has holes, even if the inputs are all convex polygons. If the inputs can be concave, then even the union of two polygons can have a hole. Does your 2-polygon algorithm handle it already?
source share