Action.Child: Handle calling the definition.
[python-bulletml.git] / bulletml / parser.py
1 """BulletML parser.
2
3 This is based on the format described at
4 http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml_ref_e.html.
5
6 Unless you are adding support for new actions, the only class you
7 should care about in here is BulletML.
8 """
9
10 from __future__ import division
11
12 from math import sin, cos, radians, pi as PI
13
14 from xml.etree.ElementTree import ElementTree
15
16 # Python 3 moved this for no really good reason.
17 try:
18 from sys import intern
19 except ImportError:
20 pass
21
22 try:
23 from io import StringIO
24 except ImportError:
25 try:
26 from cStringIO import StringIO
27 except ImportError:
28 from StringIO import StringIO
29
30 from bulletml.errors import Error
31 from bulletml.expr import NumberDef, INumberDef
32
33
34 __all__ = ["ParseError", "BulletML"]
35
36 PI_2 = PI * 2
37
38 class ParseError(Error):
39 """Raised when an error occurs parsing the XML structure."""
40 pass
41
42 def realtag(element):
43 """Strip namespace poop off the front of a tag."""
44 try:
45 return element.tag.rsplit('}', 1)[1]
46 except ValueError:
47 return element.tag
48
49 class ParamList(object):
50 """List of parameter definitions."""
51
52 def __init__(self, params=()):
53 self.params = list(params)
54
55 @classmethod
56 def FromXML(cls, doc, element):
57 """Construct using an ElementTree-style element."""
58 return cls([NumberDef(subelem.text) for subelem in element
59 if realtag(subelem) == "param"])
60
61 def __call__(self, params, rank):
62 return [param(params, rank) for param in self.params]
63
64 def __repr__(self):
65 return "%s(%r)" % (type(self).__name__, self.params)
66
67 class Direction(object):
68 """Raw direction value."""
69
70 VALID_TYPES = ["relative", "absolute", "aim", "sequence"]
71
72 def __init__(self, type, value):
73 if type not in self.VALID_TYPES:
74 raise ValueError("invalid type %r" % type)
75 self.type = intern(type)
76 self.value = value
77
78 def __getstate__(self):
79 return [('type', self.type), ('value', self.value.expr)]
80
81 def __setstate__(self, state):
82 state = dict(state)
83 self.__init__(state["type"], NumberDef(state["value"]))
84
85 @classmethod
86 def FromXML(cls, doc, element, default="absolute"):
87 """Construct using an ElementTree-style element."""
88 return cls(element.get("type", default), NumberDef(element.text))
89
90 def __call__(self, params, rank):
91 return (radians(self.value(params, rank)), self.type)
92
93 def __repr__(self):
94 return "%s(%r, type=%r)" % (
95 type(self).__name__, self.value, self.type)
96
97 class ChangeDirection(object):
98 """Direction change over time."""
99
100 def __init__(self, term, direction):
101 self.term = term
102 self.direction = direction
103
104 def __getstate__(self):
105 return [('frames', self.term.expr),
106 ('type', self.direction.type),
107 ('value', self.direction.value.expr)]
108
109 def __setstate__(self, state):
110 state = dict(state)
111 self.__init__(INumberDef(state["frames"]),
112 Direction(state["type"], NumberDef(state["value"])))
113
114 @classmethod
115 def FromXML(cls, doc, element):
116 """Construct using an ElementTree-style element."""
117 for subelem in element.getchildren():
118 tag = realtag(subelem)
119 if tag == "direction":
120 direction = Direction.FromXML(doc, subelem)
121 elif tag == "term":
122 term = INumberDef(subelem.text)
123 try:
124 return cls(term, direction)
125 except UnboundLocalError as exc:
126 raise ParseError(str(exc))
127
128 def __call__(self, owner, action, params, rank, created):
129 frames = self.term(params, rank)
130 direction, type = self.direction(params, rank)
131 action.direction_frames = frames
132 action.aiming = False
133 if type == "sequence":
134 action.direction = direction
135 else:
136 if type == "absolute":
137 direction -= owner.direction
138 elif type != "relative": # aim or default
139 action.aiming = True
140 direction += owner.aim - owner.direction
141
142 # Normalize to [-pi, pi).
143 direction = (direction + PI) % PI_2 - PI
144 if frames <= 0:
145 owner.direction += direction
146 else:
147 action.direction = direction / frames
148
149 def __repr__(self):
150 return "%s(term=%r, direction=%r)" % (
151 type(self).__name__, self.term, self.direction)
152
153 class Speed(object):
154 """Raw speed value."""
155
156 VALID_TYPES = ["relative", "absolute", "sequence"]
157
158 def __init__(self, type, value):
159 if type not in self.VALID_TYPES:
160 raise ValueError("invalid type %r" % type)
161 self.type = intern(type)
162 self.value = value
163
164 def __getstate__(self):
165 return [('type', self.type), ('value', self.value.expr)]
166
167 def __setstate__(self, state):
168 state = dict(state)
169 self.__init__(state["type"], NumberDef(state["value"]))
170
171 @classmethod
172 def FromXML(cls, doc, element):
173 """Construct using an ElementTree-style element."""
174 return cls(element.get("type", "absolute"), NumberDef(element.text))
175
176 def __call__(self, params, rank):
177 return (self.value(params, rank), self.type)
178
179 def __repr__(self):
180 return "%s(%r, type=%r)" % (type(self).__name__, self.value, self.type)
181
182 class ChangeSpeed(object):
183 """Speed change over time."""
184
185 def __init__(self, term, speed):
186 self.term = term
187 self.speed = speed
188
189 def __getstate__(self):
190 return [('frames', self.term.expr),
191 ('type', self.speed.type),
192 ('value', self.speed.value.expr)]
193
194 def __setstate__(self, state):
195 state = dict(state)
196 self.__init__(INumberDef(state["frames"]),
197 Speed(state["type"], NumberDef(state["value"])))
198
199 @classmethod
200 def FromXML(cls, doc, element):
201 """Construct using an ElementTree-style element."""
202 for subelem in element.getchildren():
203 tag = realtag(subelem)
204 if tag == "speed":
205 speed = Speed.FromXML(doc, subelem)
206 elif tag == "term":
207 term = INumberDef(subelem.text)
208 try:
209 return cls(term, speed)
210 except UnboundLocalError as exc:
211 raise ParseError(str(exc))
212
213 def __call__(self, owner, action, params, rank, created):
214 frames = self.term(params, rank)
215 speed, type = self.speed(params, rank)
216 action.speed_frames = frames
217 if frames <= 0:
218 if type == "absolute":
219 owner.speed = speed
220 elif type == "relative":
221 owner.speed += speed
222 elif type == "sequence":
223 action.speed = speed
224 elif type == "relative":
225 action.speed = speed / frames
226 else:
227 action.speed = (speed - owner.speed) / frames
228
229 def __repr__(self):
230 return "%s(term=%r, speed=%r)" % (
231 type(self).__name__, self.term, self.speed)
232
233 class Wait(object):
234 """Wait for some frames."""
235
236 def __init__(self, frames):
237 self.frames = frames
238
239 def __getstate__(self):
240 return dict(frames=self.frames.expr)
241
242 def __setstate__(self, state):
243 self.__init__(INumberDef(state["frames"]))
244
245 @classmethod
246 def FromXML(cls, doc, element):
247 """Construct using an ElementTree-style element."""
248 return cls(INumberDef(element.text))
249
250 def __call__(self, owner, action, params, rank, created):
251 action.wait_frames = self.frames(params, rank)
252 return True
253
254 def __repr__(self):
255 return "%s(%r)" % (type(self).__name__, self.frames)
256
257 class Tag(object):
258 """Set a bullet tag."""
259
260 def __init__(self, tag):
261 self.tag = tag
262
263 def __getstate__(self):
264 return dict(tag=self.tag)
265
266 def __setstate__(self, state):
267 self.__init__(state["tag"])
268
269 @classmethod
270 def FromXML(cls, doc, element):
271 """Construct using an ElementTree-style element."""
272 return cls(element.text)
273
274 def __call__(self, owner, action, params, rank, created):
275 owner.tags.add(self.tag)
276
277 class Untag(object):
278 """Unset a bullet tag."""
279
280 def __init__(self, tag):
281 self.tag = tag
282
283 def __getstate__(self):
284 return dict(tag=self.tag)
285
286 def __setstate__(self, state):
287 self.__init__(state["tag"])
288
289 @classmethod
290 def FromXML(cls, doc, element):
291 """Construct using an ElementTree-style element."""
292 return cls(element.text)
293
294 def __call__(self, owner, action, params, rank, created):
295 try:
296 owner.tags.remove(self.tag)
297 except KeyError:
298 pass
299
300 class Appearance(object):
301 """Set a bullet appearance."""
302
303 def __init__(self, appearance):
304 self.appearance = appearance
305
306 def __getstate__(self):
307 return dict(appearance=self.appearance)
308
309 def __setstate__(self, state):
310 self.__init__(state["appearance"])
311
312 @classmethod
313 def FromXML(cls, doc, element):
314 """Construct using an ElementTree-style element."""
315 return cls(element.text)
316
317 def __call__(self, owner, action, params, rank, created):
318 owner.apearance = self.appearance
319
320 class Vanish(object):
321 """Make the owner disappear."""
322
323 def __init__(self):
324 pass
325
326 @classmethod
327 def FromXML(cls, doc, element):
328 """Construct using an ElementTree-style element."""
329 return cls()
330
331 def __repr__(self):
332 return "%s()" % (type(self).__name__)
333
334 def __call__(self, owner, action, params, rank, created):
335 owner.vanish()
336 return True
337
338 class Repeat(object):
339 """Repeat an action definition."""
340
341 def __init__(self, times, action):
342 self.times = times
343 self.action = action
344
345 def __getstate__(self):
346 return [('times', self.times.expr), ('action', self.action)]
347
348 def __setstate__(self, state):
349 state = dict(state)
350 self.__init__(INumberDef(state["times"]), state["action"])
351
352 @classmethod
353 def FromXML(cls, doc, element):
354 """Construct using an ElementTree-style element."""
355 for subelem in element.getchildren():
356 tag = realtag(subelem)
357 if tag == "times":
358 times = INumberDef(subelem.text)
359 elif tag == "action":
360 action = ActionDef.FromXML(doc, subelem)
361 elif tag == "actionRef":
362 action = ActionRef.FromXML(doc, subelem)
363 try:
364 return cls(times, action)
365 except UnboundLocalError as exc:
366 raise ParseError(str(exc))
367
368 def __call__(self, owner, action, params, rank, created):
369 repeat = self.times(params, rank)
370 child = action.Child(self.action, params, rank, repeat)
371 owner.replace(action, child)
372 child.step(owner, created)
373 return True
374
375 def __repr__(self):
376 return "%s(%r, %r)" % (type(self).__name__, self.times, self.action)
377
378 class If(object):
379 """Conditional actions."""
380
381 def __init__(self, cond, then, else_=None):
382 self.cond = cond
383 self.then = then
384 self.else_ = else_
385
386 def __getstate__(self):
387 if self.else_:
388 return [('cond', self.cond.expr),
389 ('then', self.then),
390 ('else', self.else_)]
391 else:
392 return [('cond', self.cond.expr), ('then', self.then)]
393
394 def __setstate__(self, state):
395 state = dict(state)
396 state["else_"] = state.pop("else", None)
397 state["cond"] = INumberDef(state["cond"])
398 self.__init__(**state)
399
400 @classmethod
401 def FromXML(cls, doc, element):
402 """Construct using an ElementTree-style element."""
403 else_ = None
404 for subelem in element.getchildren():
405 tag = realtag(subelem)
406 if tag == "cond":
407 cond = INumberDef(subelem.text)
408 elif tag == "then":
409 then = ActionDef.FromXML(doc, subelem)
410 elif tag == "else":
411 else_ = ActionDef.FromXML(doc, subelem)
412 try:
413 return cls(cond, then, else_)
414 except UnboundLocalError as exc:
415 raise ParseError(str(exc))
416
417 def __call__(self, owner, action, params, rank, created):
418 if self.cond(params, rank):
419 branch = self.then
420 else:
421 branch = self.else_
422
423 if branch:
424 child = action.Child(branch, params, rank)
425 owner.replace(action, child)
426 child.step(owner, created)
427 return True
428
429 def __repr__(self):
430 if self.else_:
431 return "%s(%r, then=%r, else_=%r)" % (
432 type(self).__name__, self.cond, self.then, self.else_)
433 else:
434 return "%s(%r, then=%r)" % (
435 type(self).__name__, self.cond, self.then)
436
437 class Accel(object):
438 """Accelerate over some time."""
439
440 horizontal = None
441 vertical = None
442
443 def __init__(self, term, horizontal=None, vertical=None):
444 self.term = term
445 self.horizontal = horizontal
446 self.vertical = vertical
447
448 def __getstate__(self):
449 state = [('frames', self.term.expr)]
450 if self.horizontal:
451 state.append(('horizontal', self.horizontal))
452 if self.vertical:
453 state.append(('vertical', self.vertical))
454 return state
455
456 def __setstate__(self, state):
457 state = dict(state)
458 self.__init__(INumberDef(state["frames"]), state.get("horizontal"),
459 state.get("vertical"))
460
461 @classmethod
462 def FromXML(cls, doc, element):
463 """Construct using an ElementTree-style element."""
464 horizontal = None
465 vertical = None
466
467 for subelem in element.getchildren():
468 tag = realtag(subelem)
469 if tag == "term":
470 term = INumberDef(subelem.text)
471 elif tag == "horizontal":
472 horizontal = Speed.FromXML(doc, subelem)
473 elif tag == "vertical":
474 vertical = Speed.FromXML(doc, subelem)
475
476 try:
477 return cls(term, horizontal, vertical)
478 except AttributeError:
479 raise ParseError
480
481 def __call__(self, owner, action, params, rank, created):
482 frames = self.term(params, rank)
483 horizontal = self.horizontal and self.horizontal(params, rank)
484 vertical = self.vertical and self.vertical(params, rank)
485 action.accel_frames = frames
486 if horizontal:
487 mx, type = horizontal
488 if frames <= 0:
489 if type == "absolute":
490 owner.mx = mx
491 elif type == "relative":
492 owner.mx += mx
493 elif type == "sequence":
494 action.mx = mx
495 elif type == "absolute":
496 action.mx = (mx - owner.mx) / frames
497 elif type == "relative":
498 action.mx = mx / frames
499 if vertical:
500 my, type = vertical
501 if frames <= 0:
502 if type == "absolute":
503 owner.my = my
504 elif type == "relative":
505 owner.my += my
506 elif type == "sequence":
507 action.my = my
508 elif type == "absolute":
509 action.my = (my - owner.my) / frames
510 elif type == "relative":
511 action.my = my / frames
512
513 def __repr__(self):
514 return "%s(%r, horizontal=%r, vertical=%r)" % (
515 type(self).__name__, self.term, self.horizontal, self.vertical)
516
517 class BulletDef(object):
518 """Bullet definition."""
519
520 def __init__(self, actions=(), direction=None, speed=None, tags=(),
521 appearance=None):
522 self.direction = direction
523 self.speed = speed
524 self.actions = list(actions)
525 self.tags = set(tags)
526 self.appearance = appearance
527
528 def __getstate__(self):
529 state = []
530 if self.direction:
531 state.append(("direction", self.direction))
532 if self.speed:
533 state.append(("speed", self.speed))
534 if self.actions:
535 state.append(("actions", self.actions))
536 if self.tags:
537 state.append(("tags", list(self.tags)))
538 if self.appearance:
539 state.append(("appearance", self.appearance))
540 return state
541
542 def __setstate__(self, state):
543 state = dict(state)
544 self.__init__(**state)
545
546 @classmethod
547 def FromXML(cls, doc, element):
548 """Construct using an ElementTree-style element."""
549 actions = []
550 speed = None
551 direction = None
552 tags = set()
553 for subelem in element.getchildren():
554 tag = realtag(subelem)
555 if tag == "direction":
556 direction = Direction.FromXML(doc, subelem)
557 elif tag == "speed":
558 speed = Speed.FromXML(doc, subelem)
559 elif tag == "action":
560 actions.append(ActionDef.FromXML(doc, subelem))
561 elif tag == "actionRef":
562 actions.append(ActionRef.FromXML(doc, subelem))
563 elif tag == "tag":
564 tags.add(subelem.text)
565 dfn = cls(actions, direction, speed, tags)
566 doc._bullets[element.get("label")] = dfn
567 return dfn
568
569 def __call__(self, params, rank):
570 actions = [action(params, rank) for action in self.actions]
571 return (
572 self.direction and self.direction(params, rank),
573 self.speed and self.speed(params, rank),
574 self.tags,
575 self.appearance,
576 actions)
577
578 def __repr__(self):
579 return "%s(direction=%r, speed=%r, actions=%r)" % (
580 type(self).__name__, self.direction, self.speed, self.actions)
581
582 class BulletRef(object):
583 """Create a bullet by name with parameters."""
584
585 def __init__(self, bullet, params=None):
586 self.bullet = bullet
587 self.params = ParamList() if params is None else params
588
589 def __getstate__(self):
590 state = []
591 if self.params.params:
592 params = [param.expr for param in self.params.params]
593 state.append(("params", params))
594 state.append(('bullet', self.bullet))
595 return state
596
597 def __setstate__(self, state):
598 state = dict(state)
599 bullet = state["bullet"]
600 params = [NumberDef(param) for param in state.get("params", [])]
601 self.__init__(bullet, ParamList(params))
602
603 @classmethod
604 def FromXML(cls, doc, element):
605 """Construct using an ElementTree-style element."""
606 bullet = cls(element.get("label"), ParamList.FromXML(doc, element))
607 doc._bullet_refs.append(bullet)
608 return bullet
609
610 def __call__(self, params, rank):
611 return self.bullet(self.params(params, rank), rank)
612
613 def __repr__(self):
614 return "%s(params=%r, bullet=%r)" % (
615 type(self).__name__, self.params, self.bullet)
616
617 class ActionDef(object):
618 """Action definition.
619
620 To support parsing new actions, add tags to
621 ActionDef.CONSTRUCTORS. It maps tag names to classes with a
622 FromXML classmethod, which take the BulletML instance and
623 ElementTree element as arguments.
624 """
625
626 # This is self-referential, so it's filled in later.
627 CONSTRUCTORS = dict()
628
629 def __init__(self, actions):
630 self.actions = list(actions)
631
632 def __getstate__(self):
633 return dict(actions=self.actions)
634
635 def __setstate__(self, state):
636 state = dict(state)
637 self.__init__(state["actions"])
638
639 @classmethod
640 def FromXML(cls, doc, element):
641 """Construct using an ElementTree-style element."""
642 actions = []
643 for subelem in element.getchildren():
644 tag = realtag(subelem)
645 try:
646 ctr = cls.CONSTRUCTORS[tag]
647 except KeyError:
648 continue
649 else:
650 actions.append(ctr.FromXML(doc, subelem))
651 dfn = cls(actions)
652 doc._actions[element.get("label")] = dfn
653 return dfn
654
655 def __call__(self, params, rank):
656 return self.actions, params
657
658 def __repr__(self):
659 return "%s(%r)" % (type(self).__name__, self.actions)
660
661 class ActionRef(object):
662 """Run an action by name with parameters."""
663
664 def __init__(self, action, params=None):
665 self.action = action
666 self.params = params or ParamList()
667
668 def __getstate__(self):
669 state = []
670 if self.params.params:
671 params = [param.expr for param in self.params.params]
672 state.append(("params", params))
673 state.append(('action', self.action))
674 return state
675
676 def __setstate__(self, state):
677 state = dict(state)
678 action = state["action"]
679 params = [NumberDef(param) for param in state.get("params", [])]
680 self.__init__(action, ParamList(params))
681
682 @classmethod
683 def FromXML(cls, doc, element):
684 """Construct using an ElementTree-style element."""
685 action = cls(element.get("label"), ParamList.FromXML(doc, element))
686 doc._action_refs.append(action)
687 return action
688
689 def __call__(self, params, rank):
690 return self.action(self.params(params, rank), rank)
691
692 def __repr__(self):
693 return "%s(params=%r, action=%r)" % (
694 type(self).__name__, self.params, self.action)
695
696 class Offset(object):
697 """Provide an offset to a bullet's initial position."""
698
699 VALID_TYPES = ["relative", "absolute"]
700
701 def __init__(self, type, x, y):
702 if type not in self.VALID_TYPES:
703 raise ValueError("invalid type %r" % type)
704 self.type = intern(type)
705 self.x = x
706 self.y = y
707
708 def __getstate__(self):
709 state = [('type', self.type)]
710 if self.x:
711 state.append(('x', self.x.expr))
712 if self.y:
713 state.append(('y', self.y.expr))
714 return state
715
716 def __setstate__(self, state):
717 state = dict(state)
718 x = NumberDef(state["x"]) if "x" in state else None
719 y = NumberDef(state["y"]) if "y" in state else None
720 self.__init__(state["type"], x, y)
721
722 @classmethod
723 def FromXML(cls, doc, element):
724 """Construct using an ElementTree-style element."""
725 type = element.get("type", "relative")
726 x = None
727 y = None
728 for subelem in element:
729 tag = realtag(subelem)
730 if tag == "x":
731 x = NumberDef(subelem.text)
732 elif tag == "y":
733 y = NumberDef(subelem.text)
734 return cls(type, x, y)
735
736 def __call__(self, params, rank):
737 return (self.x(params, rank) if self.x else 0,
738 self.y(params, rank) if self.y else 0)
739
740 class FireDef(object):
741 """Fire definition (creates a bullet)."""
742
743 def __init__(self, bullet, direction=None, speed=None, offset=None,
744 tags=(), appearance=None):
745 self.bullet = bullet
746 self.direction = direction
747 self.speed = speed
748 self.offset = offset
749 self.tags = set(tags)
750 self.appearance = appearance
751
752 def __getstate__(self):
753 state = []
754 if self.direction:
755 state.append(("direction", self.direction))
756 if self.speed:
757 state.append(("speed", self.speed))
758 if self.offset:
759 state.append(("offset", self.offset))
760 if self.tags:
761 state.append(("tags", list(self.tags)))
762 if self.appearance:
763 state.append(("appearance", self.appearance))
764 try:
765 params = self.bullet.params
766 except AttributeError:
767 state.append(('bullet', self.bullet))
768 else:
769 if params.params:
770 state.append(('bullet', self.bullet))
771 else:
772 # Strip out empty BulletRefs.
773 state.append(('bullet', self.bullet.bullet))
774 return state
775
776 def __setstate__(self, state):
777 state = dict(state)
778 self.__init__(**state)
779
780 @classmethod
781 def FromXML(cls, doc, element):
782 """Construct using an ElementTree-style element."""
783 direction = None
784 speed = None
785 offset = None
786 tags = set()
787 appearance = None
788
789 for subelem in element.getchildren():
790 tag = realtag(subelem)
791 if tag == "direction":
792 direction = Direction.FromXML(doc, subelem, "aim")
793 elif tag == "speed":
794 speed = Speed.FromXML(doc, subelem)
795 elif tag == "bullet":
796 bullet = BulletDef.FromXML(doc, subelem)
797 elif tag == "bulletRef":
798 bullet = BulletRef.FromXML(doc, subelem)
799 elif tag == "offset":
800 offset = Offset.FromXML(doc, subelem)
801 elif tag == "tag":
802 tags.add(subelem.text)
803 elif tag == "appearance":
804 appearance = subelem.text
805 try:
806 fire = cls(bullet, direction, speed, offset, tags, appearance)
807 except UnboundLocalError as exc:
808 raise ParseError(str(exc))
809 else:
810 doc._fires[element.get("label")] = fire
811 return fire
812
813 def __call__(self, owner, action, params, rank, created):
814 direction, speed, tags, appearance, actions = self.bullet(params, rank)
815 if self.direction:
816 direction = self.direction(params, rank)
817 if self.speed:
818 speed = self.speed(params, rank)
819 tags = tags.union(self.tags)
820 if self.appearance:
821 appearance = self.appearance
822
823 if direction:
824 direction, type = direction
825 if type == "aim" or type is None:
826 direction += owner.aim
827 elif type == "sequence":
828 direction += action.previous_fire_direction
829 elif type == "relative":
830 direction += owner.direction
831 else:
832 direction = owner.aim
833 action.previous_fire_direction = direction
834
835 if speed:
836 speed, type = speed
837 if type == "sequence":
838 speed += action.previous_fire_speed
839 elif type == "relative":
840 # The reference Noiz implementation uses
841 # prvFireSpeed here, but the standard is
842 # pretty clear -- "In case of the type is
843 # "relative", ... the speed is relative to the
844 # speed of this bullet."
845 speed += owner.speed
846 else:
847 speed = 1
848 action.previous_fire_speed = speed
849
850 x, y = owner.x, owner.y
851 if self.offset:
852 off_x, off_y = self.offset(params, rank)
853 if self.offset.type == "relative":
854 s = sin(direction)
855 c = cos(direction)
856 x += c * off_x + s * off_y
857 y += s * off_x - c * off_y
858 else:
859 x += off_x
860 y += off_y
861
862 if appearance is None:
863 appearance = owner.appearance
864 bullet = owner.__class__(
865 x=x, y=y, direction=direction, speed=speed,
866 target=owner.target, actions=actions, rank=rank,
867 appearance=appearance, tags=tags, Action=action.__class__)
868 created.append(bullet)
869
870 def __repr__(self):
871 return "%s(direction=%r, speed=%r, bullet=%r)" % (
872 type(self).__name__, self.direction, self.speed, self.bullet)
873
874 class FireRef(object):
875 """Fire a bullet by name with parameters."""
876
877 def __init__(self, fire, params=None):
878 self.fire = fire
879 self.params = params or ParamList()
880
881 def __getstate__(self):
882 state = []
883 if self.params.params:
884 params = [param.expr for param in self.params.params]
885 state.append(("params", params))
886 state.append(('fire', self.fire))
887 return state
888
889 def __setstate__(self, state):
890 state = dict(state)
891 fire = state["fire"]
892 params = [NumberDef(param) for param in state.get("params", [])]
893 self.__init__(fire, ParamList(params))
894
895 @classmethod
896 def FromXML(cls, doc, element):
897 """Construct using an ElementTree-style element."""
898 fired = cls(element.get("label"), ParamList.FromXML(doc, element))
899 doc._fire_refs.append(fired)
900 return fired
901
902 def __call__(self, owner, action, params, rank, created):
903 params = self.params(params, rank)
904 return self.fire(owner, action, params, rank, created)
905
906 def __repr__(self):
907 return "%s(params=%r, fire=%r)" % (
908 type(self).__name__, self.params, self.fire)
909
910 class BulletML(object):
911 """BulletML document.
912
913 A BulletML document is a collection of top-level actions and the
914 base game type.
915
916 You can add tags to the BulletML.CONSTRUCTORS dictionary to extend
917 its parsing. It maps tag names to classes with a FromXML
918 classmethod, which take the BulletML instance and ElementTree
919 element as arguments.
920
921 """
922
923 CONSTRUCTORS = dict(
924 bullet=BulletDef,
925 action=ActionDef,
926 fire=FireDef,
927 )
928
929 def __init__(self, type="none", actions=None):
930 self.type = intern(type)
931 self.actions = [] if actions is None else actions
932
933 def __getstate__(self):
934 return [('type', self.type), ('actions', self.actions)]
935
936 def __setstate__(self, state):
937 state = dict(state)
938 self.__init__(state["type"], actions=state.get("actions"))
939
940 @classmethod
941 def FromXML(cls, source):
942 """Return a BulletML instance based on XML."""
943 if not hasattr(source, 'read'):
944 source = StringIO(source)
945
946 tree = ElementTree()
947 root = tree.parse(source)
948
949 doc = cls(type=root.get("type", "none"))
950
951 doc._bullets = {}
952 doc._actions = {}
953 doc._fires = {}
954 doc._bullet_refs = []
955 doc._action_refs = []
956 doc._fire_refs = []
957
958 for element in root.getchildren():
959 tag = realtag(element)
960 if tag in doc.CONSTRUCTORS:
961 doc.CONSTRUCTORS[tag].FromXML(doc, element)
962
963 try:
964 for ref in doc._bullet_refs:
965 ref.bullet = doc._bullets[ref.bullet]
966 for ref in doc._fire_refs:
967 ref.fire = doc._fires[ref.fire]
968 for ref in doc._action_refs:
969 ref.action = doc._actions[ref.action]
970 except KeyError as exc:
971 raise ParseError("unknown reference %s" % exc)
972
973 doc.actions = [act for name, act in doc._actions.items()
974 if name and name.startswith("top")]
975
976 del(doc._bullet_refs)
977 del(doc._action_refs)
978 del(doc._fire_refs)
979 del(doc._bullets)
980 del(doc._actions)
981 del(doc._fires)
982
983 return doc
984
985 @classmethod
986 def FromYAML(cls, source):
987 """Create a BulletML instance based on YAML."""
988
989 # Late import to avoid a circular dependency.
990 try:
991 import bulletml.bulletyaml
992 import yaml
993 except ImportError:
994 raise ParseError("PyYAML is not available")
995 else:
996 try:
997 return yaml.load(source)
998 except Exception as exc:
999 raise ParseError(str(exc))
1000
1001 @classmethod
1002 def FromDocument(cls, source):
1003 """Create a BulletML instance based on a seekable file or string.
1004
1005 This attempts to autodetect if the stream is XML or YAML.
1006 """
1007 if not hasattr(source, 'read'):
1008 source = StringIO(source)
1009 start = source.read(1)
1010 source.seek(0)
1011 if start == "<":
1012 return cls.FromXML(source)
1013 elif start == "!" or start == "#":
1014 return cls.FromYAML(source)
1015 else:
1016 raise ParseError("unknown initial character %r" % start)
1017
1018 def __repr__(self):
1019 return "%s(type=%r, actions=%r)" % (
1020 type(self).__name__, self.type, self.actions)
1021
1022 ActionDef.CONSTRUCTORS = dict(
1023 repeat=Repeat,
1024 fire=FireDef,
1025 fireRef=FireRef,
1026 changeSpeed=ChangeSpeed,
1027 changeDirection=ChangeDirection,
1028 accel=Accel,
1029 wait=Wait,
1030 vanish=Vanish,
1031 tag=Tag,
1032 appearance=Appearance,
1033 untag=Untag,
1034 action=ActionDef,
1035 actionRef=ActionRef)
1036 ActionDef.CONSTRUCTORS["if"] = If