Ported changes from 0.3.1 and bumped version to 0.3.2-SVN
[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             "  --disable-sfx                Disable sound effects\n"
247             "  --disable-music              Disable music\n"
248             "  --help                       Show this help message\n"
249             "  --version                    Display SuperTux version and quit\n"
250             "  --console                    Enable ingame scripting console\n"
251             "  --noconsole                  Disable ingame scripting console\n"
252             "  --show-fps                   Display framerate in levels\n"
253             "  --no-show-fps                Do not display framerate in levels\n"
254             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
255             "  --play-demo FILE LEVEL       Play a recorded demo\n"
256             "\n"));
257 }
258
259 /**
260  * Options that should be evaluated prior to any initializations at all go here
261  */
262 static bool pre_parse_commandline(int argc, char** argv)
263 {
264   for(int i = 1; i < argc; ++i) {
265     std::string arg = argv[i];
266
267     if(arg == "--version") {
268       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
269       return true;
270     }
271   }
272
273   return false;
274 }
275
276 /**
277  * Options that should be evaluated after config is read go here
278  */
279 static bool parse_commandline(int argc, char** argv)
280 {
281   for(int i = 1; i < argc; ++i) {
282     std::string arg = argv[i];
283
284     if(arg == "--help") {
285       print_usage(argv[0]);
286       return true;
287     } else if(arg == "--fullscreen" || arg == "-f") {
288       config->use_fullscreen = true;
289     } else if(arg == "--window" || arg == "-w") {
290       config->use_fullscreen = false;
291     } else if(arg == "--geometry" || arg == "-g") {
292       if(i+1 >= argc) {
293         print_usage(argv[0]);
294         throw std::runtime_error("Need to specify a parameter for geometry switch");
295       }
296       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
297          != 2) {
298         print_usage(argv[0]);
299         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
300       }
301     } else if(arg == "--aspect" || arg == "-a") {
302       if(i+1 >= argc) {
303         print_usage(argv[0]);
304         throw std::runtime_error("Need to specify a parameter for aspect switch");
305       }
306       if(strcasecmp(argv[i+1], "auto") == 0) {
307         i++;
308         config->aspect_ratio = -1;
309       } else {
310         int aspect_width, aspect_height;
311         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
312           print_usage(argv[0]);
313           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
314         }
315         config->aspect_ratio = static_cast<double>(aspect_width) /
316                                static_cast<double>(aspect_height);
317       }
318     } else if(arg == "--show-fps") {
319       config->show_fps = true;
320     } else if(arg == "--no-show-fps") {
321       config->show_fps = false;
322     } else if(arg == "--console") {
323       config->console_enabled = true;
324     } else if(arg == "--noconsole") {
325       config->console_enabled = false;
326     } else if(arg == "--disable-sfx") {
327       config->sound_enabled = false;
328     } else if(arg == "--disable-music") {
329       config->music_enabled = false;
330     } else if(arg == "--play-demo") {
331       if(i+1 >= argc) {
332         print_usage(argv[0]);
333         throw std::runtime_error("Need to specify a demo filename");
334       }
335       config->start_demo = argv[++i];
336     } else if(arg == "--record-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->record_demo = argv[++i];
342     } else if(arg == "-d") {
343       config->enable_script_debugger = true;
344     } else if(arg[0] != '-') {
345       config->start_level = arg;
346     } else {
347       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
348       return true;
349     }
350   }
351
352   return false;
353 }
354
355 static void init_sdl()
356 {
357   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
358     std::stringstream msg;
359     msg << "Couldn't initialize SDL: " << SDL_GetError();
360     throw std::runtime_error(msg.str());
361   }
362   // just to be sure
363   atexit(SDL_Quit);
364
365   SDL_EnableUNICODE(1);
366
367   // wait 100ms and clear SDL event queue because sometimes we have random
368   // joystick events in the queue on startup...
369   SDL_Delay(100);
370   SDL_Event dummy;
371   while(SDL_PollEvent(&dummy))
372       ;
373 }
374
375 static void init_rand()
376 {
377   config->random_seed = systemRandom.srand(config->random_seed);
378
379   //const char *how = config->random_seed? ", user fixed.": ", from time().";
380   //log_info << "Using random seed " << config->random_seed << how << std::endl;
381 }
382
383 void init_video()
384 {
385   static int desktop_width = 0;
386   static int desktop_height = 0;
387
388 /* unfortunately only newer SDLs have these infos */
389 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
390   /* find which resolution the user normally uses */
391   if(desktop_width == 0) {
392     const SDL_VideoInfo *info = SDL_GetVideoInfo();
393     desktop_width  = info->current_w;
394     desktop_height = info->current_h;
395   }
396 #endif
397
398   double aspect_ratio = config->aspect_ratio;
399
400   // try to guess aspect ratio of monitor if needed
401   if (aspect_ratio <= 0) {
402 // TODO: commented out because 
403 // 1) it tends to guess wrong if widescreen-monitors don't stretch 800x600 to fit, but just display black borders
404 // 2) aspect ratios other than 4:3 are largely untested
405 /*
406     if(config->use_fullscreen && desktop_width > 0) {
407       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
408     } else {
409 */
410       aspect_ratio = 4.0 / 3.0;
411 /*
412     }
413 */
414   }
415
416   // use aspect ratio to calculate logical resolution
417   if (aspect_ratio > 1) {
418     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
419     SCREEN_HEIGHT = 600;
420   } else {
421     SCREEN_WIDTH  = 600;
422     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
423   }
424
425   context_pointer->init_renderer();
426   screen = SDL_GetVideoSurface();
427
428   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
429
430   // set icon
431   SDL_Surface* icon = IMG_Load_RW(
432       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
433   if(icon != 0) {
434     SDL_WM_SetIcon(icon, 0);
435     SDL_FreeSurface(icon);
436   }
437 #ifdef DEBUG
438   else {
439     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
440   }
441 #endif
442
443   SDL_ShowCursor(0);
444
445   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
446 }
447
448 static void init_audio()
449 {
450   sound_manager = new SoundManager();
451
452   sound_manager->enable_sound(config->sound_enabled);
453   sound_manager->enable_music(config->music_enabled);
454 }
455
456 static void quit_audio()
457 {
458   if(sound_manager != NULL) {
459     delete sound_manager;
460     sound_manager = NULL;
461   }
462 }
463
464 void wait_for_event(float min_delay, float max_delay)
465 {
466   assert(min_delay <= max_delay);
467
468   Uint32 min = (Uint32) (min_delay * 1000);
469   Uint32 max = (Uint32) (max_delay * 1000);
470
471   Uint32 ticks = SDL_GetTicks();
472   while(SDL_GetTicks() - ticks < min) {
473     SDL_Delay(10);
474     sound_manager->update();
475   }
476
477   // clear event queue
478   SDL_Event event;
479   while (SDL_PollEvent(&event))
480   {}
481
482   /* Handle events: */
483   bool running = false;
484   ticks = SDL_GetTicks();
485   while(running) {
486     while(SDL_PollEvent(&event)) {
487       switch(event.type) {
488         case SDL_QUIT:
489           main_loop->quit();
490           break;
491         case SDL_KEYDOWN:
492         case SDL_JOYBUTTONDOWN:
493         case SDL_MOUSEBUTTONDOWN:
494           running = false;
495       }
496     }
497     if(SDL_GetTicks() - ticks >= (max - min))
498       running = false;
499     sound_manager->update();
500     SDL_Delay(10);
501   }
502 }
503
504 #ifdef DEBUG
505 static Uint32 last_timelog_ticks = 0;
506 static const char* last_timelog_component = 0;
507
508 static inline void timelog(const char* component)
509 {
510   Uint32 current_ticks = SDL_GetTicks();
511
512   if(last_timelog_component != 0) {
513     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
514   }
515
516   last_timelog_ticks = current_ticks;
517   last_timelog_component = component;
518 }
519 #else
520 static inline void timelog(const char* )
521 {
522 }
523 #endif
524
525 int main(int argc, char** argv)
526 {
527   int result = 0;
528
529 #ifndef NO_CATCH
530   try {
531 #endif
532
533     if(pre_parse_commandline(argc, argv))
534       return 0;
535
536     Console::instance = new Console();
537     init_physfs(argv[0]);
538     init_sdl();
539
540     timelog("controller");
541     main_controller = new JoystickKeyboardController();
542     timelog("config");
543     init_config();
544     timelog("tinygettext");
545     init_tinygettext();
546     timelog("commandline");
547     if(parse_commandline(argc, argv))
548       return 0;
549     timelog("audio");
550     init_audio();
551     timelog("video");
552     DrawingContext context;
553     context_pointer = &context;
554     init_video();
555     Console::instance->init_graphics();
556     timelog("scripting");
557     Scripting::init_squirrel(config->enable_script_debugger);
558     timelog("resources");
559     load_shared();
560     timelog(0);
561
562     main_loop = new MainLoop();
563     if(config->start_level != "") {
564       // we have a normal path specified at commandline not physfs paths.
565       // So we simply mount that path here...
566       std::string dir = FileSystem::dirname(config->start_level);
567       PHYSFS_addToSearchPath(dir.c_str(), true);
568
569       if(config->start_level.size() > 4 &&
570               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
571           init_rand();
572           main_loop->push_screen(new WorldMapNS::WorldMap(
573                       FileSystem::basename(config->start_level)));
574       } else {
575         init_rand();//If level uses random eg. for
576         // rain particles before we do this:
577         std::auto_ptr<GameSession> session (
578                 new GameSession(FileSystem::basename(config->start_level)));
579
580         config->random_seed =session->get_demo_random_seed(config->start_demo);
581         init_rand();//initialise generator with seed from session
582
583         if(config->start_demo != "")
584           session->play_demo(config->start_demo);
585
586         if(config->record_demo != "")
587           session->record_demo(config->record_demo);
588         main_loop->push_screen(session.release());
589       }
590     } else {
591       init_rand();
592       main_loop->push_screen(new TitleScreen());
593     }
594
595     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
596     main_loop->run(context);
597 #ifndef NO_CATCH
598   } catch(std::exception& e) {
599     log_fatal << "Unexpected exception: " << e.what() << std::endl;
600     result = 1;
601   } catch(...) {
602     log_fatal << "Unexpected exception" << std::endl;
603     result = 1;
604   }
605 #endif
606
607   delete main_loop;
608   main_loop = NULL;
609
610   unload_shared();
611   quit_audio();
612
613   if(config)
614     config->save();
615   delete config;
616   config = NULL;
617   delete main_controller;
618   main_controller = NULL;
619   delete Console::instance;
620   Console::instance = NULL;
621   Scripting::exit_squirrel();
622   delete texture_manager;
623   texture_manager = NULL;
624   SDL_Quit();
625   PHYSFS_deinit();
626
627   return result;
628 }