c1b7af0a16d660d379286dc7c07a4a664c162a24
[supertux.git] / src / scripting / script_interpreter.hpp
1 #ifndef __SCRIPT_INTERPRETER_H__
2 #define __SCRIPT_INTERPRETER_H__
3
4 #include <squirrel.h>
5 #include <iostream>
6 #include <sstream>
7 #include <string>
8 #include "timer.hpp"
9 #include "game_object.hpp"
10 #include "scripting/wrapper.hpp"
11 #include "scripting/wrapper_util.hpp"
12 #include "scripting/sound.hpp"
13 #include "scripting/level.hpp"
14
15 class Sector;
16
17 class ScriptInterpreter : public GameObject
18 {
19 public:
20   ScriptInterpreter(const std::string& working_dir);
21   ~ScriptInterpreter();
22
23   void register_sector(Sector* sector);
24
25   void draw(DrawingContext& );
26   void update(float );
27
28   void run_script(std::istream& in, const std::string& sourcename = "",
29           bool remove_when_terminated = true);
30
31   template<typename T>
32   void expose_object(T* object, const std::string& name, bool free = false)
33   {
34     sq_pushroottable(v);
35     sq_pushstring(v, name.c_str(), -1);
36
37     sq_pushroottable(v);
38     SquirrelWrapper::create_squirrel_instance(v, object, free);
39     sq_remove(v, -2);
40                         
41     // register instance in root table
42     if(sq_createslot(v, -3) < 0) {
43       std::ostringstream msg;
44       msg << "Couldn't register object '" << name << "' in squirrel root table";
45       throw SquirrelError(v, msg.str());
46     }
47     
48     sq_pop(v, 1);
49   }
50
51   void set_wakeup_time(float seconds);
52
53   /** helper function that parses a script, starts it and adds it to the sector
54    * specified
55    */
56   static void add_script_object(Sector* sector, const std::string& scriptname,
57       const std::string& script);
58
59   static ScriptInterpreter* current()
60   {
61     return _current;
62   }
63
64   const std::string& get_working_directory() const
65   {
66       return working_directory;
67   }
68
69 private:
70   HSQUIRRELVM v;
71   static ScriptInterpreter* _current;
72   Timer wakeup_timer;
73
74   /// this directory is used as base for all filenames used in scripts
75   std::string working_directory;
76   Scripting::Sound* sound;
77   Scripting::Level* level;
78 };
79
80 #endif
81