Script to grab stop codes from allstops.xml and sort
[ottawa-travel-planner.git] / RectTools.py
bloba50ce920e018c291fd75a775b99f13f2006e948a
2 # vi: set softtabstop=4 shiftwidth=4 tabstop=8 expandtab:
4 class Rectangle(object):
5 def __init__(self, x, y, w, h):
6 self.x = x
7 self.y = y
8 self.width = w
9 self.height = h
11 def __eq__(self, other):
12 if self is other:
13 return True
14 if not isinstance(other, Rectangle):
15 return False
16 return (self.x == other.x and self.y == other.y
17 and self.width == other.width and self.height == other.height)
19 def __str__(self):
20 return "(%d,%d) [%dx%d]" % (self.x, self.y, self.width, self.height)
22 def __repr__(self):
23 return "Rectangle(%d,%d, %d,%d)" % (
24 self.x, self.y, self.width, self.height)
27 class PolyRect(object):
28 def __init__(self, rects):
29 self.rects = rects
31 def area(self):
32 return sum([a.width * a.height for a in self.rects])
34 def subtract(self, r):
35 """Subtracts one rectangle from the list."""
36 newrects = []
38 for i in self.rects:
39 inter = intersection(i, r)
40 if inter is None:
41 newrects.append(i)
42 else:
43 # Create one rectangle above, one below, one left, one right.
44 if i.y < inter.y:
45 newrects.append(Rectangle(i.x, i.y, i.width, inter.y - i.y))
46 if i.y + i.height > inter.y + inter.height:
47 y = inter.y + inter.height
48 newrects.append(Rectangle(i.x, y,
49 i.width, i.height - (y - i.y)))
50 if i.x < inter.x:
51 x = i.x
52 y = max(i.y, inter.y)
53 width = inter.x - i.x
54 height = min(i.y + i.height, inter.y + inter.height) - y
55 newrects.append(Rectangle(x, y, width, height))
57 if i.x + i.width > inter.x + inter.width:
58 x = inter.x + inter.width
59 y = max(i.y, inter.y)
60 width = i.width - (x - i.x)
61 height = min(i.y + i.height, inter.y + inter.height) - y
62 newrects.append(Rectangle(x, y, width, height))
64 return PolyRect(newrects)
66 def intersection(r1, r2):
67 x = max(r1.x, r2.x)
68 width = min(r1.width - (x - r1.x), r2.width - (x - r2.x))
69 y = max(r1.y, r2.y)
70 height = min(r1.height - (y - r1.y), r2.height - (y - r2.y))
72 if width <= 0 or height <= 0:
73 return None
74 return Rectangle(x, y, width, height)