17bd43185e5d72345209a039e898b4b8e4c06ad8
[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 <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <physfs.h>
34 #include <SDL.h>
35 #include <SDL_image.h>
36 #include <GL/gl.h>
37
38 #include "gameconfig.hpp"
39 #include "resources.hpp"
40 #include "gettext.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "video/surface.hpp"
43 #include "video/texture_manager.hpp"
44 #include "video/glutil.hpp"
45 #include "control/joystickkeyboardcontroller.hpp"
46 #include "options_menu.hpp"
47 #include "mainloop.hpp"
48 #include "title.hpp"
49 #include "game_session.hpp"
50 #include "scripting/level.hpp"
51 #include "scripting/squirrel_util.hpp"
52 #include "file_system.hpp"
53 #include "physfs/physfs_sdl.hpp"
54 #include "random_generator.hpp"
55 #include "worldmap/worldmap.hpp"
56 #include "binreloc/binreloc.h"
57
58 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
61
62 int SCREEN_WIDTH;
63 int SCREEN_HEIGHT;
64
65 static void init_config()
66 {
67   config = new Config();
68   try {
69     config->load();
70   } catch(std::exception& e) {
71     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
72   }
73 }
74
75 static void init_tinygettext()
76 {
77   dictionary_manager.add_directory("locale");
78   dictionary_manager.set_charset("UTF-8");
79 }
80
81 static void init_physfs(const char* argv0)
82 {
83   if(!PHYSFS_init(argv0)) {
84     std::stringstream msg;
85     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
86     throw std::runtime_error(msg.str());
87   }
88
89   // Initialize physfs (this is a slightly modified version of
90   // PHYSFS_setSaneConfig
91   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
92   const char* userdir = PHYSFS_getUserDir();
93   const char* dirsep = PHYSFS_getDirSeparator();
94   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
95
96   // Set configuration directory
97   sprintf(writedir, "%s.%s", userdir, application);
98   if(!PHYSFS_setWriteDir(writedir)) {
99     // try to create the directory
100     char* mkdir = new char[strlen(application) + 2];
101     sprintf(mkdir, ".%s", application);
102     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
103       std::ostringstream msg;
104       msg << "Failed creating configuration directory '"
105           << writedir << "': " << PHYSFS_getLastError();
106       delete[] writedir;
107       delete[] mkdir;
108       throw std::runtime_error(msg.str());
109     }
110     delete[] mkdir;
111
112     if(!PHYSFS_setWriteDir(writedir)) {
113       std::ostringstream msg;
114       msg << "Failed to use configuration directory '"
115           <<  writedir << "': " << PHYSFS_getLastError();
116       delete[] writedir;
117       throw std::runtime_error(msg.str());
118     }
119   }
120   PHYSFS_addToSearchPath(writedir, 0);
121   delete[] writedir;
122
123   // Search for archives and add them to the search path
124   const char* archiveExt = "zip";
125   char** rc = PHYSFS_enumerateFiles("/");
126   size_t extlen = strlen(archiveExt);
127
128   for(char** i = rc; *i != 0; ++i) {
129     size_t l = strlen(*i);
130     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
131       const char* ext = (*i) + (l - extlen);
132       if(strcasecmp(ext, archiveExt) == 0) {
133         const char* d = PHYSFS_getRealDir(*i);
134         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
135         sprintf(str, "%s%s%s", d, dirsep, *i);
136         PHYSFS_addToSearchPath(str, 1);
137         delete[] str;
138       }
139     }
140   }
141
142   PHYSFS_freeList(rc);
143
144   // when started from source dir...
145   std::string dir = PHYSFS_getBaseDir();
146   dir += "/data";
147   std::string testfname = dir;
148   testfname += "/credits.txt";
149   bool sourcedir = false;
150   FILE* f = fopen(testfname.c_str(), "r");
151   if(f) {
152     fclose(f);
153     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
154       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
155     } else {
156       sourcedir = true;
157     }
158   }
159
160 #ifdef MACOSX
161   // when started from Application file on Mac OS X...
162   dir = PHYSFS_getBaseDir();
163   dir += "SuperTux.app/Contents/Resources/data";
164   testfname = dir + "/credits.txt";
165   sourcedir = false;
166   f = fopen(testfname.c_str(), "r");
167   if(f) {
168     fclose(f);
169     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
170       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
171     } else {
172       sourcedir = true;
173     }
174   }
175 #endif
176
177 #ifdef _WIN32
178   PHYSFS_addToSearchPath(".\\data", 1);
179 #endif
180
181   if(!sourcedir) {
182 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
183     std::string datadir;
184 #ifdef ENABLE_BINRELOC
185
186     char* dir;
187     br_init (NULL);
188     dir = br_find_data_dir(APPDATADIR);
189     datadir = dir;
190     datadir += "/" PACKAGE_NAME;
191     free(dir);
192
193 #else
194     datadir = APPDATADIR;
195 #endif
196     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
197       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
198     }
199 #endif
200   }
201
202   // allow symbolic links
203   PHYSFS_permitSymbolicLinks(1);
204
205   //show search Path
206   char** searchpath = PHYSFS_getSearchPath();
207   for(char** i = searchpath; *i != NULL; i++)
208     log_info << "[" << *i << "] is in the search path" << std::endl;
209   PHYSFS_freeList(searchpath);
210 }
211
212 static void print_usage(const char* argv0)
213 {
214   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
215   fprintf(stderr,
216           _("Options:\n"
217             "  -f, --fullscreen             Run in fullscreen mode\n"
218             "  -w, --window                 Run in window mode\n"
219             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
220             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
221             "  --disable-sfx                Disable sound effects\n"
222             "  --disable-music              Disable music\n"
223             "  --help                       Show this help message\n"
224             "  --version                    Display SuperTux version and quit\n"
225             "  --console                    Enable ingame scripting console\n"
226             "  --noconsole                  Disable ingame scripting console\n"
227             "  --show-fps                   Display framerate in levels\n"
228             "  --no-show-fps                Do not display framerate in levels\n"
229             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
230             "  --play-demo FILE LEVEL       Play a recorded demo\n"
231             "\n"));
232 }
233
234 /**
235  * Options that should be evaluated prior to any initializations at all go here
236  */
237 static bool pre_parse_commandline(int argc, char** argv)
238 {
239   for(int i = 1; i < argc; ++i) {
240     std::string arg = argv[i];
241
242     if(arg == "--help") {
243       print_usage(argv[0]);
244       return true;
245     } else if(arg == "--version") {
246       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
247       return true;
248     }
249   }
250
251   return false;
252 }
253
254 /**
255  * Options that should be evaluated after config is read go here
256  */
257 static bool parse_commandline(int argc, char** argv)
258 {
259   for(int i = 1; i < argc; ++i) {
260     std::string arg = argv[i];
261
262     if(arg == "--fullscreen" || arg == "-f") {
263       config->use_fullscreen = true;
264     } else if(arg == "--window" || arg == "-w") {
265       config->use_fullscreen = false;
266     } else if(arg == "--geometry" || arg == "-g") {
267       if(i+1 >= argc) {
268         print_usage(argv[0]);
269         throw std::runtime_error("Need to specify a parameter for geometry switch");
270       }
271       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
272          != 2) {
273         print_usage(argv[0]);
274         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
275       }
276     } else if(arg == "--aspect" || arg == "-a") {
277       if(i+1 >= argc) {
278         print_usage(argv[0]);
279         throw std::runtime_error("Need to specify a parameter for aspect switch");
280       }
281       if(strcasecmp(argv[i], "auto") == 0) {
282         config->aspect_ratio = -1;
283       } else {
284         int aspect_width, aspect_height;
285         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
286           print_usage(argv[0]);
287           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
288         }
289         config->aspect_ratio = static_cast<double>(aspect_width) /
290                                static_cast<double>(aspect_height);
291       }
292     } else if(arg == "--show-fps") {
293       config->show_fps = true;
294     } else if(arg == "--no-show-fps") {
295       config->show_fps = false;
296     } else if(arg == "--console") {
297       config->console_enabled = true;
298     } else if(arg == "--noconsole") {
299       config->console_enabled = false;
300     } else if(arg == "--disable-sfx") {
301       config->sound_enabled = false;
302     } else if(arg == "--disable-music") {
303       config->music_enabled = false;
304     } else if(arg == "--play-demo") {
305       if(i+1 >= argc) {
306         print_usage(argv[0]);
307         throw std::runtime_error("Need to specify a demo filename");
308       }
309       config->start_demo = argv[++i];
310     } else if(arg == "--record-demo") {
311       if(i+1 >= argc) {
312         print_usage(argv[0]);
313         throw std::runtime_error("Need to specify a demo filename");
314       }
315       config->record_demo = argv[++i];
316     } else if(arg == "-d") {
317       config->enable_script_debugger = true;
318     } else if(arg[0] != '-') {
319       config->start_level = arg;
320     } else {
321       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
322       return true;
323     }
324   }
325
326   return false;
327 }
328
329 static void init_sdl()
330 {
331   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
332     std::stringstream msg;
333     msg << "Couldn't initialize SDL: " << SDL_GetError();
334     throw std::runtime_error(msg.str());
335   }
336   // just to be sure
337   atexit(SDL_Quit);
338
339   SDL_EnableUNICODE(1);
340
341   // wait 100ms and clear SDL event queue because sometimes we have random
342   // joystick events in the queue on startup...
343   SDL_Delay(100);
344   SDL_Event dummy;
345   while(SDL_PollEvent(&dummy))
346       ;
347 }
348
349 static void init_rand()
350 {
351   config->random_seed = systemRandom.srand(config->random_seed);
352
353   //const char *how = config->random_seed? ", user fixed.": ", from time().";
354   //log_info << "Using random seed " << config->random_seed << how << std::endl;
355 }
356
357 void init_video()
358 {
359   static int desktop_width = 0;
360   static int desktop_height = 0;
361
362   if(texture_manager != NULL)
363     texture_manager->save_textures();
364
365 /* unfortunately only newer SDLs have these infos */
366 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
367   /* find which resolution the user normally uses */
368   if(desktop_width == 0) {
369     const SDL_VideoInfo *info = SDL_GetVideoInfo();
370     desktop_width  = info->current_w;
371     desktop_height = info->current_h;
372   }
373
374   /* we want vsync for smooth scrolling */
375   SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
376 #endif
377
378   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
379   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
380   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
381   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
382
383   int flags = SDL_OPENGL;
384   if(config->use_fullscreen)
385     flags |= SDL_FULLSCREEN;
386   int width = config->screenwidth;
387   int height = config->screenheight;
388   int bpp = 0;
389
390   screen = SDL_SetVideoMode(width, height, bpp, flags);
391   if(screen == 0) {
392     std::stringstream msg;
393     msg << "Couldn't set video mode (" << width << "x" << height
394         << "-" << bpp << "bpp): " << SDL_GetError();
395     throw std::runtime_error(msg.str());
396   }
397
398   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
399
400   // set icon
401   SDL_Surface* icon = IMG_Load_RW(
402       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
403   if(icon != 0) {
404     SDL_WM_SetIcon(icon, 0);
405     SDL_FreeSurface(icon);
406   }
407 #ifdef DEBUG
408   else {
409     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
410   }
411 #endif
412
413   double aspect_ratio = config->aspect_ratio;
414
415   // try to guess aspect ratio of monitor if needed
416   if (aspect_ratio <= 0) {
417     if(desktop_width > 0) {
418       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
419     } else {
420       aspect_ratio = 4.0 / 3.0;
421     }
422   }
423
424   // use aspect ratio to calculate logical resolution
425   if (aspect_ratio > 1) {
426         SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio);
427         SCREEN_HEIGHT = 600;
428   } else {
429         SCREEN_WIDTH  = 600;
430         SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio);
431   }
432
433   // setup opengl state and transform
434   glDisable(GL_DEPTH_TEST);
435   glDisable(GL_CULL_FACE);
436   glEnable(GL_TEXTURE_2D);
437   glEnable(GL_BLEND);
438   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
439
440   glViewport(0, 0, screen->w, screen->h);
441   glMatrixMode(GL_PROJECTION);
442   glLoadIdentity();
443   // logical resolution here not real monitor resolution
444   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
445   glMatrixMode(GL_MODELVIEW);
446   glLoadIdentity();
447   glTranslatef(0, 0, 0);
448
449   check_gl_error("Setting up view matrices");
450
451   if(texture_manager != NULL)
452     texture_manager->reload_textures();
453   else
454     texture_manager = new TextureManager();
455 }
456
457 static void init_audio()
458 {
459   sound_manager = new SoundManager();
460
461   sound_manager->enable_sound(config->sound_enabled);
462   sound_manager->enable_music(config->music_enabled);
463 }
464
465 static void quit_audio()
466 {
467   if(sound_manager != NULL) {
468     delete sound_manager;
469     sound_manager = NULL;
470   }
471 }
472
473 void wait_for_event(float min_delay, float max_delay)
474 {
475   assert(min_delay <= max_delay);
476
477   Uint32 min = (Uint32) (min_delay * 1000);
478   Uint32 max = (Uint32) (max_delay * 1000);
479
480   Uint32 ticks = SDL_GetTicks();
481   while(SDL_GetTicks() - ticks < min) {
482     SDL_Delay(10);
483     sound_manager->update();
484   }
485
486   // clear event queue
487   SDL_Event event;
488   while (SDL_PollEvent(&event))
489   {}
490
491   /* Handle events: */
492   bool running = false;
493   ticks = SDL_GetTicks();
494   while(running) {
495     while(SDL_PollEvent(&event)) {
496       switch(event.type) {
497         case SDL_QUIT:
498           main_loop->quit();
499           break;
500         case SDL_KEYDOWN:
501         case SDL_JOYBUTTONDOWN:
502         case SDL_MOUSEBUTTONDOWN:
503           running = false;
504       }
505     }
506     if(SDL_GetTicks() - ticks >= (max - min))
507       running = false;
508     sound_manager->update();
509     SDL_Delay(10);
510   }
511 }
512
513 #ifdef DEBUG
514 static Uint32 last_timelog_ticks = 0;
515 static const char* last_timelog_component = 0;
516
517 static inline void timelog(const char* component)
518 {
519   Uint32 current_ticks = SDL_GetTicks();
520
521   if(last_timelog_component != 0) {
522     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
523   }
524
525   last_timelog_ticks = current_ticks;
526   last_timelog_component = component;
527 }
528 #else
529 static inline void timelog(const char* )
530 {
531 }
532 #endif
533
534 int main(int argc, char** argv)
535 {
536   int result = 0;
537
538 #ifndef NO_CATCH
539   try {
540 #endif
541
542     if(pre_parse_commandline(argc, argv))
543       return 0;
544
545     Console::instance = new Console();
546     init_physfs(argv[0]);
547     init_sdl();
548
549     timelog("controller");
550     main_controller = new JoystickKeyboardController();
551     timelog("config");
552     init_config();
553     timelog("tinygettext");
554     init_tinygettext();
555     timelog("commandline");
556     if(parse_commandline(argc, argv))
557       return 0;
558     timelog("audio");
559     init_audio();
560     timelog("video");
561     init_video();
562     Console::instance->init_graphics();
563     timelog("scripting");
564     Scripting::init_squirrel(config->enable_script_debugger);
565     timelog("resources");
566     load_shared();
567     timelog(0);
568
569     main_loop = new MainLoop();
570     if(config->start_level != "") {
571       // we have a normal path specified at commandline not physfs paths.
572       // So we simply mount that path here...
573       std::string dir = FileSystem::dirname(config->start_level);
574       PHYSFS_addToSearchPath(dir.c_str(), true);
575
576       if(config->start_level.size() > 4 &&
577               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
578           init_rand();
579           main_loop->push_screen(new WorldMapNS::WorldMap(
580                       FileSystem::basename(config->start_level)));
581       } else {
582         init_rand();//If level uses random eg. for
583         // rain particles before we do this:
584         std::auto_ptr<GameSession> session (
585                 new GameSession(FileSystem::basename(config->start_level)));
586
587         config->random_seed =session->get_demo_random_seed(config->start_demo);
588         init_rand();//initialise generator with seed from session
589
590         if(config->start_demo != "")
591           session->play_demo(config->start_demo);
592
593         if(config->record_demo != "")
594           session->record_demo(config->record_demo);
595         main_loop->push_screen(session.release());
596       }
597     } else {
598       init_rand();
599       main_loop->push_screen(new TitleScreen());
600     }
601
602     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
603     main_loop->run();
604 #ifndef NO_CATCH
605   } catch(std::exception& e) {
606     log_fatal << "Unexpected exception: " << e.what() << std::endl;
607     result = 1;
608   } catch(...) {
609     log_fatal << "Unexpected exception" << std::endl;
610     result = 1;
611   }
612 #endif
613
614   delete main_loop;
615   main_loop = NULL;
616
617   free_options_menu();
618   unload_shared();
619   quit_audio();
620
621   if(config)
622     config->save();
623   delete config;
624   config = NULL;
625   delete main_controller;
626   main_controller = NULL;
627   delete Console::instance;
628   Console::instance = NULL;
629   Scripting::exit_squirrel();
630   delete texture_manager;
631   texture_manager = NULL;
632   SDL_Quit();
633   PHYSFS_deinit();
634
635   return result;
636 }