- Avoid some expensive SDL_GetTicks() calls
[supertux.git] / src / title.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
5 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 //  02111-1307, USA.
21 #include <config.h>
22
23 #include <iostream>
24 #include <sstream>
25 #include <stdexcept>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <cmath>
32 #include <SDL.h>
33 #include <SDL_image.h>
34 #include <physfs.h>
35
36 #include "title.hpp"
37 #include "mainloop.hpp"
38 #include "video/drawing_context.hpp"
39 #include "video/surface.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
42 #include "timer.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/parser.hpp"
45 #include "level.hpp"
46 #include "world.hpp"
47 #include "game_session.hpp"
48 #include "worldmap/worldmap.hpp"
49 #include "player_status.hpp"
50 #include "tile.hpp"
51 #include "sector.hpp"
52 #include "object/tilemap.hpp"
53 #include "object/camera.hpp"
54 #include "object/player.hpp"
55 #include "resources.hpp"
56 #include "gettext.hpp"
57 #include "textscroller.hpp"
58 #include "fadeout.hpp"
59 #include "file_system.hpp"
60 #include "control/joystickkeyboardcontroller.hpp"
61 #include "control/codecontroller.hpp"
62 #include "main.hpp"
63 #include "log.hpp"
64 #include "options_menu.hpp"
65 #include "console.hpp"
66
67 enum MainMenuIDs {
68   MNID_STARTGAME,
69   MNID_LEVELS_CONTRIB,
70   MNID_OPTIONMENU,
71   MNID_LEVELEDITOR,
72   MNID_CREDITS,
73   MNID_QUITMAINMENU
74 };
75
76 void
77 TitleScreen::update_load_game_menu()
78 {
79   load_game_menu.reset(new Menu());
80
81   load_game_menu->add_label(_("Start Game"));
82   load_game_menu->add_hl();
83   for(int i = 1; i <= 5; ++i) {
84     load_game_menu->add_entry(i, get_slotinfo(i));
85   }
86   load_game_menu->add_hl();
87   load_game_menu->add_back(_("Back"));
88 }
89
90 void
91 TitleScreen::free_contrib_menu()
92 {
93   for(std::vector<World*>::iterator i = contrib_worlds.begin();
94       i != contrib_worlds.end(); ++i)
95     delete *i;
96
97   contrib_worlds.clear();
98 }
99
100 void
101 TitleScreen::generate_contrib_menu()
102 {
103   /** Generating contrib levels list by making use of Level Subset  */
104   std::vector<std::string> level_worlds; 
105   char** files = PHYSFS_enumerateFiles("levels/");
106   for(const char* const* filename = files; *filename != 0; ++filename) {
107     std::string filepath = std::string("levels/") + *filename;
108     if(PHYSFS_isDirectory(filepath.c_str()))
109       level_worlds.push_back(filepath);
110   }
111   PHYSFS_freeList(files);
112
113   free_contrib_menu();
114   contrib_menu.reset(new Menu());
115
116   contrib_menu->add_label(_("Contrib Levels"));
117   contrib_menu->add_hl();
118   
119   int i = 0;
120   for (std::vector<std::string>::iterator it = level_worlds.begin();
121       it != level_worlds.end(); ++it) {
122     try {
123       std::auto_ptr<World> world (new World());
124       world->load(*it + "/info");
125       if(world->hide_from_contribs) {
126         continue;
127       }
128       contrib_menu->add_entry(i++, world->title);
129       contrib_worlds.push_back(world.release());
130     } catch(std::exception& e) {
131 #ifdef DEBUG
132       log_warning << "Couldn't parse levelset info for '" << *it << "': " << e.what() << std::endl;
133 #endif
134     }
135   }
136
137   contrib_menu->add_hl();
138   contrib_menu->add_back(_("Back"));
139 }
140
141 std::string
142 TitleScreen::get_level_name(const std::string& filename)
143 {
144   try {
145     lisp::Parser parser;
146     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
147
148     const lisp::Lisp* level = root->get_lisp("supertux-level");
149     if(!level)
150       return "";
151
152     std::string name;
153     level->get("name", name);
154     return name;
155   } catch(std::exception& e) {
156     log_warning << "Problem getting name of '" << filename << "'." << std::endl;
157     return "";
158   }
159 }
160
161 void
162 TitleScreen::check_levels_contrib_menu()
163 {
164   int index = contrib_menu->check();
165   if (index == -1)
166     return;
167
168   current_world = contrib_worlds[index];
169
170   if(!current_world->is_levelset) {
171     update_load_game_menu();
172     Menu::push_current(load_game_menu.get());
173   } else {
174     contrib_world_menu.reset(new Menu());
175
176     contrib_world_menu->add_label(current_world->title);
177     contrib_world_menu->add_hl();
178
179     for (unsigned int i = 0; i < current_world->get_num_levels(); ++i)
180     {
181       /** get level's title */
182       std::string filename = current_world->get_level_filename(i);
183       std::string title = get_level_name(filename);
184       contrib_world_menu->add_entry(i, title);
185     }
186
187     contrib_world_menu->add_hl();
188     contrib_world_menu->add_back(_("Back"));
189
190     Menu::push_current(contrib_world_menu.get());
191   }
192 }
193
194 void
195 TitleScreen::check_contrib_world_menu()
196 {
197   int index = contrib_world_menu->check();
198   if (index != -1) {
199     if (contrib_world_menu->get_item_by_id(index).kind == MN_ACTION) {
200       sound_manager->stop_music();
201       GameSession* session =
202         new GameSession(current_world->get_level_filename(index));
203       main_loop->push_screen(session);
204     }
205   }  
206 }
207
208 void
209 TitleScreen::make_tux_jump()
210 {
211   static Timer randomWaitTimer;
212   static Timer jumpPushTimer;
213   static float last_tux_x_pos = -1;
214   static float last_tux_y_pos = -1;
215
216   Sector* sector  = titlesession->get_current_sector();
217   Player* tux = sector->player;
218
219   //sector->play_music(LEVEL_MUSIC);
220
221   controller->update();
222   controller->press(Controller::RIGHT);
223
224   // Determine how far we moved since last frame
225   float dx = fabsf(last_tux_x_pos - tux->get_pos().x); 
226   float dy = fabsf(last_tux_y_pos - tux->get_pos().y); 
227  
228   // Calculate space to check for obstacles 
229   Rect lookahead = tux->get_bbox();
230   lookahead.move(Vector(96, 0));
231   
232   // Check if we should press the jump button
233   bool randomJump = !randomWaitTimer.started();
234   bool notMoving = (fabsf(dx) + fabsf(dy)) < 0.1;
235   bool pathBlocked = !sector->is_free_space(lookahead); 
236   if (!controller->released(Controller::JUMP)
237       && (notMoving || pathBlocked || randomJump)) {
238     float jumpDuration;
239     if(pathBlocked)
240       jumpDuration = 0.5;
241     else
242       jumpDuration = float(rand() % 500 + 300) / 1000.0;
243     jumpPushTimer.start(jumpDuration);
244     randomWaitTimer.start(float(rand() % 3000 + 3000) / 1000.0);
245   }
246
247   // Keep jump button pressed
248   if (jumpPushTimer.started())
249     controller->press(Controller::JUMP);
250
251   // Remember last position, so we can determine if we moved
252   last_tux_x_pos = tux->get_pos().x;
253   last_tux_y_pos = tux->get_pos().y;
254
255   // Wrap around at the end of the level back to the beginnig
256   if(sector->solids->get_width() * 32 - 320 < tux->get_pos().x) {
257     sector->activate("main");
258     sector->camera->reset(tux->get_pos());
259   }
260 }
261
262 TitleScreen::TitleScreen()
263 {
264   controller.reset(new CodeController());
265   titlesession.reset(new GameSession("levels/misc/menu.stl"));
266
267   Player* player = titlesession->get_current_sector()->player;
268   player->set_controller(controller.get());
269
270   main_menu.reset(new Menu());
271   main_menu->set_pos(SCREEN_WIDTH/2, 335);
272   main_menu->add_entry(MNID_STARTGAME, _("Start Game"));
273   main_menu->add_entry(MNID_LEVELS_CONTRIB, _("Contrib Levels"));
274   main_menu->add_submenu(_("Options"), get_options_menu());
275   main_menu->add_entry(MNID_CREDITS, _("Credits"));
276   main_menu->add_entry(MNID_QUITMAINMENU, _("Quit"));
277 }
278
279 TitleScreen::~TitleScreen()
280 {
281 }
282
283 void
284 TitleScreen::setup()
285 {
286   player_status->reset();
287
288   Sector* sector = titlesession->get_current_sector();
289   if(Sector::current() != sector) {
290     sector->play_music(LEVEL_MUSIC);
291     sector->activate(sector->player->get_pos());
292   }
293
294   Menu::set_current(main_menu.get());
295 }
296
297 void
298 TitleScreen::leave()
299 {
300   Sector* sector = titlesession->get_current_sector();
301   sector->deactivate();
302   Menu::set_current(NULL);
303 }
304
305 void
306 TitleScreen::draw(DrawingContext& context)
307 {
308   Sector* sector  = titlesession->get_current_sector();
309   sector->draw(context);
310  
311   context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
312       Vector(0, SCREEN_HEIGHT - 50), LEFT_ALLIGN, LAYER_FOREGROUND1);
313   context.draw_text(white_small_text,
314       _(
315 "Copyright (c) 2006 SuperTux Devel Team\n"
316 "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to\n"
317 "redistribute it under certain conditions; see the file COPYING for details.\n"
318 ),
319       Vector(0, SCREEN_HEIGHT - 50 + white_small_text->get_height() + 5),
320       LEFT_ALLIGN, LAYER_FOREGROUND1);
321 }
322
323 void
324 TitleScreen::update(float elapsed_time)
325 {
326   main_loop->set_speed(0.6);
327   Sector* sector  = titlesession->get_current_sector();
328   sector->update(elapsed_time);
329
330   make_tux_jump();
331   
332   Menu* menu = Menu::current();
333   if(menu) {
334     menu->update();
335           
336     if(menu == main_menu.get()) {
337       switch (main_menu->check()) {
338         case MNID_STARTGAME:
339           // Start Game, ie. goto the slots menu
340           if(main_world.get() == NULL) {
341             main_world.reset(new World());
342             main_world->load("levels/world1/info");
343           }
344           current_world = main_world.get();
345           update_load_game_menu();
346           Menu::push_current(load_game_menu.get());
347           break;
348         case MNID_LEVELS_CONTRIB:
349           // Contrib Menu
350           generate_contrib_menu();
351           Menu::push_current(contrib_menu.get());
352           break;
353         case MNID_CREDITS:
354           main_loop->push_screen(new TextScroller("credits.txt"),
355                                  new FadeOut(0.5));
356           break;
357         case MNID_QUITMAINMENU:
358           main_loop->quit(new FadeOut(0.25));
359           break;
360       }
361     } else if(menu == load_game_menu.get()) {
362       /*
363       if(event.key.keysym.sym == SDLK_DELETE) {
364         int slot = menu->get_active_item_id();
365         std::stringstream stream;
366         stream << slot;
367         std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
368         
369         if(confirm_dialog(bkg_title, str.c_str())) {
370           str = "save/slot" + stream.str() + ".stsg";
371           log_debug << "Removing: " << str << std::endl;
372           PHYSFS_delete(str.c_str());
373         }
374
375         update_load_save_game_menu(load_game_menu);
376         Menu::set_current(main_menu.get());
377       }*/
378       process_load_game_menu();
379     } else if(menu == contrib_menu.get()) {
380       check_levels_contrib_menu();
381     } else if (menu == contrib_world_menu.get()) {
382       check_contrib_world_menu();
383     }
384   }
385
386   // reopen menu of user closed it (so that the app doesn't close when user
387   // accidently hit ESC)
388   if(Menu::current() == 0) {
389     Menu::set_current(main_menu.get());
390   }
391 }
392
393 std::string
394 TitleScreen::get_slotinfo(int slot)
395 {
396   std::string tmp;
397   std::string title;
398
399   std::string basename = current_world->get_basedir();
400   basename = basename.substr(0, basename.length()-1);
401   std::string worlddirname = FileSystem::basename(basename);
402   std::ostringstream stream;
403   stream << "save/" << worlddirname << "_" << slot << ".stsg";
404   std::string slotfile = stream.str();
405
406   try {
407     lisp::Parser parser;
408     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
409
410     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
411     if(!savegame)
412       throw std::runtime_error("file is not a supertux-savegame.");
413
414     savegame->get("title", title);
415   } catch(std::exception& e) {
416     std::ostringstream slottitle;
417     slottitle << _("Slot") << " " << slot << " - " << _("Free");
418     return slottitle.str();
419   }
420
421   std::ostringstream slottitle;
422   slottitle << _("Slot") << " " << slot << " - " << title;
423   return slottitle.str();
424 }
425
426 bool
427 TitleScreen::process_load_game_menu()
428 {
429   int slot = load_game_menu->check();
430
431   if(slot == -1)
432     return false;
433
434   if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
435     return false;
436
437   std::string basename = current_world->get_basedir();
438   basename = basename.substr(0, basename.length()-1);
439   std::string worlddirname = FileSystem::basename(basename);
440   std::stringstream stream;
441   stream << "save/" << worlddirname << "_" << slot << ".stsg";
442   std::string slotfile = stream.str();
443
444   try {
445     current_world->set_savegame_filename(slotfile);
446     current_world->run();
447   } catch(std::exception& e) {
448     log_fatal << "Couldn't start world: " << e.what() << std::endl;
449   }
450
451   return true;
452 }
453