48c2b7ebde8dcb18253787f6ad4b1a960d111f65
[supertux.git] / src / supertux / main.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include <config.h>
18 #include <version.h>
19
20 #include <SDL.h>
21 #include <SDL_image.h>
22 #include <physfs.h>
23 #include <iostream>
24 #include <binreloc.h>
25 #include <tinygettext/log.hpp>
26
27 #include "supertux/main.hpp"
28
29 #ifdef MACOSX
30 namespace supertux_apple {
31 #  include <CoreFoundation/CoreFoundation.h>
32 } // namespace supertux_apple
33 #endif
34
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/joystickkeyboardcontroller.hpp"
38 #include "control/haptic_manager.hpp"
39 #include "math/random_generator.hpp"
40 #include "physfs/ifile_stream.hpp"
41 #include "physfs/physfs_sdl.hpp"
42 #include "physfs/physfs_file_system.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/screen_manager.hpp"
48 #include "supertux/resources.hpp"
49 #include "supertux/title_screen.hpp"
50 #include "util/file_system.hpp"
51 #include "util/gettext.hpp"
52 #include "video/drawing_context.hpp"
53 #include "worldmap/worldmap.hpp"
54
55 namespace { DrawingContext *context_pointer; }
56
57 void 
58 Main::init_config()
59 {
60   g_config = new Config();
61   try {
62     g_config->load();
63   } catch(std::exception& e) {
64     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
65   }
66 }
67
68 void
69 Main::init_tinygettext()
70 {
71   dictionary_manager = new tinygettext::DictionaryManager();
72   tinygettext::Log::set_log_info_callback(0);
73   dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
74
75   dictionary_manager->add_directory("locale");
76   dictionary_manager->set_charset("UTF-8");
77
78   // Config setting "locale" overrides language detection
79   if (g_config->locale != "") 
80   {
81     dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
82   }
83 }
84
85 void
86 Main::init_physfs(const char* argv0)
87 {
88   if(!PHYSFS_init(argv0)) {
89     std::stringstream msg;
90     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
91     throw std::runtime_error(msg.str());
92   }
93
94   // allow symbolic links
95   PHYSFS_permitSymbolicLinks(1);
96
97   // Initialize physfs (this is a slightly modified version of
98   // PHYSFS_setSaneConfig)
99   const char* application = PACKAGE_NAME;
100   const char* userdir = PHYSFS_getUserDir();
101
102   char* writedir = new char[strlen(userdir) + strlen(application) + 
103 #ifndef _WIN32
104                                                                     2];
105 #else
106                                                                     1];
107 #endif
108
109   // Set configuration directory
110   sprintf(writedir, 
111 #ifndef _WIN32
112                     "%s.%s",
113 #else
114                     "%s%s",
115 #endif
116                              userdir, application);
117   if(!PHYSFS_setWriteDir(writedir)) {
118     // try to create the directory
119     char* mkdir = new char[strlen(application) +
120 #ifndef _WIN32
121                                                  2];
122 #else
123                                                  1];
124 #endif
125     sprintf(mkdir,
126 #ifndef _WIN32
127                    ".%s",
128 #else
129                    "%s",
130 #endif
131                           application);
132     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
133       std::ostringstream msg;
134       msg << "Failed creating configuration directory '"
135           << writedir << "': " << PHYSFS_getLastError();
136       delete[] writedir;
137       delete[] mkdir;
138       throw std::runtime_error(msg.str());
139     }
140     delete[] mkdir;
141
142     if(!PHYSFS_setWriteDir(writedir)) {
143       std::ostringstream msg;
144       msg << "Failed to use configuration directory '"
145           <<  writedir << "': " << PHYSFS_getLastError();
146       delete[] writedir;
147       throw std::runtime_error(msg.str());
148     }
149   }
150   PHYSFS_addToSearchPath(writedir, 0);
151   delete[] writedir;
152
153   // when started from source dir...
154   std::string dir = PHYSFS_getBaseDir();
155   dir += "/data";
156   std::string testfname = dir;
157   testfname += "/credits.txt";
158   bool sourcedir = false;
159   FILE* f = fopen(testfname.c_str(), "r");
160   if(f) {
161     fclose(f);
162     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
163       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
164     } else {
165       sourcedir = true;
166     }
167   }
168
169 #ifdef MACOSX
170   {
171     using namespace supertux_apple;
172
173     // when started from Application file on Mac OS X...
174     char path[PATH_MAX];
175     CFBundleRef mainBundle = CFBundleGetMainBundle();
176     assert(mainBundle != 0);
177     CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
178     assert(mainBundleURL != 0);
179     CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
180     assert(pathStr != 0);
181     CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
182     CFRelease(mainBundleURL);
183     CFRelease(pathStr);
184
185     dir = std::string(path) + "/Contents/Resources/data";
186     testfname = dir + "/credits.txt";
187     sourcedir = false;
188     f = fopen(testfname.c_str(), "r");
189     if(f) {
190       fclose(f);
191       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
192         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
193       } else {
194         sourcedir = true;
195       }
196     }
197   }
198 #endif
199
200 #ifdef _WIN32
201   PHYSFS_addToSearchPath(".\\data", 1);
202 #endif
203
204   if(!sourcedir) {
205     std::string datadir = PHYSFS_getBaseDir();
206     datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
207     datadir += "/" INSTALL_SUBDIR_SHARE;
208 #ifdef ENABLE_BINRELOC
209
210     char* dir;
211     br_init (NULL);
212     dir = br_find_data_dir(datadir.c_str());
213     datadir = dir;
214     free(dir);
215
216 #endif
217     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
218       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
219     }
220   }
221
222   //show search Path
223   char** searchpath = PHYSFS_getSearchPath();
224   for(char** i = searchpath; *i != NULL; i++)
225     log_info << "[" << *i << "] is in the search path" << std::endl;
226   PHYSFS_freeList(searchpath);
227 }
228
229 void
230 Main::print_usage(const char* argv0)
231 {
232   std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
233             << _("Options:\n"
234                  "  -f, --fullscreen             Run in fullscreen mode\n"
235                  "  -w, --window                 Run in window mode\n"
236                  "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
237                  "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
238                  "  -d, --default                Reset video settings to default values\n"
239                  "  --renderer RENDERER          Use sdl, opengl, or auto to render\n"
240                  "  --disable-sfx                Disable sound effects\n"
241                  "  --disable-music              Disable music\n"
242                  "  -h, --help                   Show this help message and quit\n"
243                  "  -v, --version                Show SuperTux version and quit\n"
244                  "  --console                    Enable ingame scripting console\n"
245                  "  --noconsole                  Disable ingame scripting console\n"
246                  "  --show-fps                   Display framerate in levels\n"
247                  "  --no-show-fps                Do not display framerate in levels\n"
248                  "  --record-demo FILE LEVEL     Record a demo to FILE\n"
249                  "  --play-demo FILE LEVEL       Play a recorded demo\n"
250                  "  -s, --debug-scripts          Enable script debugger.\n"
251                  "\n")
252             << std::flush;
253 }
254
255 /**
256  * Options that should be evaluated prior to any initializations at all go here
257  */
258 bool
259 Main::pre_parse_commandline(int argc, char** argv)
260 {
261   for(int i = 1; i < argc; ++i) {
262     std::string arg = argv[i];
263
264     if(arg == "--version" || arg == "-v") {
265       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
266       return true;
267     }
268     if(arg == "--help" || arg == "-h") {
269       print_usage(argv[0]);
270       return true;
271     }
272   }
273
274   return false;
275 }
276
277 /**
278  * Options that should be evaluated after config is read go here
279  */
280 bool
281 Main::parse_commandline(int argc, char** argv)
282 {
283   for(int i = 1; i < argc; ++i) {
284     std::string arg = argv[i];
285
286     if(arg == "--fullscreen" || arg == "-f") {
287       g_config->use_fullscreen = true;
288     } else if(arg == "--default" || arg == "-d") {
289       g_config->use_fullscreen = false;
290       
291       g_config->window_size     = Size(800, 600);
292       g_config->fullscreen_size = Size(800, 600);
293       g_config->aspect_size     = Size(0, 0);  // auto detect
294       
295     } else if(arg == "--window" || arg == "-w") {
296       g_config->use_fullscreen = false;
297     } else if(arg == "--geometry" || arg == "-g") {
298       i += 1;
299       if(i >= argc) 
300       {
301         print_usage(argv[0]);
302         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
303       } 
304       else 
305       {
306         int width, height;
307         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
308         {
309           print_usage(argv[0]);
310           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
311         }
312         else
313         {
314           g_config->window_size     = Size(width, height);
315           g_config->fullscreen_size = Size(width, height);
316         }
317       }
318     } else if(arg == "--aspect" || arg == "-a") {
319       i += 1;
320       if(i >= argc) 
321       {
322         print_usage(argv[0]);
323         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
324       } 
325       else 
326       {
327         int aspect_width  = 0;
328         int aspect_height = 0;
329         if (strcmp(argv[i], "auto") == 0)
330         {
331           aspect_width  = 0;
332           aspect_height = 0;
333         }
334         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
335         {
336           print_usage(argv[0]);
337           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
338         }
339         else 
340         {
341           float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
342
343           // use aspect ratio to calculate logical resolution
344           if (aspect_ratio > 1) {
345             g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
346                                          600);
347           } else {
348             g_config->aspect_size = Size(600, 
349                                          static_cast<int>(600 * 1/aspect_ratio + 0.5));
350           }
351         }
352       }
353     } else if(arg == "--renderer") {
354       i += 1;
355       if(i >= argc) 
356       {
357         print_usage(argv[0]);
358         throw std::runtime_error("Need to specify a renderer for renderer argument");
359       } 
360       else 
361       {
362         g_config->video = VideoSystem::get_video_system(argv[i]);
363       }
364     } else if(arg == "--show-fps") {
365       g_config->show_fps = true;
366     } else if(arg == "--no-show-fps") {
367       g_config->show_fps = false;
368     } else if(arg == "--console") {
369       g_config->console_enabled = true;
370     } else if(arg == "--noconsole") {
371       g_config->console_enabled = false;
372     } else if(arg == "--disable-sfx") {
373       g_config->sound_enabled = false;
374     } else if(arg == "--disable-music") {
375       g_config->music_enabled = false;
376     } else if(arg == "--play-demo") {
377       if(i+1 >= argc) {
378         print_usage(argv[0]);
379         throw std::runtime_error("Need to specify a demo filename");
380       }
381       g_config->start_demo = argv[++i];
382     } else if(arg == "--record-demo") {
383       if(i+1 >= argc) {
384         print_usage(argv[0]);
385         throw std::runtime_error("Need to specify a demo filename");
386       }
387       g_config->record_demo = argv[++i];
388     } else if(arg == "--debug-scripts" || arg == "-s") {
389       g_config->enable_script_debugger = true;
390     } else if(arg[0] != '-') {
391       g_config->start_level = arg;
392     } else {
393       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
394       return true;
395     }
396   }
397
398   return false;
399 }
400
401 void
402 Main::init_sdl()
403 {
404   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC) < 0) {
405     std::stringstream msg;
406     msg << "Couldn't initialize SDL: " << SDL_GetError();
407     throw std::runtime_error(msg.str());
408   }
409   // just to be sure
410   atexit(SDL_Quit);
411
412   SDL_EnableUNICODE(1);
413
414   // wait 100ms and clear SDL event queue because sometimes we have random
415   // joystick events in the queue on startup...
416   SDL_Delay(100);
417   SDL_Event dummy;
418   while(SDL_PollEvent(&dummy))
419     ;
420 }
421
422 void
423 Main::init_rand()
424 {
425   g_config->random_seed = systemRandom.srand(g_config->random_seed);
426
427   //const char *how = config->random_seed? ", user fixed.": ", from time().";
428   //log_info << "Using random seed " << config->random_seed << how << std::endl;
429 }
430
431 void
432 Main::init_video()
433 {
434   // FIXME: Add something here
435   SCREEN_WIDTH  = 800;
436   SCREEN_HEIGHT = 600;
437
438   context_pointer->init_renderer();
439   g_screen = SDL_GetVideoSurface();
440
441   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
442
443   // set icon
444 #ifdef MACOSX
445   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
446 #else
447   const char* icon_fname = "images/engine/icons/supertux.xpm";
448 #endif
449   SDL_Surface* icon;
450   try {
451     icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
452   } catch (const std::runtime_error& err) {
453     icon = 0;
454     log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
455   }
456   if(icon != 0) {
457     SDL_WM_SetIcon(icon, 0);
458     SDL_FreeSurface(icon);
459   }
460   else {
461     log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
462   }
463
464   SDL_ShowCursor(0);
465
466   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
467            << " Window: "     << g_config->window_size
468            << " Fullscreen: " << g_config->fullscreen_size
469            << " Area: "       << g_config->aspect_size << std::endl;
470 }
471
472 void
473 Main::init_audio()
474 {
475   sound_manager = new SoundManager();
476
477   sound_manager->enable_sound(g_config->sound_enabled);
478   sound_manager->enable_music(g_config->music_enabled);
479 }
480
481 void
482 Main::quit_audio()
483 {
484   if(sound_manager != NULL) {
485     delete sound_manager;
486     sound_manager = NULL;
487   }
488 }
489
490 void
491 Main::wait_for_event(float min_delay, float max_delay)
492 {
493   assert(min_delay <= max_delay);
494
495   Uint32 min = (Uint32) (min_delay * 1000);
496   Uint32 max = (Uint32) (max_delay * 1000);
497
498   Uint32 ticks = SDL_GetTicks();
499   while(SDL_GetTicks() - ticks < min) {
500     SDL_Delay(10);
501     sound_manager->update();
502   }
503
504   // clear event queue
505   SDL_Event event;
506   while (SDL_PollEvent(&event))
507   {}
508
509   /* Handle events: */
510   bool running = false;
511   ticks = SDL_GetTicks();
512   while(running) {
513     while(SDL_PollEvent(&event)) {
514       switch(event.type) {
515         case SDL_QUIT:
516           g_screen_manager->quit();
517           break;
518         case SDL_KEYDOWN:
519         case SDL_JOYBUTTONDOWN:
520         case SDL_MOUSEBUTTONDOWN:
521           running = false;
522       }
523     }
524     if(SDL_GetTicks() - ticks >= (max - min))
525       running = false;
526     sound_manager->update();
527     SDL_Delay(10);
528   }
529 }
530
531 static Uint32 last_timelog_ticks = 0;
532 static const char* last_timelog_component = 0;
533
534 static inline void timelog(const char* component)
535 {
536   Uint32 current_ticks = SDL_GetTicks();
537
538   if(last_timelog_component != 0) {
539     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
540   }
541
542   last_timelog_ticks = current_ticks;
543   last_timelog_component = component;
544 }
545
546 int
547 Main::run(int argc, char** argv)
548 {
549   int result = 0;
550
551   try {
552
553     if(pre_parse_commandline(argc, argv))
554       return 0;
555
556     Console::instance = new Console();
557     init_physfs(argv[0]);
558     init_sdl();
559
560     timelog("haptic");
561     g_haptic_manager = new HapticManager();
562
563     timelog("controller");
564     g_main_controller = new JoystickKeyboardController();
565
566     timelog("config");
567     init_config();
568
569     timelog("addons");
570     AddonManager::get_instance().load_addons();
571
572     timelog("tinygettext");
573     init_tinygettext();
574
575     timelog("commandline");
576     if(parse_commandline(argc, argv))
577       return 0;
578
579     timelog("audio");
580     init_audio();
581
582     timelog("video");
583     DrawingContext context;
584     context_pointer = &context;
585     init_video();
586
587     Console::instance->init_graphics();
588
589     timelog("scripting");
590     scripting::init_squirrel(g_config->enable_script_debugger);
591
592     timelog("resources");
593     Resources::load_shared();
594
595     timelog(0);
596
597     const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
598
599     g_screen_manager = new ScreenManager();
600
601     init_rand();
602
603     if(g_config->start_level != "") {
604       // we have a normal path specified at commandline, not a physfs path.
605       // So we simply mount that path here...
606       std::string dir = FileSystem::dirname(g_config->start_level);
607       log_debug << "Adding dir: " << dir << std::endl;
608       PHYSFS_addToSearchPath(dir.c_str(), true);
609
610       if(g_config->start_level.size() > 4 &&
611          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
612         g_screen_manager->push_screen(new worldmap::WorldMap(
613                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
614       } else {
615         std::auto_ptr<GameSession> session (
616           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
617
618         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
619         init_rand();//initialise generator with seed from session
620
621         if(g_config->start_demo != "")
622           session->play_demo(g_config->start_demo);
623
624         if(g_config->record_demo != "")
625           session->record_demo(g_config->record_demo);
626         g_screen_manager->push_screen(session.release());
627       }
628     } else {
629       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
630     }
631
632     g_screen_manager->run(context);
633   } catch(std::exception& e) {
634     log_fatal << "Unexpected exception: " << e.what() << std::endl;
635     result = 1;
636   } catch(...) {
637     log_fatal << "Unexpected exception" << std::endl;
638     result = 1;
639   }
640
641   delete g_screen_manager;
642   g_screen_manager = NULL;
643
644   Resources::unload_shared();
645   quit_audio();
646
647   if(g_config)
648     g_config->save();
649   delete g_config;
650   g_config = NULL;
651   delete g_main_controller;
652   g_main_controller = NULL;
653   delete Console::instance;
654   Console::instance = NULL;
655   scripting::exit_squirrel();
656   delete texture_manager;
657   texture_manager = NULL;
658   SDL_Quit();
659   PHYSFS_deinit();
660
661   return result;
662 }
663
664 /* EOF */