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