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