- #1
emaybert
- 4
- 0
I'm trying to write an algorithm that will take in, as parameters, two rectangles R1 and R2 and calculate their union.
R1 and R2 may be in rotated (independently), one may be completely inside the other, or they may not be overlapping at all.
Example(Image):
View attachment 7700
The algorithm I wrote currently takes in the top-left x,y of each R as well as width/height (rotation not yet considered)
This seems to work for very simple cases, but like I said, it (a) does not factor in rotation, nor (b) consider when the union is a 5-sided polygon (see last example,in image).
Any guidance on how this is done mathematically would be greatly appreciated.
I'm not looking for code ( although that would be great ), but just the general mathematical approach to solving.
R1 and R2 may be in rotated (independently), one may be completely inside the other, or they may not be overlapping at all.
Example(Image):
View attachment 7700
The algorithm I wrote currently takes in the top-left x,y of each R as well as width/height (rotation not yet considered)
Code:
getUnionRect( x1, y1, w1, h1, x2, y2, w2, h2 )
{
var rx, ry, rw, rh; //resulting union rectangle (x,y,width,height)
rx = x2 > x1 ? x2 : x1;
ry = y2 > y1 ? y2 : y1;
rw = (x1 < x2 ) ? (x1+w1-x2): (x2+w2-x1)
rh = (y1 + h1) < (y2 + h2) ? (y1 + h1- y2) : (y2 + h2 - y1) ;
}
This seems to work for very simple cases, but like I said, it (a) does not factor in rotation, nor (b) consider when the union is a 5-sided polygon (see last example,in image).
Any guidance on how this is done mathematically would be greatly appreciated.
I'm not looking for code ( although that would be great ), but just the general mathematical approach to solving.