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