Command line switch -d, --default to reset video settings to default values.
[supertux.git] / src / main.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "log.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <physfs.h>
34 #include <SDL.h>
35 #include <SDL_image.h>
36
37 #ifdef MACOSX
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
40 }
41 #endif
42
43 #include "gameconfig.hpp"
44 #include "resources.hpp"
45 #include "gettext.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "video/surface.hpp"
48 #include "video/texture_manager.hpp"
49 #include "video/drawing_context.hpp"
50 #include "video/glutil.hpp"
51 #include "control/joystickkeyboardcontroller.hpp"
52 #include "options_menu.hpp"
53 #include "mainloop.hpp"
54 #include "title.hpp"
55 #include "game_session.hpp"
56 #include "scripting/level.hpp"
57 #include "scripting/squirrel_util.hpp"
58 #include "file_system.hpp"
59 #include "physfs/physfs_sdl.hpp"
60 #include "random_generator.hpp"
61 #include "worldmap/worldmap.hpp"
62 #include "binreloc/binreloc.h"
63
64 namespace { DrawingContext *context_pointer; }
65 SDL_Surface *screen;
66 JoystickKeyboardController* main_controller = 0;
67 TinyGetText::DictionaryManager dictionary_manager;
68
69 int SCREEN_WIDTH;
70 int SCREEN_HEIGHT;
71
72 static void init_config()
73 {
74   config = new Config();
75   try {
76     config->load();
77   } catch(std::exception& e) {
78     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
79   }
80 }
81
82 static void init_tinygettext()
83 {
84   dictionary_manager.add_directory("locale");
85   dictionary_manager.set_charset("UTF-8");
86
87   // Config setting "locale" overrides language detection
88   if (config->locale != "") {
89     dictionary_manager.set_language( config->locale );
90   }
91 }
92
93 static void init_physfs(const char* argv0)
94 {
95   if(!PHYSFS_init(argv0)) {
96     std::stringstream msg;
97     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
98     throw std::runtime_error(msg.str());
99   }
100
101   // Initialize physfs (this is a slightly modified version of
102   // PHYSFS_setSaneConfig
103   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
104   const char* userdir = PHYSFS_getUserDir();
105   const char* dirsep = PHYSFS_getDirSeparator();
106   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
107
108   // Set configuration directory
109   sprintf(writedir, "%s.%s", userdir, application);
110   if(!PHYSFS_setWriteDir(writedir)) {
111     // try to create the directory
112     char* mkdir = new char[strlen(application) + 2];
113     sprintf(mkdir, ".%s", application);
114     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
115       std::ostringstream msg;
116       msg << "Failed creating configuration directory '"
117           << writedir << "': " << PHYSFS_getLastError();
118       delete[] writedir;
119       delete[] mkdir;
120       throw std::runtime_error(msg.str());
121     }
122     delete[] mkdir;
123
124     if(!PHYSFS_setWriteDir(writedir)) {
125       std::ostringstream msg;
126       msg << "Failed to use configuration directory '"
127           <<  writedir << "': " << PHYSFS_getLastError();
128       delete[] writedir;
129       throw std::runtime_error(msg.str());
130     }
131   }
132   PHYSFS_addToSearchPath(writedir, 0);
133   delete[] writedir;
134
135   // Search for archives and add them to the search path
136   const char* archiveExt = "zip";
137   char** rc = PHYSFS_enumerateFiles("/");
138   size_t extlen = strlen(archiveExt);
139
140   for(char** i = rc; *i != 0; ++i) {
141     size_t l = strlen(*i);
142     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
143       const char* ext = (*i) + (l - extlen);
144       if(strcasecmp(ext, archiveExt) == 0) {
145         const char* d = PHYSFS_getRealDir(*i);
146         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
147         sprintf(str, "%s%s%s", d, dirsep, *i);
148         PHYSFS_addToSearchPath(str, 1);
149         delete[] str;
150       }
151     }
152   }
153
154   PHYSFS_freeList(rc);
155
156   // when started from source dir...
157   std::string dir = PHYSFS_getBaseDir();
158   dir += "/data";
159   std::string testfname = dir;
160   testfname += "/credits.txt";
161   bool sourcedir = false;
162   FILE* 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 #ifdef MACOSX
173 {
174   using namespace supertux_apple;
175
176   // when started from Application file on Mac OS X...
177   char path[PATH_MAX];
178   CFBundleRef mainBundle = CFBundleGetMainBundle();
179   assert(mainBundle != 0);
180   CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
181   assert(mainBundleURL != 0);
182   CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
183   assert(pathStr != 0);
184   CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
185   CFRelease(mainBundleURL);
186   CFRelease(pathStr);
187
188   dir = std::string(path) + "/Contents/Resources/data";
189   testfname = dir + "/credits.txt";
190   sourcedir = false;
191   f = fopen(testfname.c_str(), "r");
192   if(f) {
193     fclose(f);
194     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
195       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
196     } else {
197       sourcedir = true;
198     }
199   }
200 }
201 #endif
202
203 #ifdef _WIN32
204   PHYSFS_addToSearchPath(".\\data", 1);
205 #endif
206
207   if(!sourcedir) {
208 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
209     std::string datadir;
210 #ifdef ENABLE_BINRELOC
211
212     char* dir;
213     br_init (NULL);
214     dir = br_find_data_dir(APPDATADIR);
215     datadir = dir;
216     free(dir);
217
218 #else
219     datadir = APPDATADIR;
220 #endif
221     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
222       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
223     }
224 #endif
225   }
226
227   // allow symbolic links
228   PHYSFS_permitSymbolicLinks(1);
229
230   //show search Path
231   char** searchpath = PHYSFS_getSearchPath();
232   for(char** i = searchpath; *i != NULL; i++)
233     log_info << "[" << *i << "] is in the search path" << std::endl;
234   PHYSFS_freeList(searchpath);
235 }
236
237 static void print_usage(const char* argv0)
238 {
239   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
240   fprintf(stderr,
241           _("Options:\n"
242             "  -f, --fullscreen             Run in fullscreen mode\n"
243             "  -w, --window                 Run in window mode\n"
244             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
245             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
246             "  -d, --default                Reset video settings to default values\n"
247             "  --disable-sfx                Disable sound effects\n"
248             "  --disable-music              Disable music\n"
249             "  --help                       Show this help message\n"
250             "  --version                    Display SuperTux version and quit\n"
251             "  --console                    Enable ingame scripting console\n"
252             "  --noconsole                  Disable ingame scripting console\n"
253             "  --show-fps                   Display framerate in levels\n"
254             "  --no-show-fps                Do not display framerate in levels\n"
255             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
256             "  --play-demo FILE LEVEL       Play a recorded demo\n"
257             "\n"));
258 }
259
260 /**
261  * Options that should be evaluated prior to any initializations at all go here
262  */
263 static bool pre_parse_commandline(int argc, char** argv)
264 {
265   for(int i = 1; i < argc; ++i) {
266     std::string arg = argv[i];
267
268     if(arg == "--version") {
269       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
270       return true;
271     }
272   }
273
274   return false;
275 }
276
277 /**
278  * Options that should be evaluated after config is read go here
279  */
280 static bool parse_commandline(int argc, char** argv)
281 {
282   for(int i = 1; i < argc; ++i) {
283     std::string arg = argv[i];
284
285     if(arg == "--help") {
286       print_usage(argv[0]);
287       return true;
288     } else if(arg == "--fullscreen" || arg == "-f") {
289       config->use_fullscreen = true;
290     } else if(arg == "--default" || arg == "-d") {
291       config->use_fullscreen = false;
292       config->aspect_ratio = -1;
293       config->screenwidth = 800;
294       config->screenheight = 600;
295     } else if(arg == "--window" || arg == "-w") {
296       config->use_fullscreen = false;
297     } else if(arg == "--geometry" || arg == "-g") {
298       if(i+1 >= argc) {
299         print_usage(argv[0]);
300         throw std::runtime_error("Need to specify a parameter for geometry switch");
301       }
302       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
303          != 2) {
304         print_usage(argv[0]);
305         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
306       }
307     } else if(arg == "--aspect" || arg == "-a") {
308       if(i+1 >= argc) {
309         print_usage(argv[0]);
310         throw std::runtime_error("Need to specify a parameter for aspect switch");
311       }
312       if(strcasecmp(argv[i+1], "auto") == 0) {
313         i++;
314         config->aspect_ratio = -1;
315       } else {
316         int aspect_width, aspect_height;
317         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
318           print_usage(argv[0]);
319           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
320         }
321         config->aspect_ratio = static_cast<double>(aspect_width) /
322                                static_cast<double>(aspect_height);
323       }
324     } else if(arg == "--show-fps") {
325       config->show_fps = true;
326     } else if(arg == "--no-show-fps") {
327       config->show_fps = false;
328     } else if(arg == "--console") {
329       config->console_enabled = true;
330     } else if(arg == "--noconsole") {
331       config->console_enabled = false;
332     } else if(arg == "--disable-sfx") {
333       config->sound_enabled = false;
334     } else if(arg == "--disable-music") {
335       config->music_enabled = false;
336     } else if(arg == "--play-demo") {
337       if(i+1 >= argc) {
338         print_usage(argv[0]);
339         throw std::runtime_error("Need to specify a demo filename");
340       }
341       config->start_demo = argv[++i];
342     } else if(arg == "--record-demo") {
343       if(i+1 >= argc) {
344         print_usage(argv[0]);
345         throw std::runtime_error("Need to specify a demo filename");
346       }
347       config->record_demo = argv[++i];
348     } else if(arg == "-d") {
349       config->enable_script_debugger = true;
350     } else if(arg[0] != '-') {
351       config->start_level = arg;
352     } else {
353       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
354       return true;
355     }
356   }
357
358   return false;
359 }
360
361 static void init_sdl()
362 {
363   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
364     std::stringstream msg;
365     msg << "Couldn't initialize SDL: " << SDL_GetError();
366     throw std::runtime_error(msg.str());
367   }
368   // just to be sure
369   atexit(SDL_Quit);
370
371   SDL_EnableUNICODE(1);
372
373   // wait 100ms and clear SDL event queue because sometimes we have random
374   // joystick events in the queue on startup...
375   SDL_Delay(100);
376   SDL_Event dummy;
377   while(SDL_PollEvent(&dummy))
378       ;
379 }
380
381 static void init_rand()
382 {
383   config->random_seed = systemRandom.srand(config->random_seed);
384
385   //const char *how = config->random_seed? ", user fixed.": ", from time().";
386   //log_info << "Using random seed " << config->random_seed << how << std::endl;
387 }
388
389 void init_video()
390 {
391   static int desktop_width = 0;
392   static int desktop_height = 0;
393
394 /* unfortunately only newer SDLs have these infos */
395 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
396   /* find which resolution the user normally uses */
397   if(desktop_width == 0) {
398     const SDL_VideoInfo *info = SDL_GetVideoInfo();
399     desktop_width  = info->current_w;
400     desktop_height = info->current_h;
401   }
402 #endif
403
404   double aspect_ratio = config->aspect_ratio;
405
406   // try to guess aspect ratio of monitor if needed
407   if (aspect_ratio <= 0) {
408 // TODO: commented out because 
409 // 1) it tends to guess wrong if widescreen-monitors don't stretch 800x600 to fit, but just display black borders
410 // 2) aspect ratios other than 4:3 are largely untested
411 /*
412     if(config->use_fullscreen && desktop_width > 0) {
413       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
414     } else {
415 */
416       aspect_ratio = 4.0 / 3.0;
417 /*
418     }
419 */
420   }
421
422   // use aspect ratio to calculate logical resolution
423   if (aspect_ratio > 1) {
424     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
425     SCREEN_HEIGHT = 600;
426   } else {
427     SCREEN_WIDTH  = 600;
428     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
429   }
430
431   context_pointer->init_renderer();
432   screen = SDL_GetVideoSurface();
433
434   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
435
436   // set icon
437   #ifdef MACOSX
438   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
439   #else
440   const char* icon_fname = "images/engine/icons/supertux.xpm";
441   #endif
442   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
443   if(icon != 0) {
444     SDL_WM_SetIcon(icon, 0);
445     SDL_FreeSurface(icon);
446   }
447 #ifdef DEBUG
448   else {
449     log_warning << "Couldn't find icon '" << icon_fname << "'" << std::endl;
450   }
451 #endif
452
453   SDL_ShowCursor(0);
454
455   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
456 }
457
458 static void init_audio()
459 {
460   sound_manager = new SoundManager();
461
462   sound_manager->enable_sound(config->sound_enabled);
463   sound_manager->enable_music(config->music_enabled);
464 }
465
466 static void quit_audio()
467 {
468   if(sound_manager != NULL) {
469     delete sound_manager;
470     sound_manager = NULL;
471   }
472 }
473
474 void wait_for_event(float min_delay, float max_delay)
475 {
476   assert(min_delay <= max_delay);
477
478   Uint32 min = (Uint32) (min_delay * 1000);
479   Uint32 max = (Uint32) (max_delay * 1000);
480
481   Uint32 ticks = SDL_GetTicks();
482   while(SDL_GetTicks() - ticks < min) {
483     SDL_Delay(10);
484     sound_manager->update();
485   }
486
487   // clear event queue
488   SDL_Event event;
489   while (SDL_PollEvent(&event))
490   {}
491
492   /* Handle events: */
493   bool running = false;
494   ticks = SDL_GetTicks();
495   while(running) {
496     while(SDL_PollEvent(&event)) {
497       switch(event.type) {
498         case SDL_QUIT:
499           main_loop->quit();
500           break;
501         case SDL_KEYDOWN:
502         case SDL_JOYBUTTONDOWN:
503         case SDL_MOUSEBUTTONDOWN:
504           running = false;
505       }
506     }
507     if(SDL_GetTicks() - ticks >= (max - min))
508       running = false;
509     sound_manager->update();
510     SDL_Delay(10);
511   }
512 }
513
514 #ifdef DEBUG
515 static Uint32 last_timelog_ticks = 0;
516 static const char* last_timelog_component = 0;
517
518 static inline void timelog(const char* component)
519 {
520   Uint32 current_ticks = SDL_GetTicks();
521
522   if(last_timelog_component != 0) {
523     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
524   }
525
526   last_timelog_ticks = current_ticks;
527   last_timelog_component = component;
528 }
529 #else
530 static inline void timelog(const char* )
531 {
532 }
533 #endif
534
535 int main(int argc, char** argv)
536 {
537   int result = 0;
538
539 #ifndef NO_CATCH
540   try {
541 #endif
542
543     if(pre_parse_commandline(argc, argv))
544       return 0;
545
546     Console::instance = new Console();
547     init_physfs(argv[0]);
548     init_sdl();
549
550     timelog("controller");
551     main_controller = new JoystickKeyboardController();
552     timelog("config");
553     init_config();
554     timelog("tinygettext");
555     init_tinygettext();
556     timelog("commandline");
557     if(parse_commandline(argc, argv))
558       return 0;
559     timelog("audio");
560     init_audio();
561     timelog("video");
562     DrawingContext context;
563     context_pointer = &context;
564     init_video();
565     Console::instance->init_graphics();
566     timelog("scripting");
567     Scripting::init_squirrel(config->enable_script_debugger);
568     timelog("resources");
569     load_shared();
570     timelog(0);
571
572     main_loop = new MainLoop();
573     if(config->start_level != "") {
574       // we have a normal path specified at commandline not physfs paths.
575       // So we simply mount that path here...
576       std::string dir = FileSystem::dirname(config->start_level);
577       PHYSFS_addToSearchPath(dir.c_str(), true);
578
579       if(config->start_level.size() > 4 &&
580               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
581           init_rand();
582           main_loop->push_screen(new WorldMapNS::WorldMap(
583                       FileSystem::basename(config->start_level)));
584       } else {
585         init_rand();//If level uses random eg. for
586         // rain particles before we do this:
587         std::auto_ptr<GameSession> session (
588                 new GameSession(FileSystem::basename(config->start_level)));
589
590         config->random_seed =session->get_demo_random_seed(config->start_demo);
591         init_rand();//initialise generator with seed from session
592
593         if(config->start_demo != "")
594           session->play_demo(config->start_demo);
595
596         if(config->record_demo != "")
597           session->record_demo(config->record_demo);
598         main_loop->push_screen(session.release());
599       }
600     } else {
601       init_rand();
602       main_loop->push_screen(new TitleScreen());
603     }
604
605     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
606     main_loop->run(context);
607 #ifndef NO_CATCH
608   } catch(std::exception& e) {
609     log_fatal << "Unexpected exception: " << e.what() << std::endl;
610     result = 1;
611   } catch(...) {
612     log_fatal << "Unexpected exception" << std::endl;
613     result = 1;
614   }
615 #endif
616
617   delete main_loop;
618   main_loop = NULL;
619
620   unload_shared();
621   quit_audio();
622
623   if(config)
624     config->save();
625   delete config;
626   config = NULL;
627   delete main_controller;
628   main_controller = NULL;
629   delete Console::instance;
630   Console::instance = NULL;
631   Scripting::exit_squirrel();
632   delete texture_manager;
633   texture_manager = NULL;
634   SDL_Quit();
635   PHYSFS_deinit();
636
637   return result;
638 }