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