161a693e05f92f5126a8145e1f19dc7910add907
[supertux.git] / src / trigger / scripttrigger.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <config.h>
21
22 #include <sstream>
23 #include <stdexcept>
24 #include <memory>
25
26 #include "scripttrigger.hpp"
27 #include "game_session.hpp"
28 #include "lisp/lisp.hpp"
29 #include "lisp/writer.hpp"
30 #include "object_factory.hpp"
31 #include "sector.hpp"
32
33 ScriptTrigger::ScriptTrigger(const lisp::Lisp& reader)
34 {
35   bool must_activate = false;
36
37   reader.get("x", bbox.p1.x);
38   reader.get("y", bbox.p1.y);
39   float w = 0, h = 0;
40   reader.get("width", w);
41   reader.get("height", h);
42   bbox.set_size(w, h);
43   reader.get("script", script);
44   reader.get("button", must_activate);
45   if(script == "") {
46     throw std::runtime_error("Need to specify a script for trigger object");
47   }
48
49   if (must_activate)
50     triggerevent = EVENT_ACTIVATE;
51   else
52     triggerevent = EVENT_TOUCH;
53 }
54
55 ScriptTrigger::ScriptTrigger(const Vector& pos, const std::string& script)
56 {
57   bbox.set_pos(pos);
58   bbox.set_size(32, 32);
59   this->script = script;
60   triggerevent = EVENT_TOUCH;
61 }
62
63 ScriptTrigger::~ScriptTrigger()
64 {
65 }
66
67 void
68 ScriptTrigger::write(lisp::Writer& writer)
69 {
70   writer.start_list("scripttrigger");
71
72   writer.write("x", bbox.p1.x);
73   writer.write("y", bbox.p1.y);
74   writer.write("width", bbox.get_width());
75   writer.write("height", bbox.get_height());
76   writer.write("script", script);
77   writer.write("button", triggerevent == EVENT_ACTIVATE);
78
79   writer.end_list("scripttrigger");
80 }
81
82 void
83 ScriptTrigger::event(Player& , EventType type)
84 {
85   if(type != triggerevent)
86     return;
87
88   std::istringstream stream(script);
89   Sector::current()->run_script(stream, "ScriptTrigger");
90 }
91
92 IMPLEMENT_FACTORY(ScriptTrigger, "scripttrigger");