Fixed window title and icon, removed Renderer and Lightmap creation from DrawingConte...
[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   SCREEN_WIDTH  = 800;
468   SCREEN_HEIGHT = 600;
469
470   PHYSICAL_SCREEN_WIDTH = SCREEN_WIDTH;
471   PHYSICAL_SCREEN_HEIGHT = SCREEN_HEIGHT;
472
473   SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
474
475   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
476   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
477   if (!icon)
478   {
479     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
480   }
481   else
482   {
483     SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
484     SDL_FreeSurface(icon);
485   }
486   SDL_ShowCursor(0);
487
488   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
489            << " Window: "     << g_config->window_size
490            << " Fullscreen: " << g_config->fullscreen_size
491            << " Area: "       << g_config->aspect_size << std::endl;
492 }
493
494 void
495 Main::init_audio()
496 {
497   sound_manager = new SoundManager();
498
499   sound_manager->enable_sound(g_config->sound_enabled);
500   sound_manager->enable_music(g_config->music_enabled);
501 }
502
503 void
504 Main::quit_audio()
505 {
506   if(sound_manager != NULL) {
507     delete sound_manager;
508     sound_manager = NULL;
509   }
510 }
511
512 void
513 Main::wait_for_event(float min_delay, float max_delay)
514 {
515   assert(min_delay <= max_delay);
516
517   Uint32 min = (Uint32) (min_delay * 1000);
518   Uint32 max = (Uint32) (max_delay * 1000);
519
520   Uint32 ticks = SDL_GetTicks();
521   while(SDL_GetTicks() - ticks < min) {
522     SDL_Delay(10);
523     sound_manager->update();
524   }
525
526   // clear event queue
527   SDL_Event event;
528   while (SDL_PollEvent(&event))
529   {}
530
531   /* Handle events: */
532   bool running = false;
533   ticks = SDL_GetTicks();
534   while(running) {
535     while(SDL_PollEvent(&event)) {
536       switch(event.type) {
537         case SDL_QUIT:
538           g_screen_manager->quit();
539           break;
540         case SDL_KEYDOWN:
541         case SDL_JOYBUTTONDOWN:
542         case SDL_MOUSEBUTTONDOWN:
543           running = false;
544       }
545     }
546     if(SDL_GetTicks() - ticks >= (max - min))
547       running = false;
548     sound_manager->update();
549     SDL_Delay(10);
550   }
551 }
552
553 static Uint32 last_timelog_ticks = 0;
554 static const char* last_timelog_component = 0;
555
556 static inline void timelog(const char* component)
557 {
558   Uint32 current_ticks = SDL_GetTicks();
559
560   if(last_timelog_component != 0) {
561     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
562   }
563
564   last_timelog_ticks = current_ticks;
565   last_timelog_component = component;
566 }
567
568 int
569 Main::run(int argc, char** argv)
570 {
571   int result = 0;
572
573   try {
574     /* Do this before pre_parse_commandline, because --help now shows the
575      * default user data dir. */
576     init_physfs(argv[0]);
577
578     if(pre_parse_commandline(argc, argv))
579       return 0;
580
581     init_sdl();
582     Console::instance = new Console();
583
584     timelog("controller");
585     g_jk_controller = new JoystickKeyboardController();
586
587     timelog("config");
588     init_config();
589
590     timelog("commandline");
591     if(parse_commandline(argc, argv))
592       return 0;
593
594     timelog("video");
595     std::auto_ptr<Renderer> renderer(VideoSystem::new_renderer());
596     std::auto_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
597     DrawingContext context(*renderer, *lightmap);
598     context_pointer = &context;
599     init_video();
600     
601     timelog("audio");
602     init_audio();
603     
604     timelog("tinygettext");
605     init_tinygettext();
606
607     Console::instance->init_graphics();
608
609     timelog("scripting");
610     scripting::init_squirrel(g_config->enable_script_debugger);
611
612     timelog("resources");
613     Resources::load_shared();
614     
615     timelog("addons");
616     AddonManager::get_instance().load_addons();
617
618     timelog(0);
619
620     const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
621
622     g_screen_manager = new ScreenManager();
623
624     init_rand();
625
626     if(g_config->start_level != "") {
627       // we have a normal path specified at commandline, not a physfs path.
628       // So we simply mount that path here...
629       std::string dir = FileSystem::dirname(g_config->start_level);
630       log_debug << "Adding dir: " << dir << std::endl;
631       PHYSFS_addToSearchPath(dir.c_str(), true);
632
633       if(g_config->start_level.size() > 4 &&
634          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
635         g_screen_manager->push_screen(new worldmap::WorldMap(
636                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
637       } else {
638         std::auto_ptr<GameSession> session (
639           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
640
641         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
642         init_rand();//initialise generator with seed from session
643
644         if(g_config->start_demo != "")
645           session->play_demo(g_config->start_demo);
646
647         if(g_config->record_demo != "")
648           session->record_demo(g_config->record_demo);
649         g_screen_manager->push_screen(session.release());
650       }
651     } else {
652       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
653     }
654
655     g_screen_manager->run(context);
656   } catch(std::exception& e) {
657     log_fatal << "Unexpected exception: " << e.what() << std::endl;
658     result = 1;
659   } catch(...) {
660     log_fatal << "Unexpected exception" << std::endl;
661     result = 1;
662   }
663
664   delete g_screen_manager;
665   g_screen_manager = NULL;
666
667   Resources::unload_shared();
668   quit_audio();
669
670   if(g_config)
671     g_config->save();
672   delete g_config;
673   g_config = NULL;
674   delete g_jk_controller;
675   g_jk_controller = NULL;
676   delete Console::instance;
677   Console::instance = NULL;
678   scripting::exit_squirrel();
679   delete texture_manager;
680   texture_manager = NULL;
681   SDL_Quit();
682   PHYSFS_deinit();
683
684   return result;
685 }
686
687 /* EOF */