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