refactored some supertux mainloops
[supertux.git] / src / main.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2005 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 // 
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "msg.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <time.h>
29 #include <stdlib.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <dirent.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <physfs.h>
36 #include <SDL.h>
37 #include <SDL_image.h>
38 #include <SDL_opengl.h>
39
40 #include "gameconfig.hpp"
41 #include "resources.hpp"
42 #include "gettext.hpp"
43 #include "audio/sound_manager.hpp"
44 #include "video/surface.hpp"
45 #include "video/texture_manager.hpp"
46 #include "control/joystickkeyboardcontroller.hpp"
47 #include "misc.hpp"
48 #include "mainloop.hpp"
49 #include "title.hpp"
50 #include "game_session.hpp"
51 #include "file_system.hpp"
52 #include "physfs/physfs_sdl.hpp"
53 #include "exceptions.hpp"
54
55 SDL_Surface* screen = 0;
56 JoystickKeyboardController* main_controller = 0;
57 TinyGetText::DictionaryManager dictionary_manager;
58
59 static void init_config()
60 {
61   config = new Config();
62   try {
63     config->load();
64   } catch(std::exception& e) {
65     msg_info("Couldn't load config file: " << e.what() << ", using default settings");
66   }
67 }
68
69 static void init_tinygettext()
70 {
71   dictionary_manager.add_directory("locale");
72   dictionary_manager.set_charset("UTF-8");
73 }
74
75 static void init_physfs(const char* argv0)
76 {
77   if(!PHYSFS_init(argv0)) {
78     std::stringstream msg;
79     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
80     throw std::runtime_error(msg.str());
81   }
82
83   // Initialize physfs (this is a slightly modified version of
84   // PHYSFS_setSaneConfig
85   const char* application = PACKAGE_NAME;
86   const char* userdir = PHYSFS_getUserDir();
87   const char* dirsep = PHYSFS_getDirSeparator();
88   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
89
90   // Set configuration directory
91   sprintf(writedir, "%s.%s", userdir, application);
92   if(!PHYSFS_setWriteDir(writedir)) {
93     // try to create the directory
94     char* mkdir = new char[strlen(application) + 2];
95     sprintf(mkdir, ".%s", application);
96     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
97       std::ostringstream msg;
98       msg << "Failed creating configuration directory '" 
99           << writedir << "': " << PHYSFS_getLastError();
100       delete[] writedir;
101       delete[] mkdir;
102       throw std::runtime_error(msg.str());
103     }
104     delete[] mkdir;
105     
106     if(!PHYSFS_setWriteDir(writedir)) {
107       std::ostringstream msg;
108       msg << "Failed to use configuration directory '" 
109           <<  writedir << "': " << PHYSFS_getLastError();
110       delete[] writedir;
111       throw std::runtime_error(msg.str());
112     }
113   }
114   PHYSFS_addToSearchPath(writedir, 0);
115   delete[] writedir;
116
117   // Search for archives and add them to the search path
118   const char* archiveExt = "zip";
119   char** rc = PHYSFS_enumerateFiles("/");
120   size_t extlen = strlen(archiveExt);
121
122   for(char** i = rc; *i != 0; ++i) {
123     size_t l = strlen(*i);
124     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
125       const char* ext = (*i) + (l - extlen);
126       if(strcasecmp(ext, archiveExt) == 0) {
127         const char* d = PHYSFS_getRealDir(*i);
128         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
129         sprintf(str, "%s%s%s", d, dirsep, *i);
130         PHYSFS_addToSearchPath(str, 1);
131         delete[] str;
132       }
133     }
134   }
135   
136   PHYSFS_freeList(rc);
137
138   // when started from source dir...
139   std::string dir = PHYSFS_getBaseDir();
140   dir += "/data";
141   std::string testfname = dir;
142   testfname += "/credits.txt";
143   bool sourcedir = false;
144   FILE* f = fopen(testfname.c_str(), "r");
145   if(f) {
146     fclose(f);
147     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
148       msg_warning("Couldn't add '" << dir 
149                 << "' to physfs searchpath: " << PHYSFS_getLastError());
150     } else {
151       sourcedir = true;
152     }
153   }
154
155   if(!sourcedir) {
156 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
157     std::string datadir;
158 #ifdef ENABLE_BINRELOC
159     char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
160     datadir = brdatadir;
161     free(brdatadir);
162 #else
163     datadir = APPDATADIR;
164 #endif
165     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
166       msg_warning("Couldn't add '" << datadir
167         << "' to physfs searchpath: " << PHYSFS_getLastError());
168     }
169 #endif
170   }
171
172   // allow symbolic links
173   PHYSFS_permitSymbolicLinks(1);
174
175   //show search Path
176   for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
177     msg_info("[" << *i << "] is in the search path");
178 }
179
180 static void print_usage(const char* argv0)
181 {
182   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
183   fprintf(stderr,
184           _("Options:\n"
185             "  -f, --fullscreen             Run in fullscreen mode\n"
186             "  -w, --window                 Run in window mode\n"
187             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
188             "  --disable-sfx                Disable sound effects\n"
189             "  --disable-music              Disable music\n"
190             "  --help                       Show this help message\n"
191             "  --version                    Display SuperTux version and quit\n"
192             "  --show-fps                   Display framerate in levels\n"
193             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
194             "  --play-demo FILE LEVEL       Play a recorded demo\n"
195             "\n"));
196 }
197
198 static void parse_commandline(int argc, char** argv)
199 {
200   for(int i = 1; i < argc; ++i) {
201     std::string arg = argv[i];
202
203     if(arg == "--fullscreen" || arg == "-f") {
204       config->use_fullscreen = true;
205     } else if(arg == "--window" || arg == "-w") {
206       config->use_fullscreen = false;
207     } else if(arg == "--geometry" || arg == "-g") {
208       if(i+1 >= argc) {
209         print_usage(argv[0]);
210         throw std::runtime_error("Need to specify a parameter for geometry switch");
211       }
212       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
213          != 2) {
214         print_usage(argv[0]);
215         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
216       }
217     } else if(arg == "--show-fps") {
218       config->show_fps = true;
219     } else if(arg == "--disable-sfx") {
220       config->sound_enabled = false;
221     } else if(arg == "--disable-music") {
222       config->music_enabled = false;
223     } else if(arg == "--play-demo") {
224       if(i+1 >= argc) {
225         print_usage(argv[0]);
226         throw std::runtime_error("Need to specify a demo filename");
227       }
228       config->start_demo = argv[++i];
229     } else if(arg == "--record-demo") {
230       if(i+1 >= argc) {
231         print_usage(argv[0]);
232         throw std::runtime_error("Need to specify a demo filename");
233       }
234       config->record_demo = argv[++i];
235     } else if(arg == "--help") {
236       print_usage(argv[0]);
237       throw graceful_shutdown();
238     } else if(arg == "--version") {
239       msg_info(PACKAGE_NAME << " " << PACKAGE_VERSION);
240       throw graceful_shutdown();
241     } else if(arg[0] != '-') {
242       config->start_level = arg;
243     } else {
244       msg_warning("Unknown option '" << arg << "'. Use --help to see a list of options");
245     }
246   }
247
248   // TODO joystick switchyes...
249 }
250
251 static void init_sdl()
252 {
253   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
254     std::stringstream msg;
255     msg << "Couldn't initialize SDL: " << SDL_GetError();
256     throw std::runtime_error(msg.str());
257   }
258
259   SDL_EnableUNICODE(1);
260
261   // wait 100ms and clear SDL event queue because sometimes we have random
262   // joystick events in the queue on startup...
263   SDL_Delay(100);
264   SDL_Event dummy;
265   while(SDL_PollEvent(&dummy))
266       ;
267 }
268
269 static void check_gl_error()
270 {
271   GLenum glerror = glGetError();
272   std::string errormsg;
273   
274   if(glerror != GL_NO_ERROR) {
275     switch(glerror) {
276       case GL_INVALID_ENUM:
277         errormsg = "Invalid enumeration value";
278         break;
279       case GL_INVALID_VALUE:
280         errormsg = "Numeric argzment out of range";
281         break;
282       case GL_INVALID_OPERATION:
283         errormsg = "Invalid operation";
284         break;
285       case GL_STACK_OVERFLOW:
286         errormsg = "stack overflow";
287         break;
288       case GL_STACK_UNDERFLOW:
289         errormsg = "stack underflow";
290         break;
291       case GL_OUT_OF_MEMORY:
292         errormsg = "out of memory";
293         break;
294       case GL_TABLE_TOO_LARGE:
295         errormsg = "table too large";
296         break;
297       default:
298         errormsg = "unknown error number";
299         break;
300     }
301     std::stringstream msg;
302     msg << "OpenGL Error: " << errormsg;
303     throw std::runtime_error(msg.str());
304   }
305 }
306
307 void init_video()
308 {
309   if(texture_manager != NULL)
310     texture_manager->save_textures();
311   
312   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
313   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
314   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
315   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
316   
317   int flags = SDL_OPENGL;
318   if(config->use_fullscreen)
319     flags |= SDL_FULLSCREEN;
320   int width = config->screenwidth;
321   int height = config->screenheight;
322   int bpp = 0;
323
324   screen = SDL_SetVideoMode(width, height, bpp, flags);
325   if(screen == 0) {
326     std::stringstream msg;
327     msg << "Couldn't set video mode (" << width << "x" << height
328         << "-" << bpp << "bpp): " << SDL_GetError();
329     throw std::runtime_error(msg.str());
330   }
331
332   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
333
334   // set icon
335   SDL_Surface* icon = IMG_Load_RW(
336       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
337   if(icon != 0) {
338     SDL_WM_SetIcon(icon, 0);
339     SDL_FreeSurface(icon);
340   }
341 #ifdef DEBUG
342   else {
343     msg_warning("Couldn't find icon 'images/engine/icons/supertux.xpm'");
344   }
345 #endif
346
347   // setup opengl state and transform
348   glDisable(GL_DEPTH_TEST);
349   glDisable(GL_CULL_FACE);
350   glEnable(GL_TEXTURE_2D);
351   glEnable(GL_BLEND);
352   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
353
354   glViewport(0, 0, screen->w, screen->h);
355   glMatrixMode(GL_PROJECTION);
356   glLoadIdentity();
357   // logical resolution here not real monitor resolution
358   glOrtho(0, 800, 600, 0, -1.0, 1.0);
359   glMatrixMode(GL_MODELVIEW);
360   glLoadIdentity();
361   glTranslatef(0, 0, 0);
362
363   check_gl_error();
364
365   if(texture_manager != NULL)
366     texture_manager->reload_textures();
367   else
368     texture_manager = new TextureManager();
369 }
370
371 static void init_audio()
372 {
373   sound_manager = new SoundManager();
374   
375   sound_manager->enable_sound(config->sound_enabled);
376   sound_manager->enable_music(config->music_enabled);
377 }
378
379 static void quit_audio()
380 {
381   if(sound_manager) {
382     delete sound_manager;
383     sound_manager = 0;
384   }
385 }
386
387 void wait_for_event(float min_delay, float max_delay)
388 {
389   assert(min_delay <= max_delay);
390   
391   Uint32 min = (Uint32) (min_delay * 1000);
392   Uint32 max = (Uint32) (max_delay * 1000);
393
394   Uint32 ticks = SDL_GetTicks();
395   while(SDL_GetTicks() - ticks < min) {
396     SDL_Delay(10);
397     sound_manager->update();
398   }
399
400   // clear even queue
401   SDL_Event event;
402   while (SDL_PollEvent(&event))
403   {}
404
405   /* Handle events: */
406   bool running = false;
407   ticks = SDL_GetTicks();
408   while(running) {
409     while(SDL_PollEvent(&event)) {
410       switch(event.type) {
411         case SDL_QUIT:
412           throw graceful_shutdown();
413         case SDL_KEYDOWN:
414         case SDL_JOYBUTTONDOWN:
415         case SDL_MOUSEBUTTONDOWN:
416           running = false;
417       }
418     }
419     if(SDL_GetTicks() - ticks >= (max - min))
420       running = false;
421     sound_manager->update();
422     SDL_Delay(10);
423   }
424 }
425
426 #ifdef DEBUG
427 static Uint32 last_timelog_ticks = 0;
428 static const char* last_timelog_component = 0;
429
430 static inline void timelog(const char* component)
431 {
432   Uint32 current_ticks = SDL_GetTicks();
433   
434   if(last_timelog_component != 0) {
435     msg_info("Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds");
436   }
437
438   last_timelog_ticks = current_ticks;
439   last_timelog_component = component;
440 }
441 #else
442 static inline void timelog(const char* )
443 {
444 }
445 #endif
446
447 int main(int argc, char** argv) 
448 {
449   try {
450     srand(time(0));
451     init_physfs(argv[0]);
452     init_sdl();
453     timelog("controller");
454     main_controller = new JoystickKeyboardController();    
455     timelog("config");
456     init_config();
457     timelog("tinygettext");
458     init_tinygettext();
459     timelog("commandline");
460     parse_commandline(argc, argv);
461     timelog("audio");
462     init_audio();
463     timelog("video");
464     init_video();
465
466     timelog("menu");
467     setup_menu();
468     timelog("resources");
469     load_shared();
470     timelog(0);
471
472     main_loop = new MainLoop(); 
473     if(config->start_level != "") {
474       // we have a normal path specified at commandline not physfs paths.
475       // So we simply mount that path here...
476       std::string dir = FileSystem::dirname(config->start_level);
477       PHYSFS_addToSearchPath(dir.c_str(), true);
478       GameSession* session
479         = new GameSession(
480           FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
481       if(config->start_demo != "")
482         session->play_demo(config->start_demo);
483       if(config->record_demo != "")
484         session->record_demo(config->record_demo);
485       main_loop->push_screen(session);
486     } else {
487       main_loop->push_screen(new TitleScreen());
488     }
489
490     main_loop->run();
491
492     delete main_loop;
493     main_loop = NULL;
494   } catch(graceful_shutdown& e) {
495   } catch(std::exception& e) {
496     msg_fatal("Unexpected exception: " << e.what());
497     return 1;
498   } catch(...) {
499     msg_fatal("Unexpected exception");
500     return 1;
501   }
502
503   free_menu();
504   unload_shared();
505   quit_audio();
506
507   if(config)
508     config->save();
509   delete config;
510   delete main_controller;
511   delete texture_manager;
512   SDL_Quit();
513   PHYSFS_deinit();
514   
515   return 0;
516 }