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>
27 #include "supertux/main.hpp"
30 namespace supertux_apple {
31 # include <CoreFoundation/CoreFoundation.h>
32 } // namespace supertux_apple
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/joystickkeyboardcontroller.hpp"
38 #include "math/random_generator.hpp"
39 #include "physfs/ifile_stream.hpp"
40 #include "physfs/physfs_sdl.hpp"
41 #include "physfs/physfs_file_system.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/gameconfig.hpp"
44 #include "supertux/globals.hpp"
45 #include "supertux/player_status.hpp"
46 #include "supertux/screen_manager.hpp"
47 #include "supertux/resources.hpp"
48 #include "supertux/title_screen.hpp"
49 #include "util/file_system.hpp"
50 #include "util/gettext.hpp"
51 #include "video/drawing_context.hpp"
52 #include "worldmap/worldmap.hpp"
54 namespace { DrawingContext *context_pointer; }
57 # define WRITEDIR_NAME PACKAGE_NAME
59 # define WRITEDIR_NAME "." PACKAGE_NAME
65 g_config = new Config();
68 } catch(std::exception& e) {
69 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
74 Main::init_tinygettext()
76 dictionary_manager = new tinygettext::DictionaryManager();
77 tinygettext::Log::set_log_info_callback(0);
78 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
80 dictionary_manager->add_directory("locale");
81 dictionary_manager->set_charset("UTF-8");
83 // Config setting "locale" overrides language detection
84 if (g_config->locale != "")
86 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
91 Main::init_physfs(const char* argv0)
93 if(!PHYSFS_init(argv0)) {
94 std::stringstream msg;
95 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
96 throw std::runtime_error(msg.str());
99 // allow symbolic links
100 PHYSFS_permitSymbolicLinks(1);
102 // Initialize physfs (this is a slightly modified version of
103 // PHYSFS_setSaneConfig)
104 const char *env_writedir;
105 std::string writedir;
107 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
108 writedir = env_writedir;
109 if(!PHYSFS_setWriteDir(writedir.c_str())) {
110 std::ostringstream msg;
111 msg << "Failed to use configuration directory '"
112 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
117 std::string userdir = PHYSFS_getUserDir();
119 // Set configuration directory
120 writedir = userdir + WRITEDIR_NAME;
121 if(!PHYSFS_setWriteDir(writedir.c_str())) {
122 // try to create the directory
123 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
124 std::ostringstream msg;
125 msg << "Failed creating configuration directory '"
126 << writedir << "': " << PHYSFS_getLastError();
127 throw std::runtime_error(msg.str());
130 if(!PHYSFS_setWriteDir(writedir.c_str())) {
131 std::ostringstream msg;
132 msg << "Failed to use configuration directory '"
133 << writedir << "': " << PHYSFS_getLastError();
134 throw std::runtime_error(msg.str());
138 PHYSFS_addToSearchPath(writedir.c_str(), 0);
140 // when started from source dir...
141 std::string dir = PHYSFS_getBaseDir();
142 if (dir[dir.length() - 1] != '/')
145 std::string testfname = dir;
146 testfname += "/credits.txt";
147 bool sourcedir = false;
148 FILE* f = fopen(testfname.c_str(), "r");
151 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
152 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
160 using namespace supertux_apple;
162 // when started from Application file on Mac OS X...
164 CFBundleRef mainBundle = CFBundleGetMainBundle();
165 assert(mainBundle != 0);
166 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
167 assert(mainBundleURL != 0);
168 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
169 assert(pathStr != 0);
170 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
171 CFRelease(mainBundleURL);
174 dir = std::string(path) + "/Contents/Resources/data";
175 testfname = dir + "/credits.txt";
177 f = fopen(testfname.c_str(), "r");
180 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
181 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
190 PHYSFS_addToSearchPath(".\\data", 1);
194 std::string datadir = PHYSFS_getBaseDir();
195 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
196 datadir += "/" INSTALL_SUBDIR_SHARE;
197 #ifdef ENABLE_BINRELOC
201 dir = br_find_data_dir(datadir.c_str());
206 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
207 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
212 char** searchpath = PHYSFS_getSearchPath();
213 for(char** i = searchpath; *i != NULL; i++)
214 log_info << "[" << *i << "] is in the search path" << std::endl;
215 PHYSFS_freeList(searchpath);
219 Main::print_usage(const char* argv0)
221 std::string default_user_data_dir =
222 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
224 std::cerr << boost::format(_(
226 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
228 " -f, --fullscreen Run in fullscreen mode\n"
229 " -w, --window Run in window mode\n"
230 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
231 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
232 " -d, --default Reset video settings to default values\n"
233 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
234 " --disable-sfx Disable sound effects\n"
235 " --disable-music Disable music\n"
236 " -h, --help Show this help message and quit\n"
237 " -v, --version Show SuperTux version and quit\n"
238 " --console Enable ingame scripting console\n"
239 " --noconsole Disable ingame scripting console\n"
240 " --show-fps Display framerate in levels\n"
241 " --no-show-fps Do not display framerate in levels\n"
242 " --record-demo FILE LEVEL Record a demo to FILE\n"
243 " --play-demo FILE LEVEL Play a recorded demo\n"
244 " -s, --debug-scripts Enable script debugger.\n"
245 " --print-datadir Print supertux's primary data directory.\n"
247 "Environment variables:\n"
248 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
252 % argv0 % default_user_data_dir
257 * Options that should be evaluated prior to any initializations at all go here
260 Main::pre_parse_commandline(int argc, char** argv)
262 for(int i = 1; i < argc; ++i) {
263 std::string arg = argv[i];
265 if(arg == "--version" || arg == "-v") {
266 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
269 if(arg == "--help" || arg == "-h") {
270 print_usage(argv[0]);
273 if(arg == "--print-datadir") {
275 * Print the datadir searchpath to stdout, one path per
276 * line. Then exit. Intended for use by the supertux-editor.
280 sp = PHYSFS_getSearchPath();
282 for (sp_index = 0; sp[sp_index]; sp_index++)
283 std::cout << sp[sp_index] << std::endl;
293 * Options that should be evaluated after config is read go here
296 Main::parse_commandline(int argc, char** argv)
298 for(int i = 1; i < argc; ++i) {
299 std::string arg = argv[i];
301 if(arg == "--fullscreen" || arg == "-f") {
302 g_config->use_fullscreen = true;
303 } else if(arg == "--default" || arg == "-d") {
304 g_config->use_fullscreen = false;
306 g_config->window_size = Size(800, 600);
307 g_config->fullscreen_size = Size(800, 600);
308 g_config->aspect_size = Size(0, 0); // auto detect
310 } else if(arg == "--window" || arg == "-w") {
311 g_config->use_fullscreen = false;
312 } else if(arg == "--geometry" || arg == "-g") {
316 print_usage(argv[0]);
317 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
322 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
324 print_usage(argv[0]);
325 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
329 g_config->window_size = Size(width, height);
330 g_config->fullscreen_size = Size(width, height);
333 } else if(arg == "--aspect" || arg == "-a") {
337 print_usage(argv[0]);
338 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
342 int aspect_width = 0;
343 int aspect_height = 0;
344 if (strcmp(argv[i], "auto") == 0)
349 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
351 print_usage(argv[0]);
352 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
356 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
358 // use aspect ratio to calculate logical resolution
359 if (aspect_ratio > 1) {
360 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
363 g_config->aspect_size = Size(600,
364 static_cast<int>(600 * 1/aspect_ratio + 0.5));
368 } else if(arg == "--renderer") {
372 print_usage(argv[0]);
373 throw std::runtime_error("Need to specify a renderer for renderer argument");
377 g_config->video = VideoSystem::get_video_system(argv[i]);
379 } else if(arg == "--show-fps") {
380 g_config->show_fps = true;
381 } else if(arg == "--no-show-fps") {
382 g_config->show_fps = false;
383 } else if(arg == "--console") {
384 g_config->console_enabled = true;
385 } else if(arg == "--noconsole") {
386 g_config->console_enabled = false;
387 } else if(arg == "--disable-sfx") {
388 g_config->sound_enabled = false;
389 } else if(arg == "--disable-music") {
390 g_config->music_enabled = false;
391 } else if(arg == "--play-demo") {
393 print_usage(argv[0]);
394 throw std::runtime_error("Need to specify a demo filename");
396 g_config->start_demo = argv[++i];
397 } else if(arg == "--record-demo") {
399 print_usage(argv[0]);
400 throw std::runtime_error("Need to specify a demo filename");
402 g_config->record_demo = argv[++i];
403 } else if(arg == "--debug-scripts" || arg == "-s") {
404 g_config->enable_script_debugger = true;
405 } else if(arg[0] != '-') {
406 g_config->start_level = arg;
408 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
419 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
420 std::stringstream msg;
421 msg << "Couldn't initialize SDL: " << SDL_GetError();
422 throw std::runtime_error(msg.str());
427 SDL_EnableUNICODE(1);
429 // wait 100ms and clear SDL event queue because sometimes we have random
430 // joystick events in the queue on startup...
433 while(SDL_PollEvent(&dummy))
440 g_config->random_seed = gameRandom.srand(g_config->random_seed);
442 graphicsRandom.srand(0);
444 //const char *how = config->random_seed? ", user fixed.": ", from time().";
445 //log_info << "Using random seed " << config->random_seed << how << std::endl;
451 // FIXME: Add something here
455 context_pointer->init_renderer();
456 g_screen = SDL_GetVideoSurface();
458 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
462 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
464 const char* icon_fname = "images/engine/icons/supertux.xpm";
468 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
469 } catch (const std::runtime_error& err) {
471 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
474 SDL_WM_SetIcon(icon, 0);
475 SDL_FreeSurface(icon);
478 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
483 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
484 << " Window: " << g_config->window_size
485 << " Fullscreen: " << g_config->fullscreen_size
486 << " Area: " << g_config->aspect_size << std::endl;
492 sound_manager = new SoundManager();
494 sound_manager->enable_sound(g_config->sound_enabled);
495 sound_manager->enable_music(g_config->music_enabled);
501 if(sound_manager != NULL) {
502 delete sound_manager;
503 sound_manager = NULL;
508 Main::wait_for_event(float min_delay, float max_delay)
510 assert(min_delay <= max_delay);
512 Uint32 min = (Uint32) (min_delay * 1000);
513 Uint32 max = (Uint32) (max_delay * 1000);
515 Uint32 ticks = SDL_GetTicks();
516 while(SDL_GetTicks() - ticks < min) {
518 sound_manager->update();
523 while (SDL_PollEvent(&event))
527 bool running = false;
528 ticks = SDL_GetTicks();
530 while(SDL_PollEvent(&event)) {
533 g_screen_manager->quit();
536 case SDL_JOYBUTTONDOWN:
537 case SDL_MOUSEBUTTONDOWN:
541 if(SDL_GetTicks() - ticks >= (max - min))
543 sound_manager->update();
548 static Uint32 last_timelog_ticks = 0;
549 static const char* last_timelog_component = 0;
551 static inline void timelog(const char* component)
553 Uint32 current_ticks = SDL_GetTicks();
555 if(last_timelog_component != 0) {
556 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
559 last_timelog_ticks = current_ticks;
560 last_timelog_component = component;
564 Main::run(int argc, char** argv)
569 /* Do this before pre_parse_commandline, because --help now shows the
570 * default user data dir. */
571 init_physfs(argv[0]);
573 if(pre_parse_commandline(argc, argv))
576 Console::instance = new Console();
579 timelog("controller");
580 g_jk_controller = new JoystickKeyboardController();
586 AddonManager::get_instance().load_addons();
588 timelog("tinygettext");
591 timelog("commandline");
592 if(parse_commandline(argc, argv))
599 DrawingContext context;
600 context_pointer = &context;
603 Console::instance->init_graphics();
605 timelog("scripting");
606 scripting::init_squirrel(g_config->enable_script_debugger);
608 timelog("resources");
609 Resources::load_shared();
613 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
615 g_screen_manager = new ScreenManager();
619 if(g_config->start_level != "") {
620 // we have a normal path specified at commandline, not a physfs path.
621 // So we simply mount that path here...
622 std::string dir = FileSystem::dirname(g_config->start_level);
623 log_debug << "Adding dir: " << dir << std::endl;
624 PHYSFS_addToSearchPath(dir.c_str(), true);
626 if(g_config->start_level.size() > 4 &&
627 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
628 g_screen_manager->push_screen(new worldmap::WorldMap(
629 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
631 std::auto_ptr<GameSession> session (
632 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
634 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
635 init_rand();//initialise generator with seed from session
637 if(g_config->start_demo != "")
638 session->play_demo(g_config->start_demo);
640 if(g_config->record_demo != "")
641 session->record_demo(g_config->record_demo);
642 g_screen_manager->push_screen(session.release());
645 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
648 g_screen_manager->run(context);
649 } catch(std::exception& e) {
650 log_fatal << "Unexpected exception: " << e.what() << std::endl;
653 log_fatal << "Unexpected exception" << std::endl;
657 delete g_screen_manager;
658 g_screen_manager = NULL;
660 Resources::unload_shared();
667 delete g_jk_controller;
668 g_jk_controller = NULL;
669 delete Console::instance;
670 Console::instance = NULL;
671 scripting::exit_squirrel();
672 delete texture_manager;
673 texture_manager = NULL;