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 "supertux/main.hpp"
18
19 #include <config.h>
20 #include <version.h>
21
22 #include <SDL_image.h>
23 #include <physfs.h>
24 #include <iostream>
25 #include <binreloc.h>
26 #include <tinygettext/log.hpp>
27
28 #ifdef MACOSX
29 namespace supertux_apple {
30 #  include <CoreFoundation/CoreFoundation.h>
31 } // namespace supertux_apple
32 #endif
33
34 #include "addon/addon_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "control/joystickkeyboardcontroller.hpp"
37 #include "math/random_generator.hpp"
38 #include "physfs/ifile_stream.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "physfs/physfs_file_system.hpp"
41 #include "scripting/squirrel_util.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/screen_manager.hpp"
45 #include "supertux/resources.hpp"
46 #include "supertux/title_screen.hpp"
47 #include "util/file_system.hpp"
48 #include "util/gettext.hpp"
49 #include "video/drawing_context.hpp"
50 #include "worldmap/worldmap.hpp"
51
52 namespace { DrawingContext *context_pointer; }
53
54 void 
55 Main::init_config()
56 {
57   g_config = new Config();
58   try {
59     g_config->load();
60   } catch(std::exception& e) {
61     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
62   }
63 }
64
65 void
66 Main::init_tinygettext()
67 {
68   dictionary_manager = new tinygettext::DictionaryManager();
69   tinygettext::Log::set_log_info_callback(0);
70   dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
71
72   dictionary_manager->add_directory("locale");
73   dictionary_manager->set_charset("UTF-8");
74
75   // Config setting "locale" overrides language detection
76   if (g_config->locale != "") 
77   {
78     dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
79   }
80 }
81
82 void
83 Main::init_physfs(const char* argv0)
84 {
85   if(!PHYSFS_init(argv0)) {
86     std::stringstream msg;
87     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
88     throw std::runtime_error(msg.str());
89   }
90
91   // allow symbolic links
92   PHYSFS_permitSymbolicLinks(1);
93
94   // Initialize physfs (this is a slightly modified version of
95   // PHYSFS_setSaneConfig
96   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
97   const char* userdir = PHYSFS_getUserDir();
98   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
99
100   // Set configuration directory
101   sprintf(writedir, "%s.%s", userdir, application);
102   if(!PHYSFS_setWriteDir(writedir)) {
103     // try to create the directory
104     char* mkdir = new char[strlen(application) + 2];
105     sprintf(mkdir, ".%s", application);
106     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
107       std::ostringstream msg;
108       msg << "Failed creating configuration directory '"
109           << writedir << "': " << PHYSFS_getLastError();
110       delete[] writedir;
111       delete[] mkdir;
112       throw std::runtime_error(msg.str());
113     }
114     delete[] mkdir;
115
116     if(!PHYSFS_setWriteDir(writedir)) {
117       std::ostringstream msg;
118       msg << "Failed to use configuration directory '"
119           <<  writedir << "': " << PHYSFS_getLastError();
120       delete[] writedir;
121       throw std::runtime_error(msg.str());
122     }
123   }
124   PHYSFS_addToSearchPath(writedir, 0);
125   delete[] writedir;
126
127   // when started from source dir...
128   std::string dir = PHYSFS_getBaseDir();
129   dir += "/data";
130   std::string testfname = dir;
131   testfname += "/credits.txt";
132   bool sourcedir = false;
133   FILE* f = fopen(testfname.c_str(), "r");
134   if(f) {
135     fclose(f);
136     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
137       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
138     } else {
139       sourcedir = true;
140     }
141   }
142
143 #ifdef MACOSX
144   {
145     using namespace supertux_apple;
146
147     // when started from Application file on Mac OS X...
148     char path[PATH_MAX];
149     CFBundleRef mainBundle = CFBundleGetMainBundle();
150     assert(mainBundle != 0);
151     CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
152     assert(mainBundleURL != 0);
153     CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
154     assert(pathStr != 0);
155     CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
156     CFRelease(mainBundleURL);
157     CFRelease(pathStr);
158
159     dir = std::string(path) + "/Contents/Resources/data";
160     testfname = dir + "/credits.txt";
161     sourcedir = false;
162     f = fopen(testfname.c_str(), "r");
163     if(f) {
164       fclose(f);
165       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
166         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167       } else {
168         sourcedir = true;
169       }
170     }
171   }
172 #endif
173
174 #ifdef _WIN32
175   PHYSFS_addToSearchPath(".\\data", 1);
176 #endif
177
178   if(!sourcedir) {
179 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
180     std::string datadir;
181 #ifdef ENABLE_BINRELOC
182
183     char* dir;
184     br_init (NULL);
185     dir = br_find_data_dir(APPDATADIR);
186     datadir = dir;
187     free(dir);
188
189 #else
190     datadir = APPDATADIR;
191 #endif
192     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
193       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
194     }
195 #endif
196   }
197
198   //show search Path
199   char** searchpath = PHYSFS_getSearchPath();
200   for(char** i = searchpath; *i != NULL; i++)
201     log_info << "[" << *i << "] is in the search path" << std::endl;
202   PHYSFS_freeList(searchpath);
203 }
204
205 void
206 Main::print_usage(const char* argv0)
207 {
208   std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
209             << _("Options:\n"
210                  "  -f, --fullscreen             Run in fullscreen mode\n"
211                  "  -w, --window                 Run in window mode\n"
212                  "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
213                  "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
214                  "  -d, --default                Reset video settings to default values\n"
215                  "  --renderer RENDERER          Use sdl, opengl, or auto to render\n"
216                  "  --disable-sfx                Disable sound effects\n"
217                  "  --disable-music              Disable music\n"
218                  "  -h, --help                   Show this help message and quit\n"
219                  "  -v, --version                Show SuperTux version and quit\n"
220                  "  --console                    Enable ingame scripting console\n"
221                  "  --noconsole                  Disable ingame scripting console\n"
222                  "  --show-fps                   Display framerate in levels\n"
223                  "  --no-show-fps                Do not display framerate in levels\n"
224                  "  --record-demo FILE LEVEL     Record a demo to FILE\n"
225                  "  --play-demo FILE LEVEL       Play a recorded demo\n"
226                  "  -s, --debug-scripts          Enable script debugger.\n"
227                  "\n")
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   }
249
250   return false;
251 }
252
253 /**
254  * Options that should be evaluated after config is read go here
255  */
256 bool
257 Main::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 == "--fullscreen" || arg == "-f") {
263       g_config->use_fullscreen = true;
264     } else if(arg == "--default" || arg == "-d") {
265       g_config->use_fullscreen = false;
266       
267       g_config->window_width  = 800;
268       g_config->window_height = 600;
269
270       g_config->fullscreen_width  = 800;
271       g_config->fullscreen_height = 600;
272
273       g_config->aspect_width  = 0;  // auto detect
274       g_config->aspect_height = 0;
275       
276     } else if(arg == "--window" || arg == "-w") {
277       g_config->use_fullscreen = false;
278     } else if(arg == "--geometry" || arg == "-g") {
279       i += 1;
280       if(i >= argc) 
281       {
282         print_usage(argv[0]);
283         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
284       } 
285       else 
286       {
287         int width, height;
288         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
289         {
290           print_usage(argv[0]);
291           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
292         }
293         else
294         {
295           g_config->window_width  = width;
296           g_config->window_height = height;
297
298           g_config->fullscreen_width  = width;
299           g_config->fullscreen_height = height;
300         }
301       }
302     } else if(arg == "--aspect" || arg == "-a") {
303       i += 1;
304       if(i >= argc) 
305       {
306         print_usage(argv[0]);
307         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
308       } 
309       else 
310       {
311         int aspect_width  = 0;
312         int aspect_height = 0;
313         if (strcmp(argv[i], "auto") == 0)
314         {
315           aspect_width  = 0;
316           aspect_height = 0;
317         }
318         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
319         {
320           print_usage(argv[0]);
321           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
322         }
323         else 
324         {
325           float aspect_ratio = static_cast<double>(g_config->aspect_width) /
326             static_cast<double>(g_config->aspect_height);
327
328           // use aspect ratio to calculate logical resolution
329           if (aspect_ratio > 1) {
330             g_config->aspect_width  = static_cast<int> (600 * aspect_ratio + 0.5);
331             g_config->aspect_height = 600;
332           } else {
333             g_config->aspect_width  = 600;
334             g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
335           }
336         }
337       }
338     } else if(arg == "--renderer") {
339       i += 1;
340       if(i >= argc) 
341       {
342         print_usage(argv[0]);
343         throw std::runtime_error("Need to specify a renderer for renderer argument");
344       } 
345       else 
346       {
347         g_config->video = get_video_system(argv[i]);
348       }
349     } else if(arg == "--show-fps") {
350       g_config->show_fps = true;
351     } else if(arg == "--no-show-fps") {
352       g_config->show_fps = false;
353     } else if(arg == "--console") {
354       g_config->console_enabled = true;
355     } else if(arg == "--noconsole") {
356       g_config->console_enabled = false;
357     } else if(arg == "--disable-sfx") {
358       g_config->sound_enabled = false;
359     } else if(arg == "--disable-music") {
360       g_config->music_enabled = false;
361     } else if(arg == "--play-demo") {
362       if(i+1 >= argc) {
363         print_usage(argv[0]);
364         throw std::runtime_error("Need to specify a demo filename");
365       }
366       g_config->start_demo = argv[++i];
367     } else if(arg == "--record-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->record_demo = argv[++i];
373     } else if(arg == "--debug-scripts" || arg == "-s") {
374       g_config->enable_script_debugger = true;
375     } else if(arg[0] != '-') {
376       g_config->start_level = arg;
377     } else {
378       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
379       return true;
380     }
381   }
382
383   return false;
384 }
385
386 void
387 Main::init_sdl()
388 {
389   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
390     std::stringstream msg;
391     msg << "Couldn't initialize SDL: " << SDL_GetError();
392     throw std::runtime_error(msg.str());
393   }
394   // just to be sure
395   atexit(SDL_Quit);
396
397   SDL_EnableUNICODE(1);
398
399   // wait 100ms and clear SDL event queue because sometimes we have random
400   // joystick events in the queue on startup...
401   SDL_Delay(100);
402   SDL_Event dummy;
403   while(SDL_PollEvent(&dummy))
404     ;
405 }
406
407 void
408 Main::init_rand()
409 {
410   g_config->random_seed = systemRandom.srand(g_config->random_seed);
411
412   //const char *how = config->random_seed? ", user fixed.": ", from time().";
413   //log_info << "Using random seed " << config->random_seed << how << std::endl;
414 }
415
416 void
417 Main::init_video()
418 {
419   // FIXME: Add something here
420   SCREEN_WIDTH  = 800;
421   SCREEN_HEIGHT = 600;
422
423   context_pointer->init_renderer();
424   g_screen = SDL_GetVideoSurface();
425
426   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
427
428   // set icon
429 #ifdef MACOSX
430   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
431 #else
432   const char* icon_fname = "images/engine/icons/supertux.xpm";
433 #endif
434   SDL_Surface* icon;
435   try {
436     icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
437   } catch (const std::runtime_error& err) {
438     icon = 0;
439     log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
440   }
441   if(icon != 0) {
442     SDL_WM_SetIcon(icon, 0);
443     SDL_FreeSurface(icon);
444   }
445 #ifndef NDEBUG
446   else {
447     log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
448   }
449 #endif
450
451   SDL_ShowCursor(0);
452
453   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
454            << " Window: "     << g_config->window_width     << "x" << g_config->window_height
455            << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
456            << " Area: "       << g_config->aspect_width     << "x" << g_config->aspect_height << std::endl;
457 }
458
459 void
460 Main::init_audio()
461 {
462   sound_manager = new SoundManager();
463
464   sound_manager->enable_sound(g_config->sound_enabled);
465   sound_manager->enable_music(g_config->music_enabled);
466 }
467
468 void
469 Main::quit_audio()
470 {
471   if(sound_manager != NULL) {
472     delete sound_manager;
473     sound_manager = NULL;
474   }
475 }
476
477 void
478 Main::wait_for_event(float min_delay, float max_delay)
479 {
480   assert(min_delay <= max_delay);
481
482   Uint32 min = (Uint32) (min_delay * 1000);
483   Uint32 max = (Uint32) (max_delay * 1000);
484
485   Uint32 ticks = SDL_GetTicks();
486   while(SDL_GetTicks() - ticks < min) {
487     SDL_Delay(10);
488     sound_manager->update();
489   }
490
491   // clear event queue
492   SDL_Event event;
493   while (SDL_PollEvent(&event))
494   {}
495
496   /* Handle events: */
497   bool running = false;
498   ticks = SDL_GetTicks();
499   while(running) {
500     while(SDL_PollEvent(&event)) {
501       switch(event.type) {
502         case SDL_QUIT:
503           g_screen_manager->quit();
504           break;
505         case SDL_KEYDOWN:
506         case SDL_JOYBUTTONDOWN:
507         case SDL_MOUSEBUTTONDOWN:
508           running = false;
509       }
510     }
511     if(SDL_GetTicks() - ticks >= (max - min))
512       running = false;
513     sound_manager->update();
514     SDL_Delay(10);
515   }
516 }
517
518 #ifndef NDEBUG
519 static Uint32 last_timelog_ticks = 0;
520 static const char* last_timelog_component = 0;
521
522 static inline void timelog(const char* component)
523 {
524   Uint32 current_ticks = SDL_GetTicks();
525
526   if(last_timelog_component != 0) {
527     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
528   }
529
530   last_timelog_ticks = current_ticks;
531   last_timelog_component = component;
532 }
533 #else
534 static inline void timelog(const char* )
535 {
536 }
537 #endif
538
539 int
540 Main::main(int argc, char** argv)
541 {
542   int result = 0;
543
544   try {
545
546     if(pre_parse_commandline(argc, argv))
547       return 0;
548
549     Console::instance = new Console();
550     init_physfs(argv[0]);
551     init_sdl();
552
553     timelog("controller");
554     g_main_controller = new JoystickKeyboardController();
555
556     timelog("config");
557     init_config();
558
559     timelog("addons");
560     AddonManager::get_instance().load_addons();
561
562     timelog("tinygettext");
563     init_tinygettext();
564
565     timelog("commandline");
566     if(parse_commandline(argc, argv))
567       return 0;
568
569     timelog("audio");
570     init_audio();
571
572     timelog("video");
573     DrawingContext context;
574     context_pointer = &context;
575     init_video();
576
577     Console::instance->init_graphics();
578
579     timelog("scripting");
580     Scripting::init_squirrel(g_config->enable_script_debugger);
581
582     timelog("resources");
583     Resources::load_shared();
584
585     timelog(0);
586
587     g_screen_manager = new ScreenManager();
588     if(g_config->start_level != "") {
589       // we have a normal path specified at commandline, not a physfs path.
590       // So we simply mount that path here...
591       std::string dir = FileSystem::dirname(g_config->start_level);
592       log_debug << "Adding dir: " << dir << std::endl;
593       PHYSFS_addToSearchPath(dir.c_str(), true);
594
595       if(g_config->start_level.size() > 4 &&
596          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
597         init_rand();
598         g_screen_manager->push_screen(new WorldMapNS::WorldMap(
599                                  FileSystem::basename(g_config->start_level)));
600       } else {
601         init_rand();//If level uses random eg. for
602         // rain particles before we do this:
603         std::auto_ptr<GameSession> session (
604           new GameSession(FileSystem::basename(g_config->start_level)));
605
606         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
607         init_rand();//initialise generator with seed from session
608
609         if(g_config->start_demo != "")
610           session->play_demo(g_config->start_demo);
611
612         if(g_config->record_demo != "")
613           session->record_demo(g_config->record_demo);
614         g_screen_manager->push_screen(session.release());
615       }
616     } else {
617       init_rand();
618       g_screen_manager->push_screen(new TitleScreen());
619     }
620
621     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
622     g_screen_manager->run(context);
623   } catch(std::exception& e) {
624     log_fatal << "Unexpected exception: " << e.what() << std::endl;
625     result = 1;
626   } catch(...) {
627     log_fatal << "Unexpected exception" << std::endl;
628     result = 1;
629   }
630
631   delete g_screen_manager;
632   g_screen_manager = NULL;
633
634   Resources::unload_shared();
635   quit_audio();
636
637   if(g_config)
638     g_config->save();
639   delete g_config;
640   g_config = NULL;
641   delete g_main_controller;
642   g_main_controller = NULL;
643   delete Console::instance;
644   Console::instance = NULL;
645   Scripting::exit_squirrel();
646   delete texture_manager;
647   texture_manager = NULL;
648   SDL_Quit();
649   PHYSFS_deinit();
650
651   return result;
652 }
653
654 /* EOF */