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