Fixed window resize in OpenGL and added window resize to SDL renderer
[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->aspect_size     = Size(0, 0);  // auto detect
323       
324     } else if(arg == "--window" || arg == "-w") {
325       g_config->use_fullscreen = false;
326     } else if(arg == "--geometry" || arg == "-g") {
327       i += 1;
328       if(i >= argc) 
329       {
330         print_usage(argv[0]);
331         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
332       } 
333       else 
334       {
335         int width, height;
336         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
337         {
338           print_usage(argv[0]);
339           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
340         }
341         else
342         {
343           g_config->window_size     = Size(width, height);
344           g_config->fullscreen_size = Size(width, height);
345         }
346       }
347     } else if(arg == "--aspect" || arg == "-a") {
348       i += 1;
349       if(i >= argc) 
350       {
351         print_usage(argv[0]);
352         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
353       } 
354       else 
355       {
356         int aspect_width  = 0;
357         int aspect_height = 0;
358         if (strcmp(argv[i], "auto") == 0)
359         {
360           aspect_width  = 0;
361           aspect_height = 0;
362         }
363         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
364         {
365           print_usage(argv[0]);
366           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
367         }
368         else 
369         {
370           float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
371
372           // use aspect ratio to calculate logical resolution
373           if (aspect_ratio > 1) {
374             g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
375                                          600);
376           } else {
377             g_config->aspect_size = Size(600, 
378                                          static_cast<int>(600 * 1/aspect_ratio + 0.5));
379           }
380         }
381       }
382     } else if(arg == "--renderer") {
383       i += 1;
384       if(i >= argc) 
385       {
386         print_usage(argv[0]);
387         throw std::runtime_error("Need to specify a renderer for renderer argument");
388       } 
389       else 
390       {
391         g_config->video = VideoSystem::get_video_system(argv[i]);
392       }
393     } else if(arg == "--show-fps") {
394       g_config->show_fps = true;
395     } else if(arg == "--no-show-fps") {
396       g_config->show_fps = false;
397     } else if(arg == "--console") {
398       g_config->console_enabled = true;
399     } else if(arg == "--noconsole") {
400       g_config->console_enabled = false;
401     } else if(arg == "--disable-sfx") {
402       g_config->sound_enabled = false;
403     } else if(arg == "--disable-music") {
404       g_config->music_enabled = false;
405     } else if(arg == "--play-demo") {
406       if(i+1 >= argc) {
407         print_usage(argv[0]);
408         throw std::runtime_error("Need to specify a demo filename");
409       }
410       g_config->start_demo = argv[++i];
411     } else if(arg == "--record-demo") {
412       if(i+1 >= argc) {
413         print_usage(argv[0]);
414         throw std::runtime_error("Need to specify a demo filename");
415       }
416       g_config->record_demo = argv[++i];
417     } else if(arg == "--debug-scripts" || arg == "-s") {
418       g_config->enable_script_debugger = true;
419     } else if(arg[0] != '-') {
420       g_config->start_level = arg;
421     } else {
422       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
423       return true;
424     }
425   }
426
427   return false;
428 }
429
430 void
431 Main::init_sdl()
432 {
433   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
434     std::stringstream msg;
435     msg << "Couldn't initialize SDL: " << SDL_GetError();
436     throw std::runtime_error(msg.str());
437   }
438   // just to be sure
439   atexit(SDL_Quit);
440
441  // SDL_EnableUNICODE(1); //old code, mofif by giby 
442  //   SDL_JoystickID myID = SDL_JoystickInstanceID(myOpenedStick);
443   
444
445   // wait 100ms and clear SDL event queue because sometimes we have random
446   // joystick events in the queue on startup...
447   SDL_Delay(100);
448   SDL_Event dummy;
449   while(SDL_PollEvent(&dummy))
450     ;
451 }
452
453 void
454 Main::init_rand()
455 {
456   g_config->random_seed = gameRandom.srand(g_config->random_seed);
457
458   graphicsRandom.srand(0);
459
460   //const char *how = config->random_seed? ", user fixed.": ", from time().";
461   //log_info << "Using random seed " << config->random_seed << how << std::endl;
462 }
463
464 void
465 Main::init_video()
466 {
467   SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
468
469   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
470   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
471   if (!icon)
472   {
473     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
474   }
475   else
476   {
477     SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
478     SDL_FreeSurface(icon);
479   }
480   SDL_ShowCursor(0);
481
482   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
483            << " Window: "     << g_config->window_size
484            << " Fullscreen: " << g_config->fullscreen_size
485            << " Area: "       << g_config->aspect_size << std::endl;
486 }
487
488 void
489 Main::init_audio()
490 {
491   sound_manager = new SoundManager();
492
493   sound_manager->enable_sound(g_config->sound_enabled);
494   sound_manager->enable_music(g_config->music_enabled);
495 }
496
497 void
498 Main::quit_audio()
499 {
500   if(sound_manager != NULL) {
501     delete sound_manager;
502     sound_manager = NULL;
503   }
504 }
505
506 void
507 Main::wait_for_event(float min_delay, float max_delay)
508 {
509   assert(min_delay <= max_delay);
510
511   Uint32 min = (Uint32) (min_delay * 1000);
512   Uint32 max = (Uint32) (max_delay * 1000);
513
514   Uint32 ticks = SDL_GetTicks();
515   while(SDL_GetTicks() - ticks < min) {
516     SDL_Delay(10);
517     sound_manager->update();
518   }
519
520   // clear event queue
521   SDL_Event event;
522   while (SDL_PollEvent(&event))
523   {}
524
525   /* Handle events: */
526   bool running = false;
527   ticks = SDL_GetTicks();
528   while(running) {
529     while(SDL_PollEvent(&event)) {
530       switch(event.type) {
531         case SDL_QUIT:
532           g_screen_manager->quit();
533           break;
534         case SDL_KEYDOWN:
535         case SDL_JOYBUTTONDOWN:
536         case SDL_MOUSEBUTTONDOWN:
537           running = false;
538       }
539     }
540     if(SDL_GetTicks() - ticks >= (max - min))
541       running = false;
542     sound_manager->update();
543     SDL_Delay(10);
544   }
545 }
546
547 static Uint32 last_timelog_ticks = 0;
548 static const char* last_timelog_component = 0;
549
550 static inline void timelog(const char* component)
551 {
552   Uint32 current_ticks = SDL_GetTicks();
553
554   if(last_timelog_component != 0) {
555     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
556   }
557
558   last_timelog_ticks = current_ticks;
559   last_timelog_component = component;
560 }
561
562 int
563 Main::run(int argc, char** argv)
564 {
565   int result = 0;
566
567   try {
568     /* Do this before pre_parse_commandline, because --help now shows the
569      * default user data dir. */
570     init_physfs(argv[0]);
571
572     if(pre_parse_commandline(argc, argv))
573       return 0;
574
575     init_sdl();
576     Console::instance = new Console();
577
578     timelog("controller");
579     g_jk_controller = new JoystickKeyboardController();
580
581     timelog("config");
582     init_config();
583
584     timelog("commandline");
585     if(parse_commandline(argc, argv))
586       return 0;
587
588     timelog("video");
589     std::auto_ptr<Renderer> renderer(VideoSystem::new_renderer());
590     std::auto_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
591     DrawingContext context(*renderer, *lightmap);
592     context_pointer = &context;
593     init_video();
594     
595     timelog("audio");
596     init_audio();
597     
598     timelog("tinygettext");
599     init_tinygettext();
600
601     Console::instance->init_graphics();
602
603     timelog("scripting");
604     scripting::init_squirrel(g_config->enable_script_debugger);
605
606     timelog("resources");
607     Resources::load_shared();
608     
609     timelog("addons");
610     AddonManager::get_instance().load_addons();
611
612     timelog(0);
613
614     const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
615
616     g_screen_manager = new ScreenManager();
617
618     init_rand();
619
620     if(g_config->start_level != "") {
621       // we have a normal path specified at commandline, not a physfs path.
622       // So we simply mount that path here...
623       std::string dir = FileSystem::dirname(g_config->start_level);
624       log_debug << "Adding dir: " << dir << std::endl;
625       PHYSFS_addToSearchPath(dir.c_str(), true);
626
627       if(g_config->start_level.size() > 4 &&
628          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
629         g_screen_manager->push_screen(new worldmap::WorldMap(
630                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
631       } else {
632         std::auto_ptr<GameSession> session (
633           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
634
635         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
636         init_rand();//initialise generator with seed from session
637
638         if(g_config->start_demo != "")
639           session->play_demo(g_config->start_demo);
640
641         if(g_config->record_demo != "")
642           session->record_demo(g_config->record_demo);
643         g_screen_manager->push_screen(session.release());
644       }
645     } else {
646       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
647     }
648
649     g_screen_manager->run(context);
650   } catch(std::exception& e) {
651     log_fatal << "Unexpected exception: " << e.what() << std::endl;
652     result = 1;
653   } catch(...) {
654     log_fatal << "Unexpected exception" << std::endl;
655     result = 1;
656   }
657
658   delete g_screen_manager;
659   g_screen_manager = NULL;
660
661   Resources::unload_shared();
662   quit_audio();
663
664   if(g_config)
665     g_config->save();
666   delete g_config;
667   g_config = NULL;
668   delete g_jk_controller;
669   g_jk_controller = NULL;
670   delete Console::instance;
671   Console::instance = NULL;
672   scripting::exit_squirrel();
673   delete texture_manager;
674   texture_manager = NULL;
675   SDL_Quit();
676   PHYSFS_deinit();
677
678   return result;
679 }
680
681 /* EOF */