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