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