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