3 # Operations on rectangles.
4 # There is some normalization: all results return the object 'empty'
5 # if their result would contain no points.
13 # The empty rectangle.
15 empty
= (0, 0), (0, 0)
18 # Check if a rectangle is empty.
21 (left
, top
), (right
, bottom
) = r
22 return left
>= right
or top
>= bottom
25 # Compute the intersection or two or more rectangles.
26 # This works with a list or tuple argument.
29 if not list: raise error
, 'intersect called with empty list'
30 if is_empty(list[0]): return empty
31 (left
, top
), (right
, bottom
) = list[0]
38 if right
> r
: right
= r
39 if bottom
> b
: bottom
= b
40 if is_empty(((left
, top
), (right
, bottom
))):
42 return (left
, top
), (right
, bottom
)
45 # Compute the smallest rectangle containing all given rectangles.
46 # This works with a list or tuple argument.
49 (left
, top
), (right
, bottom
) = list[0]
50 for (l
, t
), (r
, b
) in list[1:]:
51 if not is_empty(((l
, t
), (r
, b
))):
54 if r
> right
: right
= r
55 if b
> bottom
: bottom
= b
56 res
= (left
, top
), (right
, bottom
)
62 # Check if a point is in a rectangle.
64 def pointinrect((h
, v
), ((left
, top
), (right
, bottom
))):
65 return left
<= h
< right
and top
<= v
< bottom
68 # Return a rectangle that is dh, dv inside another
70 def inset(((left
, top
), (right
, bottom
)), (dh
, dv
)):
75 r
= (left
, top
), (right
, bottom
)
82 # Conversions between rectangles and 'geometry tuples',
83 # given as origin (h, v) and dimensions (width, height).
85 def rect2geom((left
, top
), (right
, bottom
)):
86 return (left
, top
), (right
-left
, bottom
-top
)
88 def geom2rect((h
, v
), (width
, height
)):
89 return (h
, v
), (h
+width
, v
+height
)