fix for my latest commit
[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.h"
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 #ifndef WIN32
36 #include <libgen.h>
37 #endif
38 #include <SDL.h>
39 #include <SDL_mixer.h>
40 #include <SDL_image.h>
41 #include <SDL_opengl.h>
42
43 #include "gameconfig.h"
44 #include "resources.h"
45 #include "gettext.h"
46 #include "audio/sound_manager.h"
47 #include "video/surface.h"
48 #include "control/joystickkeyboardcontroller.h"
49 #include "misc.h"
50 #include "title.h"
51 #include "game_session.h"
52 #include "file_system.h"
53
54 #ifdef WIN32
55 #define mkdir(dir, mode)    mkdir(dir)
56 #endif
57
58 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
61
62 static void init_config()
63 {
64   config = new Config();
65   try {
66     config->load();
67   } catch(std::exception& e) {
68 #ifdef DEBUG
69     std::cerr << "Couldn't load config file: " << e.what() << "\n";
70 #endif
71   }
72 }
73
74 static void find_directories()
75 {
76   const char* home = getenv("HOME");
77   if(home == 0) {
78 #ifdef DEBUG
79     std::cerr << "Couldn't find home directory.\n";
80 #endif
81     home = ".";
82   }
83
84   user_dir = home;
85   user_dir += "/.supertux";
86
87   // create directories
88   std::string savedir = user_dir + "/save";
89   mkdir(user_dir.c_str(), 0755);
90   mkdir(savedir.c_str(), 0755);
91
92   // try current directory as datadir
93   if(datadir.empty()) {
94     if(FileSystem::faccessible("./data/credits.txt")) {
95       datadir = "./data/";
96     }
97   }
98
99   // Detect datadir with some linux magic
100   if(datadir.empty()) {
101     std::string exedir;
102 #ifdef WIN32
103     exedir = ".";
104 #else
105     char exe_file[PATH_MAX];
106     if(readlink("/proc/self/exe", exe_file, PATH_MAX) >= 0) {
107       exedir = std::string(dirname(exe_file));
108     } else {
109 #ifdef DEBUG
110       std::cerr << "Couldn't read /proc/self/exe \n";
111 #endif
112       exedir = ".";
113     }
114 #endif
115     std::string testdir = exedir + "/data/";
116     if(access(testdir.c_str(), F_OK) == 0) {
117       datadir = testdir;
118     }
119     
120     testdir = exedir + "/../share/supertux/";
121     if(datadir.empty() && access(testdir.c_str(), F_OK) == 0) {
122       datadir = testdir;
123     }
124   }  
125   
126 #ifdef DATA_PREFIX
127   // use default location
128   if(datadir.empty()) {
129     datadir = DATA_PREFIX;
130   }
131 #endif
132
133   if(datadir.empty())
134     throw std::runtime_error("Couldn't find datadir");
135 }
136
137 static void init_tinygettext()
138 {
139   dictionary_manager.add_directory(datadir + "/locale");
140   dictionary_manager.set_charset("UTF-8");
141 }
142
143 static void print_usage(const char* argv0)
144 {
145   fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
146   fprintf(stderr,
147           _("Options:\n"
148             "  -f, --fullscreen             Run in fullscreen mode.\n"
149             "  -w, --window                 Run in window mode.\n"
150             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in give resolution\n"
151             "  --help                       Show this help message\n"
152             "  --version                    Display SuperTux version and quit\n"
153             "\n"));
154 }
155
156 static void parse_commandline(int argc, char** argv)
157 {
158   for(int i = 1; i < argc; ++i) {
159     std::string arg = argv[i];
160
161     if(arg == "--fullscreen" || arg == "-f") {
162       config->use_fullscreen = true;
163     } else if(arg == "--window" || arg == "-w") {
164       config->use_fullscreen = false;
165     } else if(arg == "--geometry" || arg == "-g") {
166       if(i+1 >= argc) {
167         print_usage(argv[0]);
168         throw std::runtime_error("Need to specify a parameter for geometry switch");
169       }
170       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
171          != 2) {
172         print_usage(argv[0]);
173         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
174       }
175     } else if(arg == "--show-fps") {
176       config->show_fps = true;
177     } else if(arg == "--play-demo") {
178       if(i+1 >= argc) {
179         print_usage(argv[0]);
180         throw std::runtime_error("Need to specify a demo filename");
181       }
182       config->start_demo = argv[++i];
183     } else if(arg == "--record-demo") {
184       if(i+1 >= argc) {
185         print_usage(argv[0]);
186         throw std::runtime_error("Need to specify a demo filename");
187       }
188       config->record_demo = argv[++i];
189     } else if(arg == "--help") {
190       print_usage(argv[0]);
191       throw std::runtime_error("");
192     } else if(arg == "--version") {
193       std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
194       throw std::runtime_error("");
195     } else if(arg[0] != '-') {
196       config->start_level = arg;
197     } else {
198       std::cerr << "Unknown option '" << arg << "'.\n";
199       std::cerr << "Use --help to see a list of options.\n";
200     }
201   }
202
203   // TODO joystick switchyes...
204 }
205
206 static void init_sdl()
207 {
208   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
209     std::stringstream msg;
210     msg << "Couldn't initialize SDL: " << SDL_GetError();
211     throw std::runtime_error(msg.str());
212   }
213
214   SDL_EnableUNICODE(1);
215
216   // wait 100ms and clear SDL event queue because sometimes we have random
217   // joystick events in the queue on startup...
218   SDL_Delay(100);
219   SDL_Event dummy;
220   while(SDL_PollEvent(&dummy))
221       ;
222 }
223
224 static void check_gl_error()
225 {
226   GLenum glerror = glGetError();
227   std::string errormsg;
228   
229   if(glerror != GL_NO_ERROR) {
230     switch(glerror) {
231       case GL_INVALID_ENUM:
232         errormsg = "Invalid enumeration value";
233         break;
234       case GL_INVALID_VALUE:
235         errormsg = "Numeric argzment out of range";
236         break;
237       case GL_INVALID_OPERATION:
238         errormsg = "Invalid operation";
239         break;
240       case GL_STACK_OVERFLOW:
241         errormsg = "stack overflow";
242         break;
243       case GL_STACK_UNDERFLOW:
244         errormsg = "stack underflow";
245         break;
246       case GL_OUT_OF_MEMORY:
247         errormsg = "out of memory";
248         break;
249       case GL_TABLE_TOO_LARGE:
250         errormsg = "table too large";
251         break;
252       default:
253         errormsg = "unknown error number";
254         break;
255     }
256     std::stringstream msg;
257     msg << "OpenGL Error: " << errormsg;
258     throw std::runtime_error(msg.str());
259   }
260 }
261
262 void init_video()
263 {
264   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
265   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
266   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
267   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
268   
269   int flags = SDL_OPENGL;
270   if(config->use_fullscreen)
271     flags |= SDL_FULLSCREEN;
272   int width = config->screenwidth;
273   int height = config->screenheight;
274   int bpp = 0;
275
276   screen = SDL_SetVideoMode(width, height, bpp, flags);
277   if(screen == 0) {
278     std::stringstream msg;
279     msg << "Couldn't set video mode (" << width << "x" << height
280         << "-" << bpp << "bpp): " << SDL_GetError();
281     throw std::runtime_error(msg.str());
282   }
283
284   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
285
286   // set icon
287   SDL_Surface* icon = IMG_Load(
288     get_resource_filename("images/engine/icons/supertux.xpm").c_str());
289   if(icon != 0) {
290     SDL_WM_SetIcon(icon, 0);
291     SDL_FreeSurface(icon);
292   }
293 #ifdef DEBUG
294   else {
295     std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
296   }
297 #endif
298
299   // setup opengl state and transform
300   glDisable(GL_DEPTH_TEST);
301   glDisable(GL_CULL_FACE);
302
303   glViewport(0, 0, screen->w, screen->h);
304   glMatrixMode(GL_PROJECTION);
305   glLoadIdentity();
306   // logical resolution here not real monitor resolution
307   glOrtho(0, 800, 600, 0, -1.0, 1.0);
308   glMatrixMode(GL_MODELVIEW);
309   glLoadIdentity();
310   glTranslatef(0, 0, 0);
311
312   check_gl_error();
313
314   Surface::reload_all();
315 }
316
317 static void init_audio()
318 {
319   sound_manager = new SoundManager();
320   
321   int format = MIX_DEFAULT_FORMAT;
322   if(Mix_OpenAudio(config->audio_frequency, format, config->audio_channels,
323                    config->audio_chunksize) < 0) {
324     std::cerr << "Couldn't initialize audio ("
325               << config->audio_frequency << "HZ, " << config->audio_channels
326               << " Channels, Format " << format << ", ChunkSize "
327               << config->audio_chunksize << "): " << SDL_GetError() << "\n";
328     return;
329   }
330   sound_manager->set_audio_device_available(true);
331   sound_manager->enable_sound(config->sound_enabled);
332   sound_manager->enable_music(config->music_enabled);
333   
334   if(Mix_AllocateChannels(config->audio_voices) < 0) {
335     std::cerr << "Couldn't allocate '" << config->audio_voices << "' audio voices: "
336               << SDL_GetError() << "\n";
337     return;
338   }
339 }
340
341 static void quit_audio()
342 {
343   if(sound_manager) {
344     if(sound_manager->audio_device_available())
345       Mix_CloseAudio();
346
347     delete sound_manager;
348     sound_manager = 0;
349   }
350 }
351
352 void wait_for_event(float min_delay, float max_delay)
353 {
354   assert(min_delay <= max_delay);
355   
356   Uint32 min = (Uint32) (min_delay * 1000);
357   Uint32 max = (Uint32) (max_delay * 1000);
358
359   SDL_Delay(min);
360
361   // clear even queue
362   SDL_Event event;
363   while (SDL_PollEvent(&event))
364   {}
365
366   /* Handle events: */
367   bool running = false;
368   Uint32 ticks = SDL_GetTicks();
369   while(running) {
370     while(SDL_PollEvent(&event)) {
371       switch(event.type) {
372         case SDL_QUIT:
373           throw std::runtime_error("received window close");
374         case SDL_KEYDOWN:
375         case SDL_JOYBUTTONDOWN:
376         case SDL_MOUSEBUTTONDOWN:
377           running = false;
378       }
379     }
380     if(SDL_GetTicks() - ticks >= (max - min))
381       running = false;
382     SDL_Delay(10);
383   }
384 }
385
386 int main(int argc, char** argv) 
387 {
388 #ifndef DEBUG // we want backtraces in debug mode so don't catch exceptions
389   try {
390 #endif
391     srand(time(0));
392     init_sdl();
393     main_controller = new JoystickKeyboardController();    
394     find_directories();
395     init_config();
396     init_tinygettext();
397     parse_commandline(argc, argv);
398     init_audio();
399     init_video();
400
401     setup_menu();
402     load_shared();
403     if(config->start_level != "") {
404       GameSession session(config->start_level, ST_GL_LOAD_LEVEL_FILE);
405       if(config->start_demo != "")
406         session.play_demo(config->start_demo);
407       if(config->record_demo != "")
408         session.record_demo(config->record_demo);
409       session.run();
410     } else {
411       // normal game
412       title();
413     }    
414     
415 #ifndef DEBUG
416   } catch(std::exception& e) {
417     std::cerr << "Unexpected exception: " << e.what() << std::endl;
418     return 1;
419   } catch(...) {
420     std::cerr << "Unexpected exception." << std::endl;
421     return 1;
422   }
423 #endif
424
425   free_menu();
426   unload_shared();
427 #ifdef DEBUG
428   Surface::debug_check();
429 #endif
430   quit_audio();
431
432   if(config)
433     config->save();
434   delete config;
435   delete main_controller;
436   SDL_Quit();
437   
438   return 0;
439 }