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