Minor cleanup
[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   // wait 100ms and clear SDL event queue because sometimes we have random
403   // joystick events in the queue on startup...
404   SDL_Delay(100);
405   SDL_Event dummy;
406   while(SDL_PollEvent(&dummy))
407     ;
408 }
409
410 void
411 Main::init_rand()
412 {
413   g_config->random_seed = gameRandom.srand(g_config->random_seed);
414
415   graphicsRandom.srand(0);
416
417   //const char *how = config->random_seed? ", user fixed.": ", from time().";
418   //log_info << "Using random seed " << config->random_seed << how << std::endl;
419 }
420
421 void
422 Main::init_video()
423 {
424   SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
425
426   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
427   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
428   if (!icon)
429   {
430     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
431   }
432   else
433   {
434     SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
435     SDL_FreeSurface(icon);
436   }
437   SDL_ShowCursor(0);
438
439   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
440            << " Window: "     << g_config->window_size
441            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
442            << " Area: "       << g_config->aspect_size << std::endl;
443 }
444
445 void
446 Main::init_audio()
447 {
448   sound_manager = new SoundManager();
449
450   sound_manager->enable_sound(g_config->sound_enabled);
451   sound_manager->enable_music(g_config->music_enabled);
452 }
453
454 void
455 Main::quit_audio()
456 {
457   if(sound_manager != NULL) {
458     delete sound_manager;
459     sound_manager = NULL;
460   }
461 }
462
463 void
464 Main::wait_for_event(float min_delay, float max_delay)
465 {
466   assert(min_delay <= max_delay);
467
468   Uint32 min = (Uint32) (min_delay * 1000);
469   Uint32 max = (Uint32) (max_delay * 1000);
470
471   Uint32 ticks = SDL_GetTicks();
472   while(SDL_GetTicks() - ticks < min) {
473     SDL_Delay(10);
474     sound_manager->update();
475   }
476
477   // clear event queue
478   SDL_Event event;
479   while (SDL_PollEvent(&event))
480   {}
481
482   /* Handle events: */
483   bool running = false;
484   ticks = SDL_GetTicks();
485   while(running) {
486     while(SDL_PollEvent(&event)) {
487       switch(event.type) {
488         case SDL_QUIT:
489           g_screen_manager->quit();
490           break;
491         case SDL_KEYDOWN:
492         case SDL_JOYBUTTONDOWN:
493         case SDL_MOUSEBUTTONDOWN:
494           running = false;
495       }
496     }
497     if(SDL_GetTicks() - ticks >= (max - min))
498       running = false;
499     sound_manager->update();
500     SDL_Delay(10);
501   }
502 }
503
504 static Uint32 last_timelog_ticks = 0;
505 static const char* last_timelog_component = 0;
506
507 static inline void timelog(const char* component)
508 {
509   Uint32 current_ticks = SDL_GetTicks();
510
511   if(last_timelog_component != 0) {
512     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
513   }
514
515   last_timelog_ticks = current_ticks;
516   last_timelog_component = component;
517 }
518
519 int
520 Main::run(int argc, char** argv)
521 {
522   int result = 0;
523
524   try {
525     /* Do this before pre_parse_commandline, because --help now shows the
526      * default user data dir. */
527     init_physfs(argv[0]);
528
529     if(pre_parse_commandline(argc, argv))
530       return 0;
531
532     init_sdl();
533     Console::instance = new Console();
534
535     timelog("controller");
536     g_jk_controller = new JoystickKeyboardController();
537
538     timelog("config");
539     init_config();
540
541     timelog("commandline");
542     if(parse_commandline(argc, argv))
543       return 0;
544
545     timelog("video");
546     std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
547     std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
548     DrawingContext context(*renderer, *lightmap);
549     context_pointer = &context;
550     init_video();
551     
552     timelog("audio");
553     init_audio();
554     
555     timelog("tinygettext");
556     init_tinygettext();
557
558     Console::instance->init_graphics();
559
560     timelog("scripting");
561     scripting::init_squirrel(g_config->enable_script_debugger);
562
563     timelog("resources");
564     Resources::load_shared();
565     
566     timelog("addons");
567     AddonManager::get_instance().load_addons();
568
569     timelog(0);
570
571     const std::unique_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
572
573     g_screen_manager = new ScreenManager();
574
575     init_rand();
576
577     if(g_config->start_level != "") {
578       // we have a normal path specified at commandline, not a physfs path.
579       // So we simply mount that path here...
580       std::string dir = FileSystem::dirname(g_config->start_level);
581       std::string fileProtocol = "file://";
582       std::string::size_type position = dir.find(fileProtocol);
583       if(position != std::string::npos) {
584          dir = dir.replace(position, fileProtocol.length(), "");
585       }
586       log_debug << "Adding dir: " << dir << std::endl;
587       PHYSFS_addToSearchPath(dir.c_str(), true);
588
589       if(g_config->start_level.size() > 4 &&
590          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
591         g_screen_manager->push_screen(new worldmap::WorldMap(
592                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
593       } else {
594         std::unique_ptr<GameSession> session (
595           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
596
597         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
598         init_rand();//initialise generator with seed from session
599
600         if(g_config->start_demo != "")
601           session->play_demo(g_config->start_demo);
602
603         if(g_config->record_demo != "")
604           session->record_demo(g_config->record_demo);
605         g_screen_manager->push_screen(session.release());
606       }
607     } else {
608       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
609     }
610
611     g_screen_manager->run(context);
612   } catch(std::exception& e) {
613     log_fatal << "Unexpected exception: " << e.what() << std::endl;
614     result = 1;
615   } catch(...) {
616     log_fatal << "Unexpected exception" << std::endl;
617     result = 1;
618   }
619
620   delete g_screen_manager;
621   g_screen_manager = NULL;
622
623   Resources::unload_shared();
624   quit_audio();
625
626   if(g_config)
627     g_config->save();
628   delete g_config;
629   g_config = NULL;
630   delete g_jk_controller;
631   g_jk_controller = NULL;
632   delete Console::instance;
633   Console::instance = NULL;
634   scripting::exit_squirrel();
635   delete texture_manager;
636   texture_manager = NULL;
637   SDL_Quit();
638   PHYSFS_deinit();
639
640   return result;
641 }
642
643 /* EOF */