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