8874b003e505fc72fcc370b0ccf415f786091f84
[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 "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     msg_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       msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
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       msg_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
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     msg_info << "[" << *i << "] is in the search path" << std::endl;
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 bool 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       return true;
239     } else if(arg == "--version") {
240       msg_info << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
241       return true;
242     } else if(arg[0] != '-') {
243       config->start_level = arg;
244     } else {
245       msg_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
246     }
247   }
248
249   return false;
250 }
251
252 static void init_sdl()
253 {
254   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
255     std::stringstream msg;
256     msg << "Couldn't initialize SDL: " << SDL_GetError();
257     throw std::runtime_error(msg.str());
258   }
259
260   SDL_EnableUNICODE(1);
261
262   // wait 100ms and clear SDL event queue because sometimes we have random
263   // joystick events in the queue on startup...
264   SDL_Delay(100);
265   SDL_Event dummy;
266   while(SDL_PollEvent(&dummy))
267       ;
268 }
269
270 static void check_gl_error()
271 {
272   GLenum glerror = glGetError();
273   std::string errormsg;
274   
275   if(glerror != GL_NO_ERROR) {
276     switch(glerror) {
277       case GL_INVALID_ENUM:
278         errormsg = "Invalid enumeration value";
279         break;
280       case GL_INVALID_VALUE:
281         errormsg = "Numeric argzment out of range";
282         break;
283       case GL_INVALID_OPERATION:
284         errormsg = "Invalid operation";
285         break;
286       case GL_STACK_OVERFLOW:
287         errormsg = "stack overflow";
288         break;
289       case GL_STACK_UNDERFLOW:
290         errormsg = "stack underflow";
291         break;
292       case GL_OUT_OF_MEMORY:
293         errormsg = "out of memory";
294         break;
295       case GL_TABLE_TOO_LARGE:
296         errormsg = "table too large";
297         break;
298       default:
299         errormsg = "unknown error number";
300         break;
301     }
302     std::stringstream msg;
303     msg << "OpenGL Error: " << errormsg;
304     throw std::runtime_error(msg.str());
305   }
306 }
307
308 void init_video()
309 {
310   if(texture_manager != NULL)
311     texture_manager->save_textures();
312   
313   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
314   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
315   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
316   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
317   
318   int flags = SDL_OPENGL;
319   if(config->use_fullscreen)
320     flags |= SDL_FULLSCREEN;
321   int width = config->screenwidth;
322   int height = config->screenheight;
323   int bpp = 0;
324
325   screen = SDL_SetVideoMode(width, height, bpp, flags);
326   if(screen == 0) {
327     std::stringstream msg;
328     msg << "Couldn't set video mode (" << width << "x" << height
329         << "-" << bpp << "bpp): " << SDL_GetError();
330     throw std::runtime_error(msg.str());
331   }
332
333   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
334
335   // set icon
336   SDL_Surface* icon = IMG_Load_RW(
337       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
338   if(icon != 0) {
339     SDL_WM_SetIcon(icon, 0);
340     SDL_FreeSurface(icon);
341   }
342 #ifdef DEBUG
343   else {
344     msg_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
345   }
346 #endif
347
348   // setup opengl state and transform
349   glDisable(GL_DEPTH_TEST);
350   glDisable(GL_CULL_FACE);
351   glEnable(GL_TEXTURE_2D);
352   glEnable(GL_BLEND);
353   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
354
355   glViewport(0, 0, screen->w, screen->h);
356   glMatrixMode(GL_PROJECTION);
357   glLoadIdentity();
358   // logical resolution here not real monitor resolution
359   glOrtho(0, 800, 600, 0, -1.0, 1.0);
360   glMatrixMode(GL_MODELVIEW);
361   glLoadIdentity();
362   glTranslatef(0, 0, 0);
363
364   check_gl_error();
365
366   if(texture_manager != NULL)
367     texture_manager->reload_textures();
368   else
369     texture_manager = new TextureManager();
370 }
371
372 static void init_audio()
373 {
374   sound_manager = new SoundManager();
375   
376   sound_manager->enable_sound(config->sound_enabled);
377   sound_manager->enable_music(config->music_enabled);
378 }
379
380 static void init_scripting()
381 {
382   script_manager = new ScriptManager();
383
384   HSQUIRRELVM vm = script_manager->get_global_vm();
385   sq_pushroottable(vm); 
386   expose_object(vm, -1, new Scripting::Sound(), "Sound", true);
387   expose_object(vm, -1, new Scripting::Level(), "Level", true);
388   sq_pop(vm, 1);
389 }
390
391 static void quit_audio()
392 {
393   if(sound_manager != NULL) {
394     delete sound_manager;
395     sound_manager = NULL;
396   }
397 }
398
399 void wait_for_event(float min_delay, float max_delay)
400 {
401   assert(min_delay <= max_delay);
402   
403   Uint32 min = (Uint32) (min_delay * 1000);
404   Uint32 max = (Uint32) (max_delay * 1000);
405
406   Uint32 ticks = SDL_GetTicks();
407   while(SDL_GetTicks() - ticks < min) {
408     SDL_Delay(10);
409     sound_manager->update();
410   }
411
412   // clear event queue
413   SDL_Event event;
414   while (SDL_PollEvent(&event))
415   {}
416
417   /* Handle events: */
418   bool running = false;
419   ticks = SDL_GetTicks();
420   while(running) {
421     while(SDL_PollEvent(&event)) {
422       switch(event.type) {
423         case SDL_QUIT:
424           main_loop->quit();
425           break;
426         case SDL_KEYDOWN:
427         case SDL_JOYBUTTONDOWN:
428         case SDL_MOUSEBUTTONDOWN:
429           running = false;
430       }
431     }
432     if(SDL_GetTicks() - ticks >= (max - min))
433       running = false;
434     sound_manager->update();
435     SDL_Delay(10);
436   }
437 }
438
439 #ifdef DEBUG
440 static Uint32 last_timelog_ticks = 0;
441 static const char* last_timelog_component = 0;
442
443 static inline void timelog(const char* component)
444 {
445   Uint32 current_ticks = SDL_GetTicks();
446   
447   if(last_timelog_component != 0) {
448     msg_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
449   }
450
451   last_timelog_ticks = current_ticks;
452   last_timelog_component = component;
453 }
454 #else
455 static inline void timelog(const char* )
456 {
457 }
458 #endif
459
460 int main(int argc, char** argv) 
461 {
462   try {
463     srand(time(0));
464     init_physfs(argv[0]);
465     init_sdl();
466     timelog("controller");
467     main_controller = new JoystickKeyboardController();    
468     timelog("config");
469     init_config();
470     timelog("tinygettext");
471     init_tinygettext();
472     timelog("commandline");
473     if(parse_commandline(argc, argv))
474       return 0;
475     timelog("audio");
476     init_audio();
477     timelog("video");
478     init_video();
479     timelog("scripting");
480     init_scripting();
481
482     timelog("menu");
483     setup_menu();
484     timelog("resources");
485     load_shared();
486     timelog(0);
487
488     main_loop = new MainLoop(); 
489     if(config->start_level != "") {
490       // we have a normal path specified at commandline not physfs paths.
491       // So we simply mount that path here...
492       std::string dir = FileSystem::dirname(config->start_level);
493       PHYSFS_addToSearchPath(dir.c_str(), true);
494       GameSession* session
495         = new GameSession(
496           FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
497       if(config->start_demo != "")
498         session->play_demo(config->start_demo);
499       if(config->record_demo != "")
500         session->record_demo(config->record_demo);
501       main_loop->push_screen(session);
502     } else {
503       main_loop->push_screen(new TitleScreen());
504     }
505
506     main_loop->run();
507
508     delete main_loop;
509     main_loop = NULL;
510   } catch(std::exception& e) {
511     msg_fatal << "Unexpected exception: " << e.what() << std::endl;
512     return 1;
513   } catch(...) {
514     msg_fatal << "Unexpected exception" << std::endl;
515     return 1;
516   }
517
518   free_menu();
519   delete script_manager;
520   script_manager = NULL;
521   printf("crashunloadshared?\n");
522   unload_shared();
523   quit_audio();
524
525   if(config)
526     config->save();
527   delete config;
528   config = NULL;
529   delete main_controller;
530   main_controller = NULL;
531   delete texture_manager;
532   texture_manager = NULL;
533   SDL_Quit();
534   PHYSFS_deinit();
535   
536   return 0;
537 }