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