Merge branch 'feature/menu-cleanup'
[supertux.git] / src / supertux / world.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include <algorithm>
18
19 #include "lisp/parser.hpp"
20 #include "lisp/writer.hpp"
21 #include "physfs/ifile_streambuf.hpp"
22 #include "scripting/serialize.hpp"
23 #include "scripting/squirrel_util.hpp"
24 #include "supertux/globals.hpp"
25 #include "supertux/screen_fade.hpp"
26 #include "supertux/screen_manager.hpp"
27 #include "supertux/player_status.hpp"
28 #include "supertux/world.hpp"
29 #include "util/file_system.hpp"
30 #include "util/reader.hpp"
31 #include "util/string_util.hpp"
32 #include "worldmap/worldmap.hpp"
33
34 World* World::current_ = NULL;
35
36 World::World() :
37   worldname(),
38   levels(),
39   basedir(),
40   savegame_filename(),
41   state_table(),
42   world_thread(),
43   title(),
44   description(),
45   player_status(),
46   hide_from_contribs(),
47   is_levelset()
48 {
49   player_status.reset(new PlayerStatus());
50
51   is_levelset = true;
52   hide_from_contribs = false;
53   sq_resetobject(&world_thread);
54 }
55
56 World::~World()
57 {
58   sq_release(scripting::global_vm, &world_thread);
59   if(current_ == this)
60     current_ = NULL;
61 }
62
63 void
64 World::set_savegame_filename(const std::string& filename)
65 {
66   this->savegame_filename = filename;
67   // make sure the savegame directory exists
68   std::string dirname = FileSystem::dirname(filename);
69   if(!PHYSFS_exists(dirname.c_str())) {
70     if(!PHYSFS_mkdir(dirname.c_str())) {
71       std::ostringstream msg;
72       msg << "Couldn't create directory for savegames '"
73           << dirname << "': " <<PHYSFS_getLastError();
74       throw std::runtime_error(msg.str());
75     }
76   }
77
78   if(!PHYSFS_isDirectory(dirname.c_str())) {
79     std::ostringstream msg;
80     msg << "Savegame path '" << dirname << "' is not a directory";
81     throw std::runtime_error(msg.str());
82   }
83 }
84
85 void
86 World::load(const std::string& filename)
87 {
88   basedir = FileSystem::dirname(filename);
89   worldname = basedir + "worldmap.stwm";
90
91   lisp::Parser parser;
92   const lisp::Lisp* root = parser.parse(filename);
93
94   const lisp::Lisp* info = root->get_lisp("supertux-world");
95   if(info == NULL)
96     info = root->get_lisp("supertux-level-subset");
97   if(info == NULL)
98     throw std::runtime_error("File is not a world or levelsubset file");
99
100   hide_from_contribs = false;
101   is_levelset = true;
102
103   info->get("title", title);
104   info->get("description", description);
105   info->get("levelset", is_levelset);
106   info->get("hide-from-contribs", hide_from_contribs);
107
108   // Level info file doesn't define any levels, so read the
109   // directory to see what we can find
110
111   std::string path = basedir;
112   char** files = PHYSFS_enumerateFiles(path.c_str());
113   if(!files) {
114     log_warning << "Couldn't read subset dir '" << path << "'" << std::endl;
115     return;
116   }
117
118   for(const char* const* filename = files; *filename != 0; ++filename) {
119     if(StringUtil::has_suffix(*filename, ".stl")) {
120       Level level;
121       level.fullpath = path + *filename;
122       level.name = *filename;
123       levels.push_back(level);
124     }
125   }
126   PHYSFS_freeList(files);
127
128   std::sort(levels.begin(), levels.end(),
129             [](const Level& lhs, const Level& rhs)
130             {
131               return StringUtil::numeric_less(lhs.fullpath, rhs.fullpath);
132             });
133 }
134
135 void
136 World::run()
137 {
138   current_ = this;
139
140   // create new squirrel table for persistent game state
141   HSQUIRRELVM vm = scripting::global_vm;
142
143   sq_pushroottable(vm);
144   sq_pushstring(vm, "state", -1);
145   sq_newtable(vm);
146   if(SQ_FAILED(sq_createslot(vm, -3)))
147     throw scripting::SquirrelError(vm, "Couldn't create state table");
148   sq_pop(vm, 1);
149
150   load_state();
151
152   std::string filename = basedir + "/world.nut";
153   try {
154     IFileStreambuf ins(filename);
155     std::istream in(&ins);
156
157     sq_release(scripting::global_vm, &world_thread);
158     world_thread = scripting::create_thread(scripting::global_vm);
159     scripting::compile_and_run(scripting::object_to_vm(world_thread), in, filename);
160   } catch(std::exception& ) {
161     // fallback: try to load worldmap worldmap.stwm
162     using namespace worldmap;
163     g_screen_manager->push_screen(std::unique_ptr<Screen>(new WorldMap(basedir + "worldmap.stwm", get_player_status())));
164   }
165 }
166
167 void
168 World::save_state()
169 {
170   using namespace scripting;
171
172   lisp::Writer writer(savegame_filename);
173
174   writer.start_list("supertux-savegame");
175   writer.write("version", 1);
176
177   using namespace worldmap;
178   if(WorldMap::current() != NULL) {
179     std::ostringstream title;
180     title << WorldMap::current()->get_title();
181     title << " (" << WorldMap::current()->solved_level_count()
182           << "/" << WorldMap::current()->level_count() << ")";
183     writer.write("title", title.str());
184   }
185
186   writer.start_list("tux");
187   player_status->write(writer);
188   writer.end_list("tux");
189
190   writer.start_list("state");
191
192   sq_pushroottable(global_vm);
193   sq_pushstring(global_vm, "state", -1);
194   if(SQ_SUCCEEDED(sq_get(global_vm, -2))) {
195     scripting::save_squirrel_table(global_vm, -1, writer);
196     sq_pop(global_vm, 1);
197   }
198   sq_pop(global_vm, 1);
199   writer.end_list("state");
200
201   writer.end_list("supertux-savegame");
202 }
203
204 void
205 World::load_state()
206 {
207   using namespace scripting;
208
209   if(!PHYSFS_exists(savegame_filename.c_str()))
210   {
211     log_info << savegame_filename << ": doesn't exist, not loading state" << std::endl;
212   }
213   else
214   {
215     try {
216       lisp::Parser parser;
217       const lisp::Lisp* root = parser.parse(savegame_filename);
218
219       const lisp::Lisp* lisp = root->get_lisp("supertux-savegame");
220       if(lisp == NULL)
221         throw std::runtime_error("file is not a supertux-savegame file");
222
223       int version = 1;
224       lisp->get("version", version);
225       if(version != 1)
226         throw std::runtime_error("incompatible savegame version");
227
228       const lisp::Lisp* tux = lisp->get_lisp("tux");
229       if(tux == NULL)
230         throw std::runtime_error("No tux section in savegame");
231       player_status->read(*tux);
232
233       const lisp::Lisp* state = lisp->get_lisp("state");
234       if(state == NULL)
235         throw std::runtime_error("No state section in savegame");
236
237       sq_pushroottable(global_vm);
238       sq_pushstring(global_vm, "state", -1);
239       if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
240         sq_pop(global_vm, 1);
241
242       sq_pushstring(global_vm, "state", -1);
243       sq_newtable(global_vm);
244       load_squirrel_table(global_vm, -1, *state);
245       if(SQ_FAILED(sq_createslot(global_vm, -3)))
246         throw std::runtime_error("Couldn't create state table");
247       sq_pop(global_vm, 1);
248     } catch(std::exception& e) {
249       log_fatal << "Couldn't load savegame: " << e.what() << std::endl;
250     }
251   }
252 }
253
254 const std::string&
255 World::get_level_filename(unsigned int i) const
256 {
257   return levels[i].fullpath;
258 }
259
260 unsigned int
261 World::get_num_levels() const
262 {
263   return levels.size();
264 }
265
266 int
267 World::get_num_solved_levels() const
268 {
269   int num_solved_levels = 0;
270
271   HSQUIRRELVM vm = scripting::global_vm;
272   int oldtop = sq_gettop(vm);
273
274   sq_pushroottable(vm);
275   sq_pushstring(vm, "state", -1);
276   if(SQ_FAILED(sq_get(vm, -2)))
277   {
278     log_warning << "failed to get 'state' table" << std::endl;
279   }
280   else
281   {
282     sq_pushstring(vm, "worlds", -1);
283     if(SQ_FAILED(sq_get(vm, -2)))
284     {
285       log_warning << "failed to get 'state.worlds' table" << std::endl;
286     }
287     else
288     {
289       sq_pushstring(vm, worldname.c_str(), -1);
290       if(SQ_FAILED(sq_get(vm, -2)))
291       {
292         log_warning << "failed to get state.worlds['" << worldname << "']" << std::endl;
293       }
294       else
295       {
296         sq_pushstring(vm, "levels", -1);
297         if(SQ_FAILED(sq_get(vm, -2)))
298         {
299           log_warning << "failed to get state.worlds['" << worldname << "'].levels" << std::endl;
300         }
301         else
302         {
303           for(auto level : levels)
304           {
305             sq_pushstring(vm, level.name.c_str(), -1);
306             if(SQ_FAILED(sq_get(vm, -2)))
307             {
308               log_warning << "failed to get state.worlds['" << worldname << "'].levels['"
309                           << level.name << "']" << std::endl;
310             }
311             else
312             {
313               bool solved = scripting::read_bool(vm, "solved");
314               if (solved)
315               {
316                 num_solved_levels += 1;
317               }
318               sq_pop(vm, 1);
319             }
320           }
321         }
322       }
323     }
324   }
325
326   sq_settop(vm, oldtop);
327
328   return num_solved_levels;
329 }
330
331 const std::string&
332 World::get_basedir() const
333 {
334   return basedir;
335 }
336
337 const std::string&
338 World::get_title() const
339 {
340   return title;
341 }
342
343 /* EOF */