2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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.
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.
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/>.
20 #include <SDL_image.h>
24 #include <tinygettext/log.hpp>
25 #include <boost/format.hpp>
28 #include <findlocale.h>
31 #include "supertux/main.hpp"
34 namespace supertux_apple {
35 # include <CoreFoundation/CoreFoundation.h>
36 } // namespace supertux_apple
39 #include "addon/addon_manager.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "control/joystickkeyboardcontroller.hpp"
42 #include "math/random_generator.hpp"
43 #include "physfs/ifile_stream.hpp"
44 #include "physfs/physfs_sdl.hpp"
45 #include "physfs/physfs_file_system.hpp"
46 #include "scripting/squirrel_util.hpp"
47 #include "supertux/gameconfig.hpp"
48 #include "supertux/globals.hpp"
49 #include "supertux/player_status.hpp"
50 #include "supertux/screen_manager.hpp"
51 #include "supertux/resources.hpp"
52 #include "supertux/title_screen.hpp"
53 #include "util/file_system.hpp"
54 #include "util/gettext.hpp"
55 #include "video/drawing_context.hpp"
56 #include "worldmap/worldmap.hpp"
58 namespace { DrawingContext *context_pointer; }
61 # define WRITEDIR_NAME PACKAGE_NAME
63 # define WRITEDIR_NAME "." PACKAGE_NAME
69 g_config = new Config();
72 } catch(std::exception& e) {
73 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
78 Main::init_tinygettext()
80 dictionary_manager = new tinygettext::DictionaryManager();
81 tinygettext::Log::set_log_info_callback(0);
82 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
84 dictionary_manager->add_directory("locale");
85 dictionary_manager->set_charset("UTF-8");
87 // Config setting "locale" overrides language detection
88 if (g_config->locale != "")
90 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
93 FL_FindLocale(&locale);
94 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
95 FL_FreeLocale(&locale);
96 dictionary_manager->set_language(language);
101 Main::init_physfs(const char* argv0)
103 if(!PHYSFS_init(argv0)) {
104 std::stringstream msg;
105 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
106 throw std::runtime_error(msg.str());
109 // allow symbolic links
110 PHYSFS_permitSymbolicLinks(1);
112 // Initialize physfs (this is a slightly modified version of
113 // PHYSFS_setSaneConfig)
114 const char *env_writedir;
115 std::string writedir;
117 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
118 writedir = env_writedir;
119 if(!PHYSFS_setWriteDir(writedir.c_str())) {
120 std::ostringstream msg;
121 msg << "Failed to use configuration directory '"
122 << writedir << "': " << PHYSFS_getLastError();
123 throw std::runtime_error(msg.str());
127 std::string userdir = PHYSFS_getUserDir();
129 // Set configuration directory
130 writedir = userdir + WRITEDIR_NAME;
131 if(!PHYSFS_setWriteDir(writedir.c_str())) {
132 // try to create the directory
133 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
134 std::ostringstream msg;
135 msg << "Failed creating configuration directory '"
136 << writedir << "': " << PHYSFS_getLastError();
137 throw std::runtime_error(msg.str());
140 if(!PHYSFS_setWriteDir(writedir.c_str())) {
141 std::ostringstream msg;
142 msg << "Failed to use configuration directory '"
143 << writedir << "': " << PHYSFS_getLastError();
144 throw std::runtime_error(msg.str());
148 PHYSFS_addToSearchPath(writedir.c_str(), 0);
150 // when started from source dir...
151 std::string dir = PHYSFS_getBaseDir();
152 if (dir[dir.length() - 1] != '/')
155 std::string testfname = dir;
156 testfname += "/credits.txt";
157 bool sourcedir = false;
158 FILE* f = fopen(testfname.c_str(), "r");
161 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
162 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
170 using namespace supertux_apple;
172 // when started from Application file on Mac OS X...
174 CFBundleRef mainBundle = CFBundleGetMainBundle();
176 throw "Assertion failed: mainBundle != 0";
177 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
178 if(mainBundleURL == 0)
179 throw "Assertion failed: mainBundleURL != 0";
180 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
182 throw "Assertion failed: pathStr != 0";
183 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
184 CFRelease(mainBundleURL);
187 dir = std::string(path) + "/Contents/Resources/data";
188 testfname = dir + "/credits.txt";
190 f = fopen(testfname.c_str(), "r");
193 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
194 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
203 PHYSFS_addToSearchPath(".\\data", 1);
207 std::string datadir = PHYSFS_getBaseDir();
208 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
209 datadir += "/" INSTALL_SUBDIR_SHARE;
210 #ifdef ENABLE_BINRELOC
214 dir = br_find_data_dir(datadir.c_str());
219 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
220 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
225 char** searchpath = PHYSFS_getSearchPath();
226 for(char** i = searchpath; *i != NULL; i++)
227 log_info << "[" << *i << "] is in the search path" << std::endl;
228 PHYSFS_freeList(searchpath);
232 Main::print_usage(const char* argv0)
234 std::string default_user_data_dir =
235 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
237 std::cerr << boost::format(_(
239 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
241 " -f, --fullscreen Run in fullscreen mode\n"
242 " -w, --window Run in window mode\n"
243 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
244 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
245 " -d, --default Reset video settings to default values\n"
246 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
247 " --disable-sfx Disable sound effects\n"
248 " --disable-music Disable music\n"
249 " -h, --help Show this help message and quit\n"
250 " -v, --version Show SuperTux version and quit\n"
251 " --console Enable ingame scripting console\n"
252 " --noconsole Disable ingame scripting console\n"
253 " --show-fps Display framerate in levels\n"
254 " --no-show-fps Do not display framerate in levels\n"
255 " --record-demo FILE LEVEL Record a demo to FILE\n"
256 " --play-demo FILE LEVEL Play a recorded demo\n"
257 " -s, --debug-scripts Enable script debugger.\n"
258 " --print-datadir Print supertux's primary data directory.\n"
260 "Environment variables:\n"
261 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
265 % argv0 % default_user_data_dir
270 * Options that should be evaluated prior to any initializations at all go here
273 Main::pre_parse_commandline(int argc, char** argv)
275 for(int i = 1; i < argc; ++i) {
276 std::string arg = argv[i];
278 if(arg == "--version" || arg == "-v") {
279 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
282 if(arg == "--help" || arg == "-h") {
283 print_usage(argv[0]);
286 if(arg == "--print-datadir") {
288 * Print the datadir searchpath to stdout, one path per
289 * line. Then exit. Intended for use by the supertux-editor.
293 sp = PHYSFS_getSearchPath();
295 for (sp_index = 0; sp[sp_index]; sp_index++)
296 std::cout << sp[sp_index] << std::endl;
306 * Options that should be evaluated after config is read go here
309 Main::parse_commandline(int argc, char** argv)
311 for(int i = 1; i < argc; ++i) {
312 std::string arg = argv[i];
314 if(arg == "--fullscreen" || arg == "-f") {
315 g_config->use_fullscreen = true;
316 } else if(arg == "--default" || arg == "-d") {
317 g_config->use_fullscreen = false;
319 g_config->window_size = Size(800, 600);
320 g_config->fullscreen_size = Size(800, 600);
321 g_config->aspect_size = Size(0, 0); // auto detect
323 } else if(arg == "--window" || arg == "-w") {
324 g_config->use_fullscreen = false;
325 } else if(arg == "--geometry" || arg == "-g") {
329 print_usage(argv[0]);
330 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
335 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
337 print_usage(argv[0]);
338 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
342 g_config->window_size = Size(width, height);
343 g_config->fullscreen_size = Size(width, height);
346 } else if(arg == "--aspect" || arg == "-a") {
350 print_usage(argv[0]);
351 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
355 int aspect_width = 0;
356 int aspect_height = 0;
357 if (strcmp(argv[i], "auto") == 0)
362 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
364 print_usage(argv[0]);
365 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
369 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
371 // use aspect ratio to calculate logical resolution
372 if (aspect_ratio > 1) {
373 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
376 g_config->aspect_size = Size(600,
377 static_cast<int>(600 * 1/aspect_ratio + 0.5));
381 } else if(arg == "--renderer") {
385 print_usage(argv[0]);
386 throw std::runtime_error("Need to specify a renderer for renderer argument");
390 g_config->video = VideoSystem::get_video_system(argv[i]);
392 } else if(arg == "--show-fps") {
393 g_config->show_fps = true;
394 } else if(arg == "--no-show-fps") {
395 g_config->show_fps = false;
396 } else if(arg == "--console") {
397 g_config->console_enabled = true;
398 } else if(arg == "--noconsole") {
399 g_config->console_enabled = false;
400 } else if(arg == "--disable-sfx") {
401 g_config->sound_enabled = false;
402 } else if(arg == "--disable-music") {
403 g_config->music_enabled = false;
404 } else if(arg == "--play-demo") {
406 print_usage(argv[0]);
407 throw std::runtime_error("Need to specify a demo filename");
409 g_config->start_demo = argv[++i];
410 } else if(arg == "--record-demo") {
412 print_usage(argv[0]);
413 throw std::runtime_error("Need to specify a demo filename");
415 g_config->record_demo = argv[++i];
416 } else if(arg == "--debug-scripts" || arg == "-s") {
417 g_config->enable_script_debugger = true;
418 } else if(arg[0] != '-') {
419 g_config->start_level = arg;
421 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
432 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
433 std::stringstream msg;
434 msg << "Couldn't initialize SDL: " << SDL_GetError();
435 throw std::runtime_error(msg.str());
440 // SDL_EnableUNICODE(1); //old code, mofif by giby
441 // SDL_JoystickID myID = SDL_JoystickInstanceID(myOpenedStick);
444 // wait 100ms and clear SDL event queue because sometimes we have random
445 // joystick events in the queue on startup...
448 while(SDL_PollEvent(&dummy))
455 g_config->random_seed = gameRandom.srand(g_config->random_seed);
457 graphicsRandom.srand(0);
459 //const char *how = config->random_seed? ", user fixed.": ", from time().";
460 //log_info << "Using random seed " << config->random_seed << how << std::endl;
466 // FIXME: Add something here
470 context_pointer->init_renderer();
473 // SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
475 /* // set icon -- Original part B4 SDL2
477 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
479 const char* icon_fname = "images/engine/icons/supertux.xpm";
483 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
484 } catch (const std::runtime_error& err) {
486 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
489 SDL_WM_SetIcon(icon, 0); //now SDL_SetWindowIcon(window, surface); if needed
490 SDL_FreeSurface(icon);
493 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
497 // SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
501 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
503 const char* icon_fname = "images/engine/icons/supertux.xpm";
505 SDL_Window* icon = 0;
507 //icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
508 } catch (const std::runtime_error& err) {
509 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
512 // SDL_SetWindowIcon(icon, 0); //now SDL_SetWindowIcon(window, surface); if needed
513 // SDL_FreeSurface(icon);
516 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
522 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
524 const char* icon_fname = "images/engine/icons/supertux.xpm";
527 SDL_Window icon = SDL_CreateWindow(PACKAGE_NAME " " PACKAGE_VERSION,
528 SDL_WINDOWPOS_UNDEFINED,
529 SDL_WINDOWPOS_UNDEFINED,
531 SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL);
532 // not sure of that */
536 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
537 << " Window: " << g_config->window_size
538 << " Fullscreen: " << g_config->fullscreen_size
539 << " Area: " << g_config->aspect_size << std::endl;
545 sound_manager = new SoundManager();
547 sound_manager->enable_sound(g_config->sound_enabled);
548 sound_manager->enable_music(g_config->music_enabled);
554 if(sound_manager != NULL) {
555 delete sound_manager;
556 sound_manager = NULL;
561 Main::wait_for_event(float min_delay, float max_delay)
563 assert(min_delay <= max_delay);
565 Uint32 min = (Uint32) (min_delay * 1000);
566 Uint32 max = (Uint32) (max_delay * 1000);
568 Uint32 ticks = SDL_GetTicks();
569 while(SDL_GetTicks() - ticks < min) {
571 sound_manager->update();
576 while (SDL_PollEvent(&event))
580 bool running = false;
581 ticks = SDL_GetTicks();
583 while(SDL_PollEvent(&event)) {
586 g_screen_manager->quit();
589 case SDL_JOYBUTTONDOWN:
590 case SDL_MOUSEBUTTONDOWN:
594 if(SDL_GetTicks() - ticks >= (max - min))
596 sound_manager->update();
601 static Uint32 last_timelog_ticks = 0;
602 static const char* last_timelog_component = 0;
604 static inline void timelog(const char* component)
606 Uint32 current_ticks = SDL_GetTicks();
608 if(last_timelog_component != 0) {
609 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
612 last_timelog_ticks = current_ticks;
613 last_timelog_component = component;
617 Main::run(int argc, char** argv)
622 /* Do this before pre_parse_commandline, because --help now shows the
623 * default user data dir. */
624 init_physfs(argv[0]);
626 if(pre_parse_commandline(argc, argv))
630 Console::instance = new Console();
632 timelog("controller");
633 g_jk_controller = new JoystickKeyboardController();
638 timelog("commandline");
639 if(parse_commandline(argc, argv))
643 DrawingContext context;
644 context_pointer = &context;
650 timelog("tinygettext");
653 Console::instance->init_graphics();
655 timelog("scripting");
656 scripting::init_squirrel(g_config->enable_script_debugger);
658 timelog("resources");
659 Resources::load_shared();
662 AddonManager::get_instance().load_addons();
666 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
668 g_screen_manager = new ScreenManager();
672 if(g_config->start_level != "") {
673 // we have a normal path specified at commandline, not a physfs path.
674 // So we simply mount that path here...
675 std::string dir = FileSystem::dirname(g_config->start_level);
676 log_debug << "Adding dir: " << dir << std::endl;
677 PHYSFS_addToSearchPath(dir.c_str(), true);
679 if(g_config->start_level.size() > 4 &&
680 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
681 g_screen_manager->push_screen(new worldmap::WorldMap(
682 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
684 std::auto_ptr<GameSession> session (
685 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
687 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
688 init_rand();//initialise generator with seed from session
690 if(g_config->start_demo != "")
691 session->play_demo(g_config->start_demo);
693 if(g_config->record_demo != "")
694 session->record_demo(g_config->record_demo);
695 g_screen_manager->push_screen(session.release());
698 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
701 g_screen_manager->run(context);
702 } catch(std::exception& e) {
703 log_fatal << "Unexpected exception: " << e.what() << std::endl;
706 log_fatal << "Unexpected exception" << std::endl;
710 delete g_screen_manager;
711 g_screen_manager = NULL;
713 Resources::unload_shared();
720 delete g_jk_controller;
721 g_jk_controller = NULL;
722 delete Console::instance;
723 Console::instance = NULL;
724 scripting::exit_squirrel();
725 delete texture_manager;
726 texture_manager = NULL;