Added a "graceful exit" exception to be called when the user asks to prematurely...
[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 "main.hpp"
24
25 #include <stdexcept>
26 #include <iostream>
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_mixer.h>
38 #include <SDL_image.h>
39 #include <SDL_opengl.h>
40
41 #include "gameconfig.hpp"
42 #include "resources.hpp"
43 #include "gettext.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "video/surface.hpp"
46 #include "video/texture_manager.hpp"
47 #include "control/joystickkeyboardcontroller.hpp"
48 #include "misc.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 #ifdef DEBUG
66     std::cerr << "Couldn't load config file: " << e.what() << "\n";
67 #endif
68   }
69 }
70
71 static void init_tinygettext()
72 {
73   dictionary_manager.add_directory("locale");
74   dictionary_manager.set_charset("UTF-8");
75 }
76
77 static void init_physfs(const char* argv0)
78 {
79   if(!PHYSFS_init(argv0)) {
80     std::stringstream msg;
81     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
82     throw std::runtime_error(msg.str());
83   }
84
85   // Initialize physfs (this is a slightly modified version of
86   // PHYSFS_setSaneConfig
87   const char* application = PACKAGE_NAME;
88   const char* userdir = PHYSFS_getUserDir();
89   const char* dirsep = PHYSFS_getDirSeparator();
90   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
91
92   // Set configuration directory
93   sprintf(writedir, "%s.%s", userdir, application);
94   if(!PHYSFS_setWriteDir(writedir)) {
95     // try to create the directory
96     char* mkdir = new char[strlen(application) + 2];
97     sprintf(mkdir, ".%s", application);
98     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
99       std::ostringstream msg;
100       msg << "Failed creating configuration directory '" 
101           << writedir << "': " << PHYSFS_getLastError();
102       delete[] writedir;
103       delete[] mkdir;
104       throw std::runtime_error(msg.str());
105     }
106     delete[] mkdir;
107     
108     if(!PHYSFS_setWriteDir(writedir)) {
109       std::ostringstream msg;
110       msg << "Failed to use configuration directory '" 
111           <<  writedir << "': " << PHYSFS_getLastError();
112       delete[] writedir;
113       throw std::runtime_error(msg.str());
114     }
115   }
116   PHYSFS_addToSearchPath(writedir, 0);
117   delete[] writedir;
118
119   // Search for archives and add them to the search path
120   const char* archiveExt = "zip";
121   char** rc = PHYSFS_enumerateFiles("/");
122   size_t extlen = strlen(archiveExt);
123
124   for(char** i = rc; *i != 0; ++i) {
125     size_t l = strlen(*i);
126     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
127       const char* ext = (*i) + (l - extlen);
128       if(strcasecmp(ext, archiveExt) == 0) {
129         const char* d = PHYSFS_getRealDir(*i);
130         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
131         sprintf(str, "%s%s%s", d, dirsep, *i);
132         PHYSFS_addToSearchPath(str, 1);
133         delete[] str;
134       }
135     }
136   }
137   
138   PHYSFS_freeList(rc);
139
140   // when started from source dir...
141   std::string dir = PHYSFS_getBaseDir();
142   dir += "/data";
143   std::string testfname = dir;
144   testfname += "/credits.txt";
145   bool sourcedir = false;
146   FILE* f = fopen(testfname.c_str(), "r");
147   if(f) {
148     fclose(f);
149     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
150       std::cout << "Warning: Couldn't add '" << dir 
151                 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
152     } else {
153       sourcedir = true;
154     }
155   }
156
157   if(!sourcedir) {
158 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
159     std::string datadir;
160 #ifdef ENABLE_BINRELOC
161     char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
162     datadir = brdatadir;
163     free(brdatadir);
164 #else
165     datadir = APPDATADIR;
166 #endif
167     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
168       std::cout << "Couldn't add '" << datadir
169         << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
170     }
171 #endif
172   }
173
174   // allow symbolic links
175   PHYSFS_permitSymbolicLinks(1);
176
177   //show search Path
178   for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
179     printf("[%s] is in the search path.\n", *i);
180 }
181
182 static void print_usage(const char* argv0)
183 {
184   fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
185   fprintf(stderr,
186           _("Options:\n"
187             "  -f, --fullscreen             Run in fullscreen mode\n"
188             "  -w, --window                 Run in window mode\n"
189             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\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 == "--play-demo") {
220       if(i+1 >= argc) {
221         print_usage(argv[0]);
222         throw std::runtime_error("Need to specify a demo filename");
223       }
224       config->start_demo = argv[++i];
225     } else if(arg == "--record-demo") {
226       if(i+1 >= argc) {
227         print_usage(argv[0]);
228         throw std::runtime_error("Need to specify a demo filename");
229       }
230       config->record_demo = argv[++i];
231     } else if(arg == "--help") {
232       print_usage(argv[0]);
233       throw graceful_shutdown();
234     } else if(arg == "--version") {
235       std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
236       throw graceful_shutdown();
237     } else if(arg[0] != '-') {
238       config->start_level = arg;
239     } else {
240       std::cerr << "Unknown option '" << arg << "'.\n";
241       std::cerr << "Use --help to see a list of options.\n";
242     }
243   }
244
245   // TODO joystick switchyes...
246 }
247
248 static void init_sdl()
249 {
250   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
251     std::stringstream msg;
252     msg << "Couldn't initialize SDL: " << SDL_GetError();
253     throw std::runtime_error(msg.str());
254   }
255
256   SDL_EnableUNICODE(1);
257
258   // wait 100ms and clear SDL event queue because sometimes we have random
259   // joystick events in the queue on startup...
260   SDL_Delay(100);
261   SDL_Event dummy;
262   while(SDL_PollEvent(&dummy))
263       ;
264 }
265
266 static void check_gl_error()
267 {
268   GLenum glerror = glGetError();
269   std::string errormsg;
270   
271   if(glerror != GL_NO_ERROR) {
272     switch(glerror) {
273       case GL_INVALID_ENUM:
274         errormsg = "Invalid enumeration value";
275         break;
276       case GL_INVALID_VALUE:
277         errormsg = "Numeric argzment out of range";
278         break;
279       case GL_INVALID_OPERATION:
280         errormsg = "Invalid operation";
281         break;
282       case GL_STACK_OVERFLOW:
283         errormsg = "stack overflow";
284         break;
285       case GL_STACK_UNDERFLOW:
286         errormsg = "stack underflow";
287         break;
288       case GL_OUT_OF_MEMORY:
289         errormsg = "out of memory";
290         break;
291       case GL_TABLE_TOO_LARGE:
292         errormsg = "table too large";
293         break;
294       default:
295         errormsg = "unknown error number";
296         break;
297     }
298     std::stringstream msg;
299     msg << "OpenGL Error: " << errormsg;
300     throw std::runtime_error(msg.str());
301   }
302 }
303
304 void init_video()
305 {
306   if(texture_manager != NULL)
307     texture_manager->save_textures();
308   
309   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
310   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
311   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
312   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
313   
314   int flags = SDL_OPENGL;
315   if(config->use_fullscreen)
316     flags |= SDL_FULLSCREEN;
317   int width = config->screenwidth;
318   int height = config->screenheight;
319   int bpp = 0;
320
321   screen = SDL_SetVideoMode(width, height, bpp, flags);
322   if(screen == 0) {
323     std::stringstream msg;
324     msg << "Couldn't set video mode (" << width << "x" << height
325         << "-" << bpp << "bpp): " << SDL_GetError();
326     throw std::runtime_error(msg.str());
327   }
328
329   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
330
331   // set icon
332   SDL_Surface* icon = IMG_Load_RW(
333       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
334   if(icon != 0) {
335     SDL_WM_SetIcon(icon, 0);
336     SDL_FreeSurface(icon);
337   }
338 #ifdef DEBUG
339   else {
340     std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
341   }
342 #endif
343
344   // setup opengl state and transform
345   glDisable(GL_DEPTH_TEST);
346   glDisable(GL_CULL_FACE);
347   glEnable(GL_TEXTURE_2D);
348   glEnable(GL_BLEND);
349   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
350
351   glViewport(0, 0, screen->w, screen->h);
352   glMatrixMode(GL_PROJECTION);
353   glLoadIdentity();
354   // logical resolution here not real monitor resolution
355   glOrtho(0, 800, 600, 0, -1.0, 1.0);
356   glMatrixMode(GL_MODELVIEW);
357   glLoadIdentity();
358   glTranslatef(0, 0, 0);
359
360   check_gl_error();
361
362   if(texture_manager != NULL)
363     texture_manager->reload_textures();
364   else
365     texture_manager = new TextureManager();
366 }
367
368 static void init_audio()
369 {
370   sound_manager = new SoundManager();
371   
372   sound_manager->enable_sound(config->sound_enabled);
373   sound_manager->enable_music(config->music_enabled);
374 }
375
376 static void quit_audio()
377 {
378   if(sound_manager) {
379     delete sound_manager;
380     sound_manager = 0;
381   }
382 }
383
384 void wait_for_event(float min_delay, float max_delay)
385 {
386   assert(min_delay <= max_delay);
387   
388   Uint32 min = (Uint32) (min_delay * 1000);
389   Uint32 max = (Uint32) (max_delay * 1000);
390
391   Uint32 ticks = SDL_GetTicks();
392   while(SDL_GetTicks() - ticks < min) {
393     SDL_Delay(10);
394     sound_manager->update();
395   }
396
397   // clear even queue
398   SDL_Event event;
399   while (SDL_PollEvent(&event))
400   {}
401
402   /* Handle events: */
403   bool running = false;
404   ticks = SDL_GetTicks();
405   while(running) {
406     while(SDL_PollEvent(&event)) {
407       switch(event.type) {
408         case SDL_QUIT:
409           throw graceful_shutdown();
410         case SDL_KEYDOWN:
411         case SDL_JOYBUTTONDOWN:
412         case SDL_MOUSEBUTTONDOWN:
413           running = false;
414       }
415     }
416     if(SDL_GetTicks() - ticks >= (max - min))
417       running = false;
418     sound_manager->update();
419     SDL_Delay(10);
420   }
421 }
422
423 int main(int argc, char** argv) 
424 {
425   try {
426     srand(time(0));
427     init_physfs(argv[0]);
428     init_sdl();
429     main_controller = new JoystickKeyboardController();    
430     init_config();
431     init_tinygettext();
432     parse_commandline(argc, argv);
433     init_audio();
434     init_video();
435
436     setup_menu();
437     load_shared();
438     if(config->start_level != "") {
439       // we have a normal path specified at commandline not physfs paths.
440       // So we simply mount that path here...
441       std::string dir = FileSystem::dirname(config->start_level);
442       PHYSFS_addToSearchPath(dir.c_str(), true);
443       GameSession session(
444           FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
445       if(config->start_demo != "")
446         session.play_demo(config->start_demo);
447       if(config->record_demo != "")
448         session.record_demo(config->record_demo);
449       session.run();
450     } else {
451       // normal game
452       title();
453     }
454   } catch(graceful_shutdown& e) {
455   } catch(std::exception& e) {
456     std::cerr << "Unexpected exception: " << e.what() << std::endl;
457     return 1;
458   } catch(...) {
459     std::cerr << "Unexpected exception." << std::endl;
460     return 1;
461   }
462
463   free_menu();
464   unload_shared();
465   quit_audio();
466
467   if(config)
468     config->save();
469   delete config;
470   delete main_controller;
471   delete texture_manager;
472   SDL_Quit();
473   PHYSFS_deinit();
474   
475   return 0;
476 }