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