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