blob: aa5ff4449b76a0abdb78bdc9fe18a890eafc4a7c [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'rect'.
2#
3# Operations on rectangles.
4# There is some normalization: all results return the object 'empty'
5# if their result would contain no points.
6
7
8# Exception.
9#
10error = 'rect.error'
11
12
13# The empty rectangle.
14#
15empty = (0, 0), (0, 0)
16
17
18# Check if a rectangle is empty.
19#
20def is_empty((left, top), (right, bottom)):
21 return left >= right or top >= bottom
22
23
24# Compute the intersection or two or more rectangles.
25# This works with a list or tuple argument.
26#
27def intersect(list):
28 if not list: raise error, 'intersect called with empty list'
29 if is_empty(list[0]): return empty
30 (left, top), (right, bottom) = list[0]
31 for rect in list[1:]:
Guido van Rossum124eb941990-10-26 13:44:32 +000032 if is_empty(rect):
33 return empty
34 (l, t), (r, b) = rect
35 if left < l: left = l
36 if top < t: top = t
37 if right > r: right = r
38 if bottom > b: bottom = b
39 if is_empty((left, top), (right, bottom)):
40 return empty
Guido van Rossumc6360141990-10-13 19:23:40 +000041 return (left, top), (right, bottom)
42
43
44# Compute the smallest rectangle containing all given rectangles.
45# This works with a list or tuple argument.
46#
47def union(list):
48 (left, top), (right, bottom) = empty
49 for (l, t), (r, b) in list[1:]:
50 if not is_empty((l, t), (r, b)):
51 if l < left: left = l
52 if t < top: top = t
53 if r > right: right = r
54 if b > bottom: bottom = b
55 res = (left, top), (right, bottom)
56 if is_empty(res):
57 return empty
58 return res
59
60
61# Check if a point is in a rectangle.
62#
63def pointinrect((h, v), ((left, top), (right, bottom))):
64 return left <= h < right and top <= v < bottom
65
66
67# Return a rectangle that is dh, dv inside another
68#
69def inset(((left, top), (right, bottom)), (dh, dv)):
70 left = left + dh
71 top = top + dv
72 right = right - dh
73 bottom = bottom - dv
74 r = (left, top), (right, bottom)
75 if is_empty(r):
76 return empty
77 else:
78 return r
79
80
81# Conversions between rectangles and 'geometry tuples',
82# given as origin (h, v) and dimensions (width, height).
83#
84def rect2geom((left, top), (right, bottom)):
85 return (left, top), (right-left, bottom-top)
86
87def geom2rect((h, v), (width, height)):
88 return (h, v), (h+width, v+height)