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