fix cr/lfs and remove trailing whitespaces...
[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 #include "random_generator.hpp"
67
68 enum MainMenuIDs {
69   MNID_STARTGAME,
70   MNID_LEVELS_CONTRIB,
71   MNID_OPTIONMENU,
72   MNID_LEVELEDITOR,
73   MNID_CREDITS,
74   MNID_QUITMAINMENU
75 };
76
77 void
78 TitleScreen::update_load_game_menu()
79 {
80   load_game_menu.reset(new Menu());
81
82   load_game_menu->add_label(_("Start Game"));
83   load_game_menu->add_hl();
84   for(int i = 1; i <= 5; ++i) {
85     load_game_menu->add_entry(i, get_slotinfo(i));
86   }
87   load_game_menu->add_hl();
88   load_game_menu->add_back(_("Back"));
89 }
90
91 void
92 TitleScreen::free_contrib_menu()
93 {
94   for(std::vector<World*>::iterator i = contrib_worlds.begin();
95       i != contrib_worlds.end(); ++i)
96     delete *i;
97
98   contrib_worlds.clear();
99 }
100
101 void
102 TitleScreen::generate_contrib_menu()
103 {
104   /** Generating contrib levels list by making use of Level Subset  */
105   std::vector<std::string> level_worlds;
106   char** files = PHYSFS_enumerateFiles("levels/");
107   for(const char* const* filename = files; *filename != 0; ++filename) {
108     std::string filepath = std::string("levels/") + *filename;
109     if(PHYSFS_isDirectory(filepath.c_str()))
110       level_worlds.push_back(filepath);
111   }
112   PHYSFS_freeList(files);
113
114   free_contrib_menu();
115   contrib_menu.reset(new Menu());
116
117   contrib_menu->add_label(_("Contrib Levels"));
118   contrib_menu->add_hl();
119
120   int i = 0;
121   for (std::vector<std::string>::iterator it = level_worlds.begin();
122       it != level_worlds.end(); ++it) {
123     try {
124       std::auto_ptr<World> world (new World());
125       world->load(*it + "/info");
126       if(world->hide_from_contribs) {
127         continue;
128       }
129       contrib_menu->add_entry(i++, world->title);
130       contrib_worlds.push_back(world.release());
131     } catch(std::exception& e) {
132 #ifdef DEBUG
133       log_warning << "Couldn't parse levelset info for '" << *it << "': " << e.what() << std::endl;
134 #endif
135     }
136   }
137
138   contrib_menu->add_hl();
139   contrib_menu->add_back(_("Back"));
140 }
141
142 std::string
143 TitleScreen::get_level_name(const std::string& filename)
144 {
145   try {
146     lisp::Parser parser;
147     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
148
149     const lisp::Lisp* level = root->get_lisp("supertux-level");
150     if(!level)
151       return "";
152
153     std::string name;
154     level->get("name", name);
155     return name;
156   } catch(std::exception& e) {
157     log_warning << "Problem getting name of '" << filename << "'." << std::endl;
158     return "";
159   }
160 }
161
162 void
163 TitleScreen::check_levels_contrib_menu()
164 {
165   int index = contrib_menu->check();
166   if (index == -1)
167     return;
168
169   current_world = contrib_worlds[index];
170
171   if(!current_world->is_levelset) {
172     update_load_game_menu();
173     Menu::push_current(load_game_menu.get());
174   } else {
175     contrib_world_menu.reset(new Menu());
176
177     contrib_world_menu->add_label(current_world->title);
178     contrib_world_menu->add_hl();
179
180     for (unsigned int i = 0; i < current_world->get_num_levels(); ++i)
181     {
182       /** get level's title */
183       std::string filename = current_world->get_level_filename(i);
184       std::string title = get_level_name(filename);
185       contrib_world_menu->add_entry(i, title);
186     }
187
188     contrib_world_menu->add_hl();
189     contrib_world_menu->add_back(_("Back"));
190
191     Menu::push_current(contrib_world_menu.get());
192   }
193 }
194
195 void
196 TitleScreen::check_contrib_world_menu()
197 {
198   int index = contrib_world_menu->check();
199   if (index != -1) {
200     if (contrib_world_menu->get_item_by_id(index).kind == MN_ACTION) {
201       sound_manager->stop_music();
202       GameSession* session =
203         new GameSession(current_world->get_level_filename(index));
204       main_loop->push_screen(session);
205     }
206   }
207 }
208
209 void
210 TitleScreen::make_tux_jump()
211 {
212   static Timer randomWaitTimer;
213   static Timer jumpPushTimer;
214   static float last_tux_x_pos = -1;
215   static float last_tux_y_pos = -1;
216
217   Sector* sector  = titlesession->get_current_sector();
218   Player* tux = sector->player;
219
220   //sector->play_music(LEVEL_MUSIC);
221
222   controller->update();
223   controller->press(Controller::RIGHT);
224
225   // Determine how far we moved since last frame
226   float dx = fabsf(last_tux_x_pos - tux->get_pos().x);
227   float dy = fabsf(last_tux_y_pos - tux->get_pos().y);
228
229   // Calculate space to check for obstacles
230   Rect lookahead = tux->get_bbox();
231   lookahead.move(Vector(96, 0));
232
233   // Check if we should press the jump button
234   bool randomJump = !randomWaitTimer.started();
235   bool notMoving = (fabsf(dx) + fabsf(dy)) < 0.1;
236   bool pathBlocked = !sector->is_free_space(lookahead);
237   if (!controller->released(Controller::JUMP)
238       && (notMoving || pathBlocked || randomJump)) {
239     float jumpDuration;
240     if(pathBlocked)
241       jumpDuration = 0.5;
242     else
243       jumpDuration = systemRandom.randf(0.3, 0.8);
244     jumpPushTimer.start(jumpDuration);
245     randomWaitTimer.start(systemRandom.randf(3.0, 6.0));
246   }
247
248   // Keep jump button pressed
249   if (jumpPushTimer.started())
250     controller->press(Controller::JUMP);
251
252   // Remember last position, so we can determine if we moved
253   last_tux_x_pos = tux->get_pos().x;
254   last_tux_y_pos = tux->get_pos().y;
255
256   // Wrap around at the end of the level back to the beginnig
257   if(sector->get_width() - 320 < tux->get_pos().x) {
258     sector->activate("main");
259     sector->camera->reset(tux->get_pos());
260   }
261 }
262
263 TitleScreen::TitleScreen()
264 {
265   controller.reset(new CodeController());
266   titlesession.reset(new GameSession("levels/misc/menu.stl"));
267
268   Player* player = titlesession->get_current_sector()->player;
269   player->set_controller(controller.get());
270
271   main_menu.reset(new Menu());
272   main_menu->set_pos(SCREEN_WIDTH/2, 335);
273   main_menu->add_entry(MNID_STARTGAME, _("Start Game"));
274   main_menu->add_entry(MNID_LEVELS_CONTRIB, _("Contrib Levels"));
275   main_menu->add_submenu(_("Options"), get_options_menu());
276   main_menu->add_entry(MNID_CREDITS, _("Credits"));
277   main_menu->add_entry(MNID_QUITMAINMENU, _("Quit"));
278 }
279
280 TitleScreen::~TitleScreen()
281 {
282 }
283
284 void
285 TitleScreen::setup()
286 {
287   player_status->reset();
288
289   Sector* sector = titlesession->get_current_sector();
290   if(Sector::current() != sector) {
291     sector->play_music(LEVEL_MUSIC);
292     sector->activate(sector->player->get_pos());
293   }
294
295   Menu::set_current(main_menu.get());
296 }
297
298 void
299 TitleScreen::leave()
300 {
301   Sector* sector = titlesession->get_current_sector();
302   sector->deactivate();
303   Menu::set_current(NULL);
304 }
305
306 void
307 TitleScreen::draw(DrawingContext& context)
308 {
309   Sector* sector  = titlesession->get_current_sector();
310   sector->draw(context);
311
312   context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
313       Vector(0, SCREEN_HEIGHT - 50), LEFT_ALLIGN, LAYER_FOREGROUND1);
314   context.draw_text(white_small_text,
315       _(
316 "Copyright (c) 2006 SuperTux Devel Team\n"
317 "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to\n"
318 "redistribute it under certain conditions; see the file COPYING for details.\n"
319 ),
320       Vector(0, SCREEN_HEIGHT - 50 + white_small_text->get_height() + 5),
321       LEFT_ALLIGN, LAYER_FOREGROUND1);
322 }
323
324 void
325 TitleScreen::update(float elapsed_time)
326 {
327   main_loop->set_speed(0.6);
328   Sector* sector  = titlesession->get_current_sector();
329   sector->update(elapsed_time);
330
331   make_tux_jump();
332
333   Menu* menu = Menu::current();
334   if(menu) {
335     menu->update();
336
337     if(menu == main_menu.get()) {
338       switch (main_menu->check()) {
339         case MNID_STARTGAME:
340           // Start Game, ie. goto the slots menu
341           if(main_world.get() == NULL) {
342             main_world.reset(new World());
343             main_world->load("levels/world1/info");
344           }
345           current_world = main_world.get();
346           update_load_game_menu();
347           Menu::push_current(load_game_menu.get());
348           break;
349         case MNID_LEVELS_CONTRIB:
350           // Contrib Menu
351           generate_contrib_menu();
352           Menu::push_current(contrib_menu.get());
353           break;
354         case MNID_CREDITS:
355           main_loop->push_screen(new TextScroller("credits.txt"),
356                                  new FadeOut(0.5));
357           break;
358         case MNID_QUITMAINMENU:
359           main_loop->quit(new FadeOut(0.25));
360           break;
361       }
362     } else if(menu == load_game_menu.get()) {
363       /*
364       if(event.key.keysym.sym == SDLK_DELETE) {
365         int slot = menu->get_active_item_id();
366         std::stringstream stream;
367         stream << slot;
368         std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
369
370         if(confirm_dialog(bkg_title, str.c_str())) {
371           str = "save/slot" + stream.str() + ".stsg";
372           log_debug << "Removing: " << str << std::endl;
373           PHYSFS_delete(str.c_str());
374         }
375
376         update_load_save_game_menu(load_game_menu);
377         Menu::set_current(main_menu.get());
378       }*/
379       process_load_game_menu();
380     } else if(menu == contrib_menu.get()) {
381       check_levels_contrib_menu();
382     } else if (menu == contrib_world_menu.get()) {
383       check_contrib_world_menu();
384     }
385   }
386
387   // reopen menu of user closed it (so that the app doesn't close when user
388   // accidently hit ESC)
389   if(Menu::current() == 0) {
390     Menu::set_current(main_menu.get());
391   }
392 }
393
394 std::string
395 TitleScreen::get_slotinfo(int slot)
396 {
397   std::string tmp;
398   std::string title;
399
400   std::string basename = current_world->get_basedir();
401   basename = basename.substr(0, basename.length()-1);
402   std::string worlddirname = FileSystem::basename(basename);
403   std::ostringstream stream;
404   stream << "save/" << worlddirname << "_" << slot << ".stsg";
405   std::string slotfile = stream.str();
406
407   try {
408     lisp::Parser parser;
409     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
410
411     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
412     if(!savegame)
413       throw std::runtime_error("file is not a supertux-savegame.");
414
415     savegame->get("title", title);
416   } catch(std::exception& e) {
417     std::ostringstream slottitle;
418     slottitle << _("Slot") << " " << slot << " - " << _("Free");
419     return slottitle.str();
420   }
421
422   std::ostringstream slottitle;
423   slottitle << _("Slot") << " " << slot << " - " << title;
424   return slottitle.str();
425 }
426
427 bool
428 TitleScreen::process_load_game_menu()
429 {
430   int slot = load_game_menu->check();
431
432   if(slot == -1)
433     return false;
434
435   if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
436     return false;
437
438   std::string basename = current_world->get_basedir();
439   basename = basename.substr(0, basename.length()-1);
440   std::string worlddirname = FileSystem::basename(basename);
441   std::stringstream stream;
442   stream << "save/" << worlddirname << "_" << slot << ".stsg";
443   std::string slotfile = stream.str();
444
445   try {
446     current_world->set_savegame_filename(slotfile);
447     current_world->run();
448   } catch(std::exception& e) {
449     log_fatal << "Couldn't start world: " << e.what() << std::endl;
450   }
451
452   return true;
453 }