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; }
59 g_config = new Config();
62 } catch(std::exception& e) {
63 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
68 Main::init_tinygettext()
70 dictionary_manager = new tinygettext::DictionaryManager();
71 tinygettext::Log::set_log_info_callback(0);
72 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
74 dictionary_manager->add_directory("locale");
75 dictionary_manager->set_charset("UTF-8");
77 // Config setting "locale" overrides language detection
78 if (g_config->locale != "")
80 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
85 Main::init_physfs(const char* argv0)
87 if(!PHYSFS_init(argv0)) {
88 std::stringstream msg;
89 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
90 throw std::runtime_error(msg.str());
93 // allow symbolic links
94 PHYSFS_permitSymbolicLinks(1);
96 // Initialize physfs (this is a slightly modified version of
97 // PHYSFS_setSaneConfig)
98 const char* application = PACKAGE_NAME;
99 const char* userdir = PHYSFS_getUserDir();
101 char* writedir = new char[strlen(userdir) + strlen(application) +
108 // Set configuration directory
115 userdir, application);
116 if(!PHYSFS_setWriteDir(writedir)) {
117 // try to create the directory
118 char* mkdir = new char[strlen(application) +
131 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
132 std::ostringstream msg;
133 msg << "Failed creating configuration directory '"
134 << writedir << "': " << PHYSFS_getLastError();
137 throw std::runtime_error(msg.str());
141 if(!PHYSFS_setWriteDir(writedir)) {
142 std::ostringstream msg;
143 msg << "Failed to use configuration directory '"
144 << writedir << "': " << PHYSFS_getLastError();
146 throw std::runtime_error(msg.str());
149 PHYSFS_addToSearchPath(writedir, 0);
152 // when started from source dir...
153 std::string dir = PHYSFS_getBaseDir();
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();
175 assert(mainBundle != 0);
176 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
177 assert(mainBundleURL != 0);
178 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
179 assert(pathStr != 0);
180 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
181 CFRelease(mainBundleURL);
184 dir = std::string(path) + "/Contents/Resources/data";
185 testfname = dir + "/credits.txt";
187 f = fopen(testfname.c_str(), "r");
190 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
191 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
200 PHYSFS_addToSearchPath(".\\data", 1);
204 std::string datadir = PHYSFS_getBaseDir();
205 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
206 datadir += "/" INSTALL_SUBDIR_SHARE;
207 #ifdef ENABLE_BINRELOC
211 dir = br_find_data_dir(datadir.c_str());
216 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
217 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
222 char** searchpath = PHYSFS_getSearchPath();
223 for(char** i = searchpath; *i != NULL; i++)
224 log_info << "[" << *i << "] is in the search path" << std::endl;
225 PHYSFS_freeList(searchpath);
229 Main::print_usage(const char* argv0)
231 std::cerr << boost::format(_(
233 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
235 " -f, --fullscreen Run in fullscreen mode\n"
236 " -w, --window Run in window mode\n"
237 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
238 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
239 " -d, --default Reset video settings to default values\n"
240 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
241 " --disable-sfx Disable sound effects\n"
242 " --disable-music Disable music\n"
243 " -h, --help Show this help message and quit\n"
244 " -v, --version Show SuperTux version and quit\n"
245 " --console Enable ingame scripting console\n"
246 " --noconsole Disable ingame scripting console\n"
247 " --show-fps Display framerate in levels\n"
248 " --no-show-fps Do not display framerate in levels\n"
249 " --record-demo FILE LEVEL Record a demo to FILE\n"
250 " --play-demo FILE LEVEL Play a recorded demo\n"
251 " -s, --debug-scripts Enable script debugger.\n"
259 * Options that should be evaluated prior to any initializations at all go here
262 Main::pre_parse_commandline(int argc, char** argv)
264 for(int i = 1; i < argc; ++i) {
265 std::string arg = argv[i];
267 if(arg == "--version" || arg == "-v") {
268 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
271 if(arg == "--help" || arg == "-h") {
272 print_usage(argv[0]);
281 * Options that should be evaluated after config is read go here
284 Main::parse_commandline(int argc, char** argv)
286 for(int i = 1; i < argc; ++i) {
287 std::string arg = argv[i];
289 if(arg == "--fullscreen" || arg == "-f") {
290 g_config->use_fullscreen = true;
291 } else if(arg == "--default" || arg == "-d") {
292 g_config->use_fullscreen = false;
294 g_config->window_size = Size(800, 600);
295 g_config->fullscreen_size = Size(800, 600);
296 g_config->aspect_size = Size(0, 0); // auto detect
298 } else if(arg == "--window" || arg == "-w") {
299 g_config->use_fullscreen = false;
300 } else if(arg == "--geometry" || arg == "-g") {
304 print_usage(argv[0]);
305 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
310 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
312 print_usage(argv[0]);
313 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
317 g_config->window_size = Size(width, height);
318 g_config->fullscreen_size = Size(width, height);
321 } else if(arg == "--aspect" || arg == "-a") {
325 print_usage(argv[0]);
326 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
330 int aspect_width = 0;
331 int aspect_height = 0;
332 if (strcmp(argv[i], "auto") == 0)
337 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
339 print_usage(argv[0]);
340 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
344 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
346 // use aspect ratio to calculate logical resolution
347 if (aspect_ratio > 1) {
348 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
351 g_config->aspect_size = Size(600,
352 static_cast<int>(600 * 1/aspect_ratio + 0.5));
356 } else if(arg == "--renderer") {
360 print_usage(argv[0]);
361 throw std::runtime_error("Need to specify a renderer for renderer argument");
365 g_config->video = VideoSystem::get_video_system(argv[i]);
367 } else if(arg == "--show-fps") {
368 g_config->show_fps = true;
369 } else if(arg == "--no-show-fps") {
370 g_config->show_fps = false;
371 } else if(arg == "--console") {
372 g_config->console_enabled = true;
373 } else if(arg == "--noconsole") {
374 g_config->console_enabled = false;
375 } else if(arg == "--disable-sfx") {
376 g_config->sound_enabled = false;
377 } else if(arg == "--disable-music") {
378 g_config->music_enabled = false;
379 } else if(arg == "--play-demo") {
381 print_usage(argv[0]);
382 throw std::runtime_error("Need to specify a demo filename");
384 g_config->start_demo = argv[++i];
385 } else if(arg == "--record-demo") {
387 print_usage(argv[0]);
388 throw std::runtime_error("Need to specify a demo filename");
390 g_config->record_demo = argv[++i];
391 } else if(arg == "--debug-scripts" || arg == "-s") {
392 g_config->enable_script_debugger = true;
393 } else if(arg[0] != '-') {
394 g_config->start_level = arg;
396 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
407 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
408 std::stringstream msg;
409 msg << "Couldn't initialize SDL: " << SDL_GetError();
410 throw std::runtime_error(msg.str());
415 SDL_EnableUNICODE(1);
417 // wait 100ms and clear SDL event queue because sometimes we have random
418 // joystick events in the queue on startup...
421 while(SDL_PollEvent(&dummy))
428 g_config->random_seed = gameRandom.srand(g_config->random_seed);
430 graphicsRandom.srand(0);
432 //const char *how = config->random_seed? ", user fixed.": ", from time().";
433 //log_info << "Using random seed " << config->random_seed << how << std::endl;
439 // FIXME: Add something here
443 context_pointer->init_renderer();
444 g_screen = SDL_GetVideoSurface();
446 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
450 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
452 const char* icon_fname = "images/engine/icons/supertux.xpm";
456 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
457 } catch (const std::runtime_error& err) {
459 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
462 SDL_WM_SetIcon(icon, 0);
463 SDL_FreeSurface(icon);
466 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
471 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
472 << " Window: " << g_config->window_size
473 << " Fullscreen: " << g_config->fullscreen_size
474 << " Area: " << g_config->aspect_size << std::endl;
480 sound_manager = new SoundManager();
482 sound_manager->enable_sound(g_config->sound_enabled);
483 sound_manager->enable_music(g_config->music_enabled);
489 if(sound_manager != NULL) {
490 delete sound_manager;
491 sound_manager = NULL;
496 Main::wait_for_event(float min_delay, float max_delay)
498 assert(min_delay <= max_delay);
500 Uint32 min = (Uint32) (min_delay * 1000);
501 Uint32 max = (Uint32) (max_delay * 1000);
503 Uint32 ticks = SDL_GetTicks();
504 while(SDL_GetTicks() - ticks < min) {
506 sound_manager->update();
511 while (SDL_PollEvent(&event))
515 bool running = false;
516 ticks = SDL_GetTicks();
518 while(SDL_PollEvent(&event)) {
521 g_screen_manager->quit();
524 case SDL_JOYBUTTONDOWN:
525 case SDL_MOUSEBUTTONDOWN:
529 if(SDL_GetTicks() - ticks >= (max - min))
531 sound_manager->update();
536 static Uint32 last_timelog_ticks = 0;
537 static const char* last_timelog_component = 0;
539 static inline void timelog(const char* component)
541 Uint32 current_ticks = SDL_GetTicks();
543 if(last_timelog_component != 0) {
544 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
547 last_timelog_ticks = current_ticks;
548 last_timelog_component = component;
552 Main::run(int argc, char** argv)
558 if(pre_parse_commandline(argc, argv))
561 Console::instance = new Console();
562 init_physfs(argv[0]);
565 timelog("controller");
566 g_jk_controller = new JoystickKeyboardController();
572 AddonManager::get_instance().load_addons();
574 timelog("tinygettext");
577 timelog("commandline");
578 if(parse_commandline(argc, argv))
585 DrawingContext context;
586 context_pointer = &context;
589 Console::instance->init_graphics();
591 timelog("scripting");
592 scripting::init_squirrel(g_config->enable_script_debugger);
594 timelog("resources");
595 Resources::load_shared();
599 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
601 g_screen_manager = new ScreenManager();
605 if(g_config->start_level != "") {
606 // we have a normal path specified at commandline, not a physfs path.
607 // So we simply mount that path here...
608 std::string dir = FileSystem::dirname(g_config->start_level);
609 log_debug << "Adding dir: " << dir << std::endl;
610 PHYSFS_addToSearchPath(dir.c_str(), true);
612 if(g_config->start_level.size() > 4 &&
613 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
614 g_screen_manager->push_screen(new worldmap::WorldMap(
615 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
617 std::auto_ptr<GameSession> session (
618 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
620 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
621 init_rand();//initialise generator with seed from session
623 if(g_config->start_demo != "")
624 session->play_demo(g_config->start_demo);
626 if(g_config->record_demo != "")
627 session->record_demo(g_config->record_demo);
628 g_screen_manager->push_screen(session.release());
631 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
634 g_screen_manager->run(context);
635 } catch(std::exception& e) {
636 log_fatal << "Unexpected exception: " << e.what() << std::endl;
639 log_fatal << "Unexpected exception" << std::endl;
643 delete g_screen_manager;
644 g_screen_manager = NULL;
646 Resources::unload_shared();
653 delete g_jk_controller;
654 g_jk_controller = NULL;
655 delete Console::instance;
656 Console::instance = NULL;
657 scripting::exit_squirrel();
658 delete texture_manager;
659 texture_manager = NULL;