fix some more timings and the long standing gradient software bug (which was function...
[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 <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <cmath>
31 #include <SDL.h>
32 #include <SDL_image.h>
33
34 #ifndef WIN32
35 #include <sys/types.h>
36 #include <ctype.h>
37 #endif
38
39 #include "defines.h"
40 #include "app/globals.h"
41 #include "title.h"
42 #include "video/screen.h"
43 #include "video/surface.h"
44 #include "high_scores.h"
45 #include "gui/menu.h"
46 #include "timer.h"
47 #include "special/frame_rate.h"
48 #include "app/setup.h"
49 #include "level.h"
50 #include "level_subset.h"
51 #include "gameloop.h"
52 #include "worldmap.h"
53 #include "leveleditor.h"
54 #include "scene.h"
55 #include "player.h"
56 #include "tile.h"
57 #include "sector.h"
58 #include "tilemap.h"
59 #include "resources.h"
60 #include "app/gettext.h"
61 #include "misc.h"
62 #include "camera.h"
63
64 static Surface* bkg_title;
65 static Surface* logo;
66 static Surface* img_choose_subset;
67
68 static bool walking;
69 static Timer2 random_timer;
70
71 static int frame;
72
73 static GameSession* titlesession;
74
75 static std::vector<LevelSubset*> contrib_subsets;
76 static LevelSubset* current_contrib_subset = 0;
77 static int first_level_index;
78
79 static std::set<std::string> worldmap_list;
80
81 static FrameRate frame_rate(100);  
82
83 /* If the demo was stopped - because game started, level
84    editor was excuted, etc - call this when you get back
85    to the title code.
86  */
87 void resume_demo()
88 {
89   // FIXME: shouldn't be needed if GameSession
90   // didn't relay on global variables
91   titlesession->get_current_sector()->activate();
92   titlesession->set_current();
93
94   frame_rate.update();
95 }
96
97 void update_load_save_game_menu(Menu* pmenu)
98 {
99   for(int i = 2; i < 7; ++i)
100     {
101       // FIXME: Insert a real savegame struct/class here instead of
102       // doing string vodoo
103       std::string tmp = slotinfo(i - 1);
104       pmenu->item[i].kind = MN_ACTION;
105       pmenu->item[i].change_text(tmp.c_str());
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->additem(MN_LABEL,_("Contrib Levels"),0,0);
127   contrib_menu->additem(MN_HL,"",0,0);
128   int i = 0;
129
130   for(std::set<std::string>::iterator it = worldmap_list.begin(); it != worldmap_list.end(); ++it)
131     {
132     WorldMapNS::WorldMap worldmap;
133     worldmap.loadmap((*it).c_str());
134     contrib_menu->additem(MN_ACTION, worldmap.get_world_title(),0,0, i);
135     ++i;
136     }
137
138   contrib_menu->additem(MN_HL,"",0,0);
139
140   first_level_index = i;
141   for (std::set<std::string>::iterator it = level_subsets.begin(); it != level_subsets.end(); ++it)
142     {
143       LevelSubset* subset = new LevelSubset();
144       subset->load(*it);
145       if(subset->hide_from_contribs)
146         {
147         delete subset;
148         continue;
149         }
150       contrib_menu->additem(MN_GOTO, subset->title, 0, contrib_subset_menu, i);
151       contrib_subsets.push_back(subset);
152       ++i;
153     }
154
155   contrib_menu->additem(MN_HL,"",0,0);
156   contrib_menu->additem(MN_BACK,_("Back"),0,0);
157
158   level_subsets.clear();
159 }
160
161 void check_levels_contrib_menu()
162 {
163   static int current_subset = -1;
164
165   int index = contrib_menu->check();
166   if (index == -1)
167     return;
168
169   if((unsigned)index < worldmap_list.size())
170     {
171     WorldMapNS::WorldMap worldmap;
172     std::set<std::string>::iterator it = worldmap_list.begin();
173     for(int i = index; i > 0; --i)
174     ++it;
175
176     std::string map_filename = *it;
177
178     // some fading
179     fadeout(256);
180     DrawingContext context;
181       context.draw_text(white_text, "Loading...",
182                         Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
183       context.do_drawing();
184
185     worldmap.set_map_filename(map_filename);
186
187     // hack to erase the extension
188     unsigned int ext_pos = it->find_last_of(".");
189     if(ext_pos != std::string::npos)
190       map_filename.erase(ext_pos, map_filename.size() - ext_pos);
191
192     // TODO: slots should be available for contrib maps
193     worldmap.loadgame(st_save_dir + "/" + map_filename + "-slot1.stsg");
194
195     worldmap.display();  // run the map
196
197     Menu::set_current(main_menu);
198     resume_demo();
199     }
200   else if (index < (int)contrib_subsets.size() + first_level_index)
201     {
202     index -= first_level_index;
203     if (current_subset != index)
204       {
205       current_subset = index;
206       // FIXME: This shouln't be busy looping
207       LevelSubset& subset = * (contrib_subsets[index]);
208
209       current_contrib_subset = &subset;
210
211       contrib_subset_menu->clear();
212
213       contrib_subset_menu->additem(MN_LABEL, subset.title, 0,0);
214       contrib_subset_menu->additem(MN_HL,"",0,0);
215
216       for (int i = 0; i < subset.get_num_levels(); ++i)
217         {
218         /** get level's title */
219         std::string level_title = "<no title>";
220
221         std::string filename = subset.get_level_filename(i);
222         std::string filepath;
223         filepath = st_dir + "/levels/" + filename;
224         if (access(filepath.c_str(), R_OK) != 0)
225         {
226           filepath = datadir + "/levels/" + filename;
227           if (access(filepath.c_str(), R_OK) != 0)
228           {
229             std::cerr << "Error: Level: couldn't find level: " << filename << std::endl;
230             continue;
231           }
232         }
233         
234         LispReader* reader = LispReader::load(filepath, "supertux-level");
235         if(!reader)
236           {
237           std::cerr << "Error: Could not open level file. Ignoring...\n";
238           continue;
239           }
240
241         reader->read_string("name", level_title, true);
242         delete reader;
243
244         contrib_subset_menu->additem(MN_ACTION, level_title, 0, 0, i);
245         }
246
247       contrib_subset_menu->additem(MN_HL,"",0,0);      
248       contrib_subset_menu->additem(MN_BACK, _("Back"), 0, 0);
249
250       titlesession->get_current_sector()->activate();
251       titlesession->set_current();
252       }
253     }
254 }
255
256 void check_contrib_subset_menu()
257 {
258   int index = contrib_subset_menu->check();
259   if (index != -1)
260     {
261       if (contrib_subset_menu->get_item_by_id(index).kind == MN_ACTION)
262         {
263           std::cout << "Starting level: " << index << std::endl;
264           
265           GameSession session(
266               current_contrib_subset->get_level_filename(index), ST_GL_PLAY);
267           session.run();
268           player_status.reset();
269           Menu::set_current(main_menu);
270           resume_demo();
271         }
272     }  
273 }
274
275 void draw_demo(float elapsed_time)
276 {
277   Sector* world  = titlesession->get_current_sector();
278   Player* tux = world->player;
279
280   world->play_music(LEVEL_MUSIC);
281   
282   tux->key_event((SDLKey) keymap.right,DOWN);
283   
284   if(random_timer.check()) {
285     random_timer.start(float(rand() % 3000 + 3000) / 1000.);
286     walking = !walking;
287   } else {
288       if(walking)
289         tux->key_event((SDLKey) keymap.jump,UP);
290       else
291         tux->key_event((SDLKey) keymap.jump,DOWN);
292   }
293
294   // Wrap around at the end of the level back to the beginnig
295   if(world->solids->get_width() * 32 - 320 < tux->get_pos().x)
296     {
297       tux->level_begin();
298       world->camera->reset(tux->get_pos());
299     }
300
301   tux->can_jump = true;
302   float last_tux_x_pos = tux->get_pos().x;
303   world->action(elapsed_time);
304   
305
306   // disabled for now, since with the new jump code we easily get deadlocks
307   // Jump if tux stays in the same position for one loop, ie. if he is
308   // stuck behind a wall
309   if (last_tux_x_pos == tux->get_pos().x)
310     {
311       walking = false;
312     }
313
314   world->draw(*titlesession->context);
315 }
316
317 /* --- TITLE SCREEN --- */
318 void title(void)
319 {
320   walking = true;
321   LevelEditor* leveleditor;
322
323   Ticks::pause_init();
324
325   titlesession = new GameSession("misc/menu.stl", ST_GL_DEMO_GAME);
326
327   /* Load images: */
328   bkg_title = new Surface(datadir + "/images/background/arctis.jpg", false);
329   logo = new Surface(datadir + "/images/title/logo.png", true);
330   img_choose_subset = new Surface(datadir + "/images/status/choose-level-subset.png", true);
331
332   /* Generating contrib maps by only using a string_list */
333   worldmap_list = FileSystem::dfiles("levels/worldmap", "", "icyisland.stwm");
334
335   titlesession->get_current_sector()->activate();
336   titlesession->set_current();
337
338   /* --- Main title loop: --- */
339   frame = 0;
340
341   random_timer.start(float(rand() % 2000 + 2000) / 1000.0);
342
343   Uint32 lastticks = SDL_GetTicks();
344   
345   Menu::set_current(main_menu);
346   DrawingContext& context = *titlesession->context;
347   while (Menu::current())
348     {
349       // Calculate the movement-factor
350       Uint32 ticks = SDL_GetTicks();
351       float elapsed_time = float(ticks - lastticks) / 1000.;
352       global_time += elapsed_time;
353       lastticks = ticks;
354       // 40fps is minimum
355       if(elapsed_time > .04)
356         elapsed_time = .04;
357       
358       /* Lower the speed so that Tux doesn't jump too hectically throught
359          the demo. */
360       elapsed_time /= 2;
361
362       SDL_Event event;
363       while (SDL_PollEvent(&event))
364         {
365           if (Menu::current())
366             {
367               Menu::current()->event(event);
368             }
369          // FIXME: QUIT signal should be handled more generic, not locally
370           if (event.type == SDL_QUIT)
371             Menu::set_current(0);
372         }
373   
374       /* Draw the background: */
375       draw_demo(elapsed_time);
376       
377       
378       if (Menu::current() == main_menu)
379         context.draw_surface(logo, Vector(screen->w/2 - logo->w/2, 30),
380             LAYER_FOREGROUND1+1);
381
382       context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
383               Vector(0, screen->h - 70), LEFT_ALLIGN, LAYER_FOREGROUND1);
384       context.draw_text(white_small_text,
385         _("Copyright (c) 2003 SuperTux Devel Team\n"
386           "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you\n"
387           "are welcome to redistribute it under certain conditions; see the file COPYING\n"
388           "for details.\n"), Vector(0, screen->h - 70 + white_small_text->get_height()), LEFT_ALLIGN, LAYER_FOREGROUND1);
389
390       /* Don't draw menu, if quit is true */
391       Menu* menu = Menu::current();
392       if(menu)
393         {
394           menu->draw(context);
395           menu->action();
396           
397           if(menu == main_menu)
398             {
399               switch (main_menu->check())
400                 {
401                 case MNID_STARTGAME:
402                   // Start Game, ie. goto the slots menu
403                   update_load_save_game_menu(load_game_menu);
404                   break;
405                 case MNID_LEVELS_CONTRIB:
406                   // Contrib Menu
407                   puts("Entering contrib menu");
408                   generate_contrib_menu();
409                   break;
410                 case MNID_LEVELEDITOR:
411                   leveleditor = new LevelEditor();
412                   leveleditor->run();
413                   delete leveleditor;
414                   Menu::set_current(main_menu);
415                   resume_demo();
416                   break;
417                 case MNID_CREDITS:
418                   fadeout(500);
419                   display_text_file("credits.txt", SCROLL_SPEED_CREDITS, white_big_text , white_text, white_small_text, blue_text );
420                   fadeout(500);
421                   Menu::set_current(main_menu);
422                   break;
423                 case MNID_QUITMAINMENU:
424                   Menu::set_current(0);
425                   break;
426                 }
427             }
428           else if(menu == options_menu)
429             {
430               process_options_menu();
431             }
432           else if(menu == load_game_menu)
433             {
434               if(event.key.keysym.sym == SDLK_DELETE)
435                 {
436                 int slot = menu->get_active_item_id();
437                 std::stringstream stream;
438                 stream << slot;
439                 std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
440                 
441                 if(confirm_dialog(bkg_title, str.c_str()))
442                   {
443                   str = st_save_dir + "/slot" + stream.str() + ".stsg";
444                   printf("Removing: %s\n",str.c_str());
445                   remove(str.c_str());
446                   }
447
448                 update_load_save_game_menu(load_game_menu);
449                 Menu::set_current(main_menu);
450                 resume_demo();
451                 }
452               else if (process_load_game_menu())
453                 {
454                   resume_demo();
455                 }
456             }
457           else if(menu == contrib_menu)
458             {
459               check_levels_contrib_menu();
460             }
461           else if (menu == contrib_subset_menu)
462             {
463               check_contrib_subset_menu();
464             }
465         }
466
467       mouse_cursor->draw(context);
468      
469       context.do_drawing();
470
471       frame_rate.update();
472
473       /* Pause: */
474       frame++;
475     }
476   /* Free surfaces: */
477
478   free_contrib_menu();
479   worldmap_list.clear();
480   delete titlesession;
481   delete bkg_title;
482   delete logo;
483   delete img_choose_subset;
484 }
485
486
487 // EOF //
488