source: tools/generate_poly.py@ 443:fffb9becf608

Last change on this file since 443:fffb9becf608 was 443:fffb9becf608, checked in by Simon Cross <hodgestar@…>, 8 years ago

Shape generator.

File size: 2.1 KB
Line 
1import optparse
2import sys
3import math
4
5
6def parse_params(args):
7 params = {}
8 for arg in args:
9 key, _, value = arg.partition("=")
10 params[key] = value
11 return params
12
13
14def parse_args(args):
15 """Parse arguments."""
16 parser = optparse.OptionParser(usage="%prog <type> arg1=foo arg2=bar")
17 opts, args = parser.parse_args(args)
18 args = args[1:]
19
20 if not args:
21 parser.print_help()
22 return None, {}, opts
23
24 obj_type = args[0]
25 params = parse_params(args[1:])
26 return obj_type, params, opts
27
28
29class PolyGenerator(object):
30 def generate(self, obj_type, params, opts):
31 handler = getattr(self, 'generate_%s' % (obj_type,),
32 self.unknown_type)
33 return handler(params, opts)
34
35 def print_poly(self, poly):
36 print "Poly:"
37 for point in poly:
38 print " - [%d, %d]" % tuple(point)
39
40 def unknown_type(self, params, opts):
41 prefix = "generate_"
42 known_types = [k[len(prefix):] for k in self.__dict__
43 if k.startswith(prefix)]
44 raise ValueError("Unknown object type. Known types: %s" %
45 ",".join(known_types))
46
47 def check_params(self, params, *sigs):
48 results = []
49 for name, parser in sigs:
50 value = params.get(name)
51 try:
52 result = parser(value)
53 except:
54 raise ValueError(
55 "Failed to parse param %s with value %s (parser: %r)"
56 % (name, value, parser))
57 results.append(result)
58 return results
59
60 def generate_circle(self, params, opts):
61 r, steps = self.check_params(params, ("r", int), ("steps", int))
62 poly = []
63 rad, step_size = 0, 2 * math.pi / steps
64 for p in range(steps + 1):
65 x, y = r * math.sin(rad), r * math.cos(rad)
66 poly.append([x, y])
67 rad += step_size
68 return poly
69
70
71if __name__ == "__main__":
72 obj_type, params, opts = parse_args(sys.argv)
73 if obj_type is not None:
74 p = PolyGenerator()
75 poly = p.generate(obj_type, params, opts)
76 p.print_poly(poly)
Note: See TracBrowser for help on using the repository browser.