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