1 """
2 This module extends the Springbot class to alow
3 its objects to be sent via xmlrpc or other methods over
4 network by translating(two ways) the object itself to a simpler
5 structure based on dictionary and tuples.
6 """
7
8 from springbot import Springbot
9 from gear import Spring, Node
10 import exceptions
11
12
13
14
16 """
17 Extends evolvable springbot to add marshal and unmarshal methods to
18 send more easily through network like xmlrpc
19 """
20
22 """
23 Transforms the springbot into a dictionary
24 """
25 springbot_d = {}
26 for key, value in self._info.iteritems():
27 springbot_d[key] = value
28
29 springbot_d['nodes'] = tuple({'id': node.id,
30 'pos' : (node.pos.x, node.pos.y),
31 'vel': (node.vel.x, node.vel.y),
32 'acc': (node.acc.x, node.acc.y)} for node in self.nodes)
33
34 springbot_d['springs'] = tuple({'from': spring.a.id, 'to': spring.b.id,
35 'amplitude': spring.amplitude, 'offset': spring.offset,
36 'normal': spring.normal} for spring in self.springs)
37
38 return springbot_d
39
40
42 """
43 Reads a dictionary into this springbot
44 """
45 self.nodes = []
46 self.springs = []
47
48 for node_d in dic['nodes']:
49 newnode = Node(node_d['pos'], node_d['vel'], node_d['acc'])
50 newnode.id = node_d['id']
51 self.nodes.append(newnode)
52
53 for spring_d in dic['springs']:
54 id_a = spring_d['from']
55 id_b = spring_d['to']
56
57 for node in self.nodes:
58 if node.id == id_a:
59 a = node
60 break
61 else:
62 raise exceptions.IndexError("node id %d(from) not found\n" % (id_a))
63
64
65 for node in self.nodes:
66 if node.id == id_b:
67 b = node
68 break
69 else:
70 raise exceptions.IndexError("node id %d(to) not found\n" % (id_b))
71
72 self.springs.append(Spring(a, b, spring_d['amplitude'], spring_d['offset'], spring_d['normal']))
73
74 del dic['nodes']
75 del dic['springs']
76 self._info = dict(dic)
77
78 return self
79