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 "video/renderer.hpp"
32 #include "supertux/main.hpp"
35 namespace supertux_apple {
36 # include <CoreFoundation/CoreFoundation.h>
37 } // namespace supertux_apple
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"
59 namespace { DrawingContext *context_pointer; }
62 # define WRITEDIR_NAME PACKAGE_NAME
64 # define WRITEDIR_NAME "." PACKAGE_NAME
70 g_config = new Config();
73 } catch(std::exception& e) {
74 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
79 Main::init_tinygettext()
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));
85 dictionary_manager->add_directory("locale");
86 dictionary_manager->set_charset("UTF-8");
88 // Config setting "locale" overrides language detection
89 if (g_config->locale != "")
91 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->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);
102 Main::init_physfs(const char* argv0)
104 if(!PHYSFS_init(argv0)) {
105 std::stringstream msg;
106 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
107 throw std::runtime_error(msg.str());
110 // allow symbolic links
111 PHYSFS_permitSymbolicLinks(1);
113 // Initialize physfs (this is a slightly modified version of
114 // PHYSFS_setSaneConfig)
115 const char *env_writedir;
116 std::string writedir;
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());
128 std::string userdir = PHYSFS_getUserDir();
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());
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());
149 PHYSFS_addToSearchPath(writedir.c_str(), 0);
151 // when started from source dir...
152 std::string dir = PHYSFS_getBaseDir();
153 if (dir[dir.length() - 1] != '/')
156 std::string testfname = dir;
157 testfname += "/credits.txt";
158 bool sourcedir = false;
159 FILE* f = fopen(testfname.c_str(), "r");
162 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
163 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
171 using namespace supertux_apple;
173 // when started from Application file on Mac OS X...
175 CFBundleRef mainBundle = CFBundleGetMainBundle();
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);
183 throw "Assertion failed: pathStr != 0";
184 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
185 CFRelease(mainBundleURL);
188 dir = std::string(path) + "/Contents/Resources/data";
189 testfname = dir + "/credits.txt";
191 f = fopen(testfname.c_str(), "r");
194 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
195 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
204 PHYSFS_addToSearchPath(".\\data", 1);
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
215 dir = br_find_data_dir(datadir.c_str());
220 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
221 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
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);
233 Main::print_usage(const char* argv0)
235 std::string default_user_data_dir =
236 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
238 std::cerr << boost::format(_(
240 "Usage: %s [OPTIONS] [LEVELFILE]\n\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"
261 "Environment variables:\n"
262 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
266 % argv0 % default_user_data_dir
271 * Options that should be evaluated prior to any initializations at all go here
274 Main::pre_parse_commandline(int argc, char** argv)
276 for(int i = 1; i < argc; ++i) {
277 std::string arg = argv[i];
279 if(arg == "--version" || arg == "-v") {
280 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
283 if(arg == "--help" || arg == "-h") {
284 print_usage(argv[0]);
287 if(arg == "--print-datadir") {
289 * Print the datadir searchpath to stdout, one path per
290 * line. Then exit. Intended for use by the supertux-editor.
294 sp = PHYSFS_getSearchPath();
296 for (sp_index = 0; sp[sp_index]; sp_index++)
297 std::cout << sp[sp_index] << std::endl;
307 * Options that should be evaluated after config is read go here
310 Main::parse_commandline(int argc, char** argv)
312 for(int i = 1; i < argc; ++i) {
313 std::string arg = argv[i];
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;
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
324 } else if(arg == "--window" || arg == "-w") {
325 g_config->use_fullscreen = false;
326 } else if(arg == "--geometry" || arg == "-g") {
330 print_usage(argv[0]);
331 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
336 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
338 print_usage(argv[0]);
339 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
343 g_config->window_size = Size(width, height);
344 g_config->fullscreen_size = Size(width, height);
347 } else if(arg == "--aspect" || arg == "-a") {
351 print_usage(argv[0]);
352 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
356 int aspect_width = 0;
357 int aspect_height = 0;
358 if (strcmp(argv[i], "auto") == 0)
363 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
365 print_usage(argv[0]);
366 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
370 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
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),
377 g_config->aspect_size = Size(600,
378 static_cast<int>(600 * 1/aspect_ratio + 0.5));
382 } else if(arg == "--renderer") {
386 print_usage(argv[0]);
387 throw std::runtime_error("Need to specify a renderer for renderer argument");
391 g_config->video = VideoSystem::get_video_system(argv[i]);
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") {
407 print_usage(argv[0]);
408 throw std::runtime_error("Need to specify a demo filename");
410 g_config->start_demo = argv[++i];
411 } else if(arg == "--record-demo") {
413 print_usage(argv[0]);
414 throw std::runtime_error("Need to specify a demo filename");
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;
422 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
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());
441 // SDL_EnableUNICODE(1); //old code, mofif by giby
442 // SDL_JoystickID myID = SDL_JoystickInstanceID(myOpenedStick);
445 // wait 100ms and clear SDL event queue because sometimes we have random
446 // joystick events in the queue on startup...
449 while(SDL_PollEvent(&dummy))
456 g_config->random_seed = gameRandom.srand(g_config->random_seed);
458 graphicsRandom.srand(0);
460 //const char *how = config->random_seed? ", user fixed.": ", from time().";
461 //log_info << "Using random seed " << config->random_seed << how << std::endl;
467 SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
469 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
470 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
473 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
477 SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
478 SDL_FreeSurface(icon);
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;
491 sound_manager = new SoundManager();
493 sound_manager->enable_sound(g_config->sound_enabled);
494 sound_manager->enable_music(g_config->music_enabled);
500 if(sound_manager != NULL) {
501 delete sound_manager;
502 sound_manager = NULL;
507 Main::wait_for_event(float min_delay, float max_delay)
509 assert(min_delay <= max_delay);
511 Uint32 min = (Uint32) (min_delay * 1000);
512 Uint32 max = (Uint32) (max_delay * 1000);
514 Uint32 ticks = SDL_GetTicks();
515 while(SDL_GetTicks() - ticks < min) {
517 sound_manager->update();
522 while (SDL_PollEvent(&event))
526 bool running = false;
527 ticks = SDL_GetTicks();
529 while(SDL_PollEvent(&event)) {
532 g_screen_manager->quit();
535 case SDL_JOYBUTTONDOWN:
536 case SDL_MOUSEBUTTONDOWN:
540 if(SDL_GetTicks() - ticks >= (max - min))
542 sound_manager->update();
547 static Uint32 last_timelog_ticks = 0;
548 static const char* last_timelog_component = 0;
550 static inline void timelog(const char* component)
552 Uint32 current_ticks = SDL_GetTicks();
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;
558 last_timelog_ticks = current_ticks;
559 last_timelog_component = component;
563 Main::run(int argc, char** argv)
568 /* Do this before pre_parse_commandline, because --help now shows the
569 * default user data dir. */
570 init_physfs(argv[0]);
572 if(pre_parse_commandline(argc, argv))
576 Console::instance = new Console();
578 timelog("controller");
579 g_jk_controller = new JoystickKeyboardController();
584 timelog("commandline");
585 if(parse_commandline(argc, argv))
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;
598 timelog("tinygettext");
601 Console::instance->init_graphics();
603 timelog("scripting");
604 scripting::init_squirrel(g_config->enable_script_debugger);
606 timelog("resources");
607 Resources::load_shared();
610 AddonManager::get_instance().load_addons();
614 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
616 g_screen_manager = new ScreenManager();
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);
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()));
632 std::auto_ptr<GameSession> session (
633 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
635 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
636 init_rand();//initialise generator with seed from session
638 if(g_config->start_demo != "")
639 session->play_demo(g_config->start_demo);
641 if(g_config->record_demo != "")
642 session->record_demo(g_config->record_demo);
643 g_screen_manager->push_screen(session.release());
646 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
649 g_screen_manager->run(context);
650 } catch(std::exception& e) {
651 log_fatal << "Unexpected exception: " << e.what() << std::endl;
654 log_fatal << "Unexpected exception" << std::endl;
658 delete g_screen_manager;
659 g_screen_manager = NULL;
661 Resources::unload_shared();
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;