* In the usage help, put LEVELFILE into brackets since it's an optional argument.
[supertux.git] / src / title.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.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 "video/screen.hpp"
38 #include "video/surface.hpp"
39 #include "audio/sound_manager.hpp"
40 #include "gui/menu.hpp"
41 #include "timer.hpp"
42 #include "lisp/lisp.hpp"
43 #include "lisp/parser.hpp"
44 #include "level.hpp"
45 #include "level_subset.hpp"
46 #include "game_session.hpp"
47 #include "worldmap.hpp"
48 #include "player_status.hpp"
49 #include "tile.hpp"
50 #include "sector.hpp"
51 #include "object/tilemap.hpp"
52 #include "object/camera.hpp"
53 #include "object/player.hpp"
54 #include "resources.hpp"
55 #include "gettext.hpp"
56 #include "misc.hpp"
57 #include "textscroller.hpp"
58 #include "file_system.hpp"
59 #include "control/joystickkeyboardcontroller.hpp"
60 #include "control/codecontroller.hpp"
61 #include "main.hpp"
62 #include "exceptions.hpp"
63
64 static Surface* bkg_title;
65 static Surface* logo;
66 //static Surface* img_choose_subset;
67
68 static bool walking;
69 static Timer random_timer;
70
71 static int frame;
72
73 static GameSession* titlesession;
74 static CodeController* controller;
75
76 static std::vector<LevelSubset*> contrib_subsets;
77 static LevelSubset* current_contrib_subset = 0;
78 static int current_subset = -1;
79
80 /* If the demo was stopped - because game started, level
81    editor was excuted, etc - call this when you get back
82    to the title code.
83  */
84 void resume_demo()
85 {
86   player_status->reset();
87   titlesession->get_current_sector()->activate("main");
88   titlesession->set_current();
89
90   //frame_rate.update();
91 }
92
93 void update_load_save_game_menu(Menu* menu)
94 {
95   printf("update loadsavemenu.\n");
96   for(int i = 1; i < 6; ++i) {
97     MenuItem& item = menu->get_item_by_id(i);
98     item.kind = MN_ACTION;
99     item.change_text(slotinfo(i));
100   }
101 }
102
103 void free_contrib_menu()
104 {
105   for(std::vector<LevelSubset*>::iterator i = contrib_subsets.begin();
106       i != contrib_subsets.end(); ++i)
107     delete *i;
108
109   contrib_subsets.clear();
110   contrib_menu->clear();
111   current_contrib_subset = 0;
112   current_subset = -1;
113 }
114
115 void generate_contrib_menu()
116 {
117   /** Generating contrib levels list by making use of Level Subset  */
118   std::vector<std::string> level_subsets; 
119   char** files = PHYSFS_enumerateFiles("levels/");
120   for(const char* const* filename = files; *filename != 0; ++filename) {
121     std::string filepath = std::string("levels/") + *filename;
122     if(PHYSFS_isDirectory(filepath.c_str()))
123       level_subsets.push_back(filepath);
124   }
125   PHYSFS_freeList(files);
126
127   free_contrib_menu();
128
129   contrib_menu->add_label(_("Contrib Levels"));
130   contrib_menu->add_hl();
131   
132   int i = 0;
133   for (std::vector<std::string>::iterator it = level_subsets.begin();
134       it != level_subsets.end(); ++it) {
135     try {
136       std::auto_ptr<LevelSubset> subset (new LevelSubset());
137       subset->load(*it);
138       if(subset->hide_from_contribs) {
139         continue;
140       }
141       contrib_menu->add_submenu(subset->title, contrib_subset_menu, i++);
142       contrib_subsets.push_back(subset.release());
143     } catch(std::exception& e) {
144 #ifdef DEBUG
145       std::cerr << "Couldn't parse levelset info for '"
146         << *it << "': " << e.what() << "\n";
147 #endif
148     }
149   }
150
151   contrib_menu->add_hl();
152   contrib_menu->add_back(_("Back"));
153 }
154
155 std::string get_level_name(const std::string& filename)
156 {
157   try {
158     lisp::Parser parser;
159     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
160
161     const lisp::Lisp* level = root->get_lisp("supertux-level");
162     if(!level)
163       return "";
164
165     std::string name;
166     level->get("name", name);
167     return name;
168   } catch(std::exception& e) {
169     std::cerr << "Problem getting name of '" << filename << "'.\n";
170     return "";
171   }
172 }
173
174 void check_levels_contrib_menu()
175 {
176   int index = contrib_menu->check();
177   if (index == -1)
178     return;
179
180   LevelSubset& subset = * (contrib_subsets[index]);
181   
182   if(subset.has_worldmap) {
183     WorldMapNS::WorldMap worldmap;
184     worldmap.set_map_filename(subset.get_worldmap_filename());
185     sound_manager->stop_music();
186
187     // some fading
188     fadeout(256);
189     DrawingContext context;
190     context.draw_text(white_text, "Loading...",
191         Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
192     context.do_drawing();
193
194     // TODO: slots should be available for contrib maps
195     worldmap.loadgame("save/" + subset.name + "-slot1.stsg");
196     worldmap.display();  // run the map
197
198     Menu::set_current(main_menu);
199     resume_demo();
200   } else if (current_subset != index) {
201     current_subset = index;
202     LevelSubset& subset = * (contrib_subsets[index]);
203
204     current_contrib_subset = &subset;
205
206     contrib_subset_menu->clear();
207
208     contrib_subset_menu->add_label(subset.title);
209     contrib_subset_menu->add_hl();
210
211     for (int i = 0; i < subset.get_num_levels(); ++i)
212     {
213       /** get level's title */
214       std::string filename = subset.get_level_filename(i);
215       std::string title = get_level_name(filename);
216       contrib_subset_menu->add_entry(i, title);
217     }
218
219     contrib_subset_menu->add_hl();
220     contrib_subset_menu->add_back(_("Back"));
221
222     titlesession->get_current_sector()->activate("main");
223     titlesession->set_current();
224   }
225 }
226
227 void check_contrib_subset_menu()
228 {
229   int index = contrib_subset_menu->check();
230   if (index != -1) {
231     if (contrib_subset_menu->get_item_by_id(index).kind == MN_ACTION) {
232       sound_manager->stop_music();
233       GameSession session(
234           current_contrib_subset->get_level_filename(index), ST_GL_PLAY);
235       session.run();
236       player_status->reset();
237       Menu::set_current(main_menu);
238       resume_demo();
239     }
240   }  
241 }
242
243 void draw_demo(float elapsed_time)
244 {
245   static float last_tux_x_pos = -1;
246   static float last_tux_y_pos = -1;
247   Sector* sector  = titlesession->get_current_sector();
248   Player* tux = sector->player;
249
250   sector->play_music(LEVEL_MUSIC);
251
252   controller->update();
253   controller->press(Controller::RIGHT);
254   
255   if(random_timer.check() || 
256       (walking && fabsf(last_tux_x_pos - tux->get_pos().x)) < .1) {
257     walking = false;
258   } else {
259       if(!walking && fabsf(tux->get_pos().y - last_tux_y_pos) < .1) {
260         random_timer.start(float(rand() % 3000 + 3000) / 1000.);
261         walking = true;
262       }
263   }
264   if(!walking)
265     controller->press(Controller::JUMP);
266   last_tux_x_pos = tux->get_pos().x;
267   last_tux_y_pos = tux->get_pos().y;
268
269   // Wrap around at the end of the level back to the beginnig
270   if(sector->solids->get_width() * 32 - 320 < tux->get_pos().x) {
271     sector->activate("main");
272     sector->camera->reset(tux->get_pos());
273   }
274
275   sector->update(elapsed_time);
276   sector->draw(*titlesession->context);
277 }
278
279 /* --- TITLE SCREEN --- */
280 void title()
281 {
282   walking = true;
283   //LevelEditor* leveleditor;
284   controller = new CodeController();
285
286   titlesession = new GameSession("levels/misc/menu.stl", ST_GL_DEMO_GAME);
287
288   /* Load images: */
289   bkg_title = new Surface("images/background/arctis.jpg");
290   logo = new Surface("images/engine/menu/logo.png");
291   //img_choose_subset = new Surface("images/status/choose-level-subset.png");
292
293   titlesession->get_current_sector()->activate("main");
294   titlesession->set_current();
295
296   Player* player = titlesession->get_current_sector()->player;
297   player->set_controller(controller);
298
299   /* --- Main title loop: --- */
300   frame = 0;
301
302   random_timer.start(float(rand() % 2000 + 2000) / 1000.0);
303
304   Uint32 lastticks = SDL_GetTicks();
305   
306   Menu::set_current(main_menu);
307   DrawingContext& context = *titlesession->context;
308   bool running = true;
309   while (running)
310     {
311       // Calculate the movement-factor
312       Uint32 ticks = SDL_GetTicks();
313       float elapsed_time = float(ticks - lastticks) / 1000.;
314       game_time += elapsed_time;
315       lastticks = ticks;
316       // 40fps is minimum
317       if(elapsed_time > .04)
318         elapsed_time = .04;
319       
320       /* Lower the speed so that Tux doesn't jump too hectically throught
321          the demo. */
322       elapsed_time /= 2;
323
324       SDL_Event event;
325       main_controller->update();
326       while (SDL_PollEvent(&event)) {
327         if (Menu::current()) {
328           Menu::current()->event(event);
329         }
330         main_controller->process_event(event);
331         if (event.type == SDL_QUIT)
332           throw graceful_shutdown();
333       }
334   
335       /* Draw the background: */
336       draw_demo(elapsed_time);
337
338       if (Menu::current() == main_menu)
339         context.draw_surface(logo, Vector(SCREEN_WIDTH/2 - logo->get_width()/2, 30),
340             LAYER_FOREGROUND1+1);
341
342       context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
343               Vector(0, SCREEN_HEIGHT - 50), LEFT_ALLIGN, LAYER_FOREGROUND1);
344       context.draw_text(white_small_text,
345         _(
346 "Copyright (c) 2006 SuperTux Devel Team\n"
347 "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to\n"
348 "redistribute it under certain conditions; see the file COPYING for details.\n"
349         ),
350         Vector(0, SCREEN_HEIGHT - 50 + white_small_text->get_height() + 5),
351         LEFT_ALLIGN, LAYER_FOREGROUND1);
352
353       /* Don't draw menu, if quit is true */
354       Menu* menu = Menu::current();
355       if(menu)
356         {
357           menu->draw(context);
358           menu->update();
359           
360           if(menu == main_menu)
361             {
362               switch (main_menu->check())
363                 {
364                 case MNID_STARTGAME:
365                   // Start Game, ie. goto the slots menu
366                   update_load_save_game_menu(load_game_menu);
367                   break;
368                 case MNID_LEVELS_CONTRIB:
369                   // Contrib Menu
370                   generate_contrib_menu();
371                   break;
372 #if 0
373                 case MNID_LEVELEDITOR: {
374                   LevelEdtiro* leveleditor = new LevelEditor();
375                   leveleditor->run();
376                   delete leveleditor;
377                   Menu::set_current(main_menu);
378                   resume_demo();
379                   break;
380                 }
381 #endif
382                 case MNID_CREDITS:
383                   sound_manager->stop_music();
384                   fadeout(500);
385                   sound_manager->play_music("music/credits.ogg");
386                   display_text_file("credits.txt");
387                   sound_manager->stop_music();
388                   fadeout(500);
389                   Menu::set_current(main_menu);
390                   break;
391                 case MNID_QUITMAINMENU:
392                   running = false;
393                   break;
394                 }
395             }
396           else if(menu == options_menu)
397             {
398               process_options_menu();
399             }
400           else if(menu == load_game_menu)
401             {
402               if(event.key.keysym.sym == SDLK_DELETE)
403                 {
404                 int slot = menu->get_active_item_id();
405                 std::stringstream stream;
406                 stream << slot;
407                 std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
408                 
409                 if(confirm_dialog(bkg_title, str.c_str())) {
410                   str = "save/slot" + stream.str() + ".stsg";
411                   printf("Removing: %s\n",str.c_str());
412                   PHYSFS_delete(str.c_str());
413                 }
414
415                 update_load_save_game_menu(load_game_menu);
416                 Menu::set_current(main_menu);
417                 resume_demo();
418                 }
419               else if (process_load_game_menu())
420                 {
421                   resume_demo();
422                 }
423             }
424           else if(menu == contrib_menu)
425             {
426               check_levels_contrib_menu();
427             }
428           else if (menu == contrib_subset_menu)
429             {
430               check_contrib_subset_menu();
431             }
432         }
433
434       // reopen menu of user closed it (so that the app doesn't close when user
435       // accidently hit ESC)
436       if(Menu::current() == 0) {
437         Menu::set_current(main_menu);
438       }
439
440       context.do_drawing();
441       sound_manager->update();
442
443       //frame_rate.update();
444
445       /* Pause: */
446       frame++;
447     }
448   /* Free surfaces: */
449
450   free_contrib_menu();
451   delete titlesession;
452   delete bkg_title;
453   delete logo;
454   //delete img_choose_subset;
455 }