Moved World loading into a factory method World::load()
[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 std::unique_ptr<World>
35 World::load(const std::string& filename)
36 {
37   std::unique_ptr<World> world(new World);
38   world->load_(filename);
39   return std::move(world);
40 }
41
42 World::World() :
43   m_worldmap_filename(),
44   m_levels(),
45   m_basedir(),
46   m_savegame_filename(),
47   m_world_thread(),
48   m_title(),
49   m_description(),
50   m_player_status(new PlayerStatus),
51   m_hide_from_contribs(false),
52   m_is_levelset(true)
53 {
54   sq_resetobject(&m_world_thread);
55 }
56
57 World::~World()
58 {
59   sq_release(scripting::global_vm, &m_world_thread);
60 }
61
62 void
63 World::set_savegame_filename(const std::string& filename)
64 {
65   m_savegame_filename = filename;
66   // make sure the savegame directory exists
67   std::string dirname = FileSystem::dirname(filename);
68   if(!PHYSFS_exists(dirname.c_str())) {
69     if(!PHYSFS_mkdir(dirname.c_str())) {
70       std::ostringstream msg;
71       msg << "Couldn't create directory for savegames '"
72           << dirname << "': " <<PHYSFS_getLastError();
73       throw std::runtime_error(msg.str());
74     }
75   }
76
77   if(!PHYSFS_isDirectory(dirname.c_str())) {
78     std::ostringstream msg;
79     msg << "Savegame path '" << dirname << "' is not a directory";
80     throw std::runtime_error(msg.str());
81   }
82 }
83
84 void
85 World::load_(const std::string& filename)
86 {
87   m_basedir = FileSystem::dirname(filename);
88   m_worldmap_filename = m_basedir + "worldmap.stwm";
89
90   lisp::Parser parser;
91   const lisp::Lisp* root = parser.parse(filename);
92
93   const lisp::Lisp* info = root->get_lisp("supertux-world");
94   if(info == NULL)
95     info = root->get_lisp("supertux-level-subset");
96   if(info == NULL)
97     throw std::runtime_error("File is not a world or levelsubset file");
98
99   m_hide_from_contribs = false;
100   m_is_levelset = true;
101
102   info->get("title", m_title);
103   info->get("description", m_description);
104   info->get("levelset", m_is_levelset);
105   info->get("hide-from-contribs", m_hide_from_contribs);
106
107   // Level info file doesn't define any levels, so read the
108   // directory to see what we can find
109
110   std::string path = m_basedir;
111   char** files = PHYSFS_enumerateFiles(path.c_str());
112   if(!files) {
113     log_warning << "Couldn't read subset dir '" << path << "'" << std::endl;
114     return;
115   }
116
117   for(const char* const* filename = files; *filename != 0; ++filename) {
118     if(StringUtil::has_suffix(*filename, ".stl")) {
119       Level level;
120       level.fullpath = path + *filename;
121       level.name = *filename;
122       m_levels.push_back(level);
123     }
124   }
125   PHYSFS_freeList(files);
126
127   std::sort(m_levels.begin(), m_levels.end(),
128             [](const Level& lhs, const Level& rhs)
129             {
130               return StringUtil::numeric_less(lhs.fullpath, rhs.fullpath);
131             });
132 }
133
134 void
135 World::run()
136 {
137   // create new squirrel table for persistent game state
138   HSQUIRRELVM vm = scripting::global_vm;
139
140   sq_pushroottable(vm);
141   sq_pushstring(vm, "state", -1);
142   sq_newtable(vm);
143   if(SQ_FAILED(sq_createslot(vm, -3)))
144     throw scripting::SquirrelError(vm, "Couldn't create state table");
145   sq_pop(vm, 1);
146
147   load_state();
148
149   std::string filename = m_basedir + "/world.nut";
150   try {
151     IFileStreambuf ins(filename);
152     std::istream in(&ins);
153
154     sq_release(scripting::global_vm, &m_world_thread);
155     m_world_thread = scripting::create_thread(scripting::global_vm);
156     scripting::compile_and_run(scripting::object_to_vm(m_world_thread), in, filename);
157   } catch(std::exception& ) {
158     // fallback: try to load worldmap worldmap.stwm
159     using namespace worldmap;
160     g_screen_manager->push_screen(std::unique_ptr<Screen>(new WorldMap(m_basedir + "worldmap.stwm", get_player_status())));
161   }
162 }
163
164 void
165 World::save_state()
166 {
167   using namespace scripting;
168
169   lisp::Writer writer(m_savegame_filename);
170
171   writer.start_list("supertux-savegame");
172   writer.write("version", 1);
173
174   using namespace worldmap;
175   if(WorldMap::current() != NULL) {
176     std::ostringstream title;
177     title << WorldMap::current()->get_title();
178     title << " (" << WorldMap::current()->solved_level_count()
179           << "/" << WorldMap::current()->level_count() << ")";
180     writer.write("title", title.str());
181   }
182
183   writer.start_list("tux");
184   m_player_status->write(writer);
185   writer.end_list("tux");
186
187   writer.start_list("state");
188
189   sq_pushroottable(global_vm);
190   sq_pushstring(global_vm, "state", -1);
191   if(SQ_SUCCEEDED(sq_get(global_vm, -2))) {
192     scripting::save_squirrel_table(global_vm, -1, writer);
193     sq_pop(global_vm, 1);
194   }
195   sq_pop(global_vm, 1);
196   writer.end_list("state");
197
198   writer.end_list("supertux-savegame");
199 }
200
201 void
202 World::load_state()
203 {
204   using namespace scripting;
205
206   if(!PHYSFS_exists(m_savegame_filename.c_str()))
207   {
208     log_info << m_savegame_filename << ": doesn't exist, not loading state" << std::endl;
209   }
210   else
211   {
212     try {
213       lisp::Parser parser;
214       const lisp::Lisp* root = parser.parse(m_savegame_filename);
215
216       const lisp::Lisp* lisp = root->get_lisp("supertux-savegame");
217       if(lisp == NULL)
218         throw std::runtime_error("file is not a supertux-savegame file");
219
220       int version = 1;
221       lisp->get("version", version);
222       if(version != 1)
223         throw std::runtime_error("incompatible savegame version");
224
225       const lisp::Lisp* tux = lisp->get_lisp("tux");
226       if(tux == NULL)
227         throw std::runtime_error("No tux section in savegame");
228       m_player_status->read(*tux);
229
230       const lisp::Lisp* state = lisp->get_lisp("state");
231       if(state == NULL)
232         throw std::runtime_error("No state section in savegame");
233
234       sq_pushroottable(global_vm);
235       sq_pushstring(global_vm, "state", -1);
236       if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
237         sq_pop(global_vm, 1);
238
239       sq_pushstring(global_vm, "state", -1);
240       sq_newtable(global_vm);
241       load_squirrel_table(global_vm, -1, *state);
242       if(SQ_FAILED(sq_createslot(global_vm, -3)))
243         throw std::runtime_error("Couldn't create state table");
244       sq_pop(global_vm, 1);
245     } catch(std::exception& e) {
246       log_fatal << "Couldn't load savegame: " << e.what() << std::endl;
247     }
248   }
249 }
250
251 const std::string&
252 World::get_level_filename(unsigned int i) const
253 {
254   return m_levels[i].fullpath;
255 }
256
257 unsigned int
258 World::get_num_levels() const
259 {
260   return m_levels.size();
261 }
262
263 int
264 World::get_num_solved_levels() const
265 {
266   int num_solved_levels = 0;
267
268   HSQUIRRELVM vm = scripting::global_vm;
269   int oldtop = sq_gettop(vm);
270
271   sq_pushroottable(vm);
272   sq_pushstring(vm, "state", -1);
273   if(SQ_FAILED(sq_get(vm, -2)))
274   {
275     log_warning << "failed to get 'state' table" << std::endl;
276   }
277   else
278   {
279     sq_pushstring(vm, "worlds", -1);
280     if(SQ_FAILED(sq_get(vm, -2)))
281     {
282       log_warning << "failed to get 'state.worlds' table" << std::endl;
283     }
284     else
285     {
286       sq_pushstring(vm, m_worldmap_filename.c_str(), -1);
287       if(SQ_FAILED(sq_get(vm, -2)))
288       {
289         log_warning << "failed to get state.worlds['" << m_worldmap_filename << "']" << std::endl;
290       }
291       else
292       {
293         sq_pushstring(vm, "levels", -1);
294         if(SQ_FAILED(sq_get(vm, -2)))
295         {
296           log_warning << "failed to get state.worlds['" << m_worldmap_filename << "'].levels" << std::endl;
297         }
298         else
299         {
300           for(auto level : m_levels)
301           {
302             sq_pushstring(vm, level.name.c_str(), -1);
303             if(SQ_FAILED(sq_get(vm, -2)))
304             {
305               log_warning << "failed to get state.worlds['" << m_worldmap_filename << "'].levels['"
306                           << level.name << "']" << std::endl;
307             }
308             else
309             {
310               bool solved = scripting::read_bool(vm, "solved");
311               if (solved)
312               {
313                 num_solved_levels += 1;
314               }
315               sq_pop(vm, 1);
316             }
317           }
318         }
319       }
320     }
321   }
322
323   sq_settop(vm, oldtop);
324
325   return num_solved_levels;
326 }
327
328 const std::string&
329 World::get_basedir() const
330 {
331   return m_basedir;
332 }
333
334 const std::string&
335 World::get_title() const
336 {
337   return m_title;
338 }
339
340 /* EOF */