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