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