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>
26 #include "supertux/main.hpp"
29 namespace supertux_apple {
30 # include <CoreFoundation/CoreFoundation.h>
31 } // namespace supertux_apple
34 #include "addon/addon_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "control/joystickkeyboardcontroller.hpp"
37 #include "math/random_generator.hpp"
38 #include "physfs/ifile_stream.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "physfs/physfs_file_system.hpp"
41 #include "scripting/squirrel_util.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/player_status.hpp"
45 #include "supertux/screen_manager.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/title_screen.hpp"
48 #include "util/file_system.hpp"
49 #include "util/gettext.hpp"
50 #include "video/drawing_context.hpp"
51 #include "worldmap/worldmap.hpp"
53 namespace { DrawingContext *context_pointer; }
58 g_config = new Config();
61 } catch(std::exception& e) {
62 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
67 Main::init_tinygettext()
69 dictionary_manager = new tinygettext::DictionaryManager();
70 tinygettext::Log::set_log_info_callback(0);
71 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
73 dictionary_manager->add_directory("locale");
74 dictionary_manager->set_charset("UTF-8");
76 // Config setting "locale" overrides language detection
77 if (g_config->locale != "")
79 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
84 Main::init_physfs(const char* argv0)
86 if(!PHYSFS_init(argv0)) {
87 std::stringstream msg;
88 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
89 throw std::runtime_error(msg.str());
92 // allow symbolic links
93 PHYSFS_permitSymbolicLinks(1);
95 // Initialize physfs (this is a slightly modified version of
96 // PHYSFS_setSaneConfig)
97 const char* application = PACKAGE_NAME;
98 const char* userdir = PHYSFS_getUserDir();
99 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
101 // Set configuration directory
102 sprintf(writedir, "%s.%s", userdir, application);
103 if(!PHYSFS_setWriteDir(writedir)) {
104 // try to create the directory
105 char* mkdir = new char[strlen(application) + 2];
106 sprintf(mkdir, ".%s", application);
107 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
108 std::ostringstream msg;
109 msg << "Failed creating configuration directory '"
110 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
117 if(!PHYSFS_setWriteDir(writedir)) {
118 std::ostringstream msg;
119 msg << "Failed to use configuration directory '"
120 << writedir << "': " << PHYSFS_getLastError();
122 throw std::runtime_error(msg.str());
125 PHYSFS_addToSearchPath(writedir, 0);
128 // when started from source dir...
129 std::string dir = PHYSFS_getBaseDir();
131 std::string testfname = dir;
132 testfname += "/credits.txt";
133 bool sourcedir = false;
134 FILE* f = fopen(testfname.c_str(), "r");
137 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
138 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
146 using namespace supertux_apple;
148 // when started from Application file on Mac OS X...
150 CFBundleRef mainBundle = CFBundleGetMainBundle();
151 assert(mainBundle != 0);
152 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
153 assert(mainBundleURL != 0);
154 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
155 assert(pathStr != 0);
156 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
157 CFRelease(mainBundleURL);
160 dir = std::string(path) + "/Contents/Resources/data";
161 testfname = dir + "/credits.txt";
163 f = fopen(testfname.c_str(), "r");
166 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
167 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
176 PHYSFS_addToSearchPath(".\\data", 1);
180 std::string datadir = PHYSFS_getBaseDir();
181 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
182 datadir += "/" INSTALL_SUBDIR_SHARE;
183 #ifdef ENABLE_BINRELOC
187 dir = br_find_data_dir(datadir.c_str());
192 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
193 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
198 char** searchpath = PHYSFS_getSearchPath();
199 for(char** i = searchpath; *i != NULL; i++)
200 log_info << "[" << *i << "] is in the search path" << std::endl;
201 PHYSFS_freeList(searchpath);
205 Main::print_usage(const char* argv0)
207 std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
209 " -f, --fullscreen Run in fullscreen mode\n"
210 " -w, --window Run in window mode\n"
211 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
212 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
213 " -d, --default Reset video settings to default values\n"
214 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
215 " --disable-sfx Disable sound effects\n"
216 " --disable-music Disable music\n"
217 " -h, --help Show this help message and quit\n"
218 " -v, --version Show SuperTux version and quit\n"
219 " --console Enable ingame scripting console\n"
220 " --noconsole Disable ingame scripting console\n"
221 " --show-fps Display framerate in levels\n"
222 " --no-show-fps Do not display framerate in levels\n"
223 " --record-demo FILE LEVEL Record a demo to FILE\n"
224 " --play-demo FILE LEVEL Play a recorded demo\n"
225 " -s, --debug-scripts Enable script debugger.\n"
231 * Options that should be evaluated prior to any initializations at all go here
234 Main::pre_parse_commandline(int argc, char** argv)
236 for(int i = 1; i < argc; ++i) {
237 std::string arg = argv[i];
239 if(arg == "--version" || arg == "-v") {
240 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
243 if(arg == "--help" || arg == "-h") {
244 print_usage(argv[0]);
253 * Options that should be evaluated after config is read go here
256 Main::parse_commandline(int argc, char** argv)
258 for(int i = 1; i < argc; ++i) {
259 std::string arg = argv[i];
261 if(arg == "--fullscreen" || arg == "-f") {
262 g_config->use_fullscreen = true;
263 } else if(arg == "--default" || arg == "-d") {
264 g_config->use_fullscreen = false;
266 g_config->window_size = Size(800, 600);
267 g_config->fullscreen_size = Size(800, 600);
268 g_config->aspect_size = Size(0, 0); // auto detect
270 } else if(arg == "--window" || arg == "-w") {
271 g_config->use_fullscreen = false;
272 } else if(arg == "--geometry" || arg == "-g") {
276 print_usage(argv[0]);
277 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
282 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
284 print_usage(argv[0]);
285 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
289 g_config->window_size = Size(width, height);
290 g_config->fullscreen_size = Size(width, height);
293 } else if(arg == "--aspect" || arg == "-a") {
297 print_usage(argv[0]);
298 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
302 int aspect_width = 0;
303 int aspect_height = 0;
304 if (strcmp(argv[i], "auto") == 0)
309 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
311 print_usage(argv[0]);
312 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
316 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
318 // use aspect ratio to calculate logical resolution
319 if (aspect_ratio > 1) {
320 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
323 g_config->aspect_size = Size(600,
324 static_cast<int>(600 * 1/aspect_ratio + 0.5));
328 } else if(arg == "--renderer") {
332 print_usage(argv[0]);
333 throw std::runtime_error("Need to specify a renderer for renderer argument");
337 g_config->video = VideoSystem::get_video_system(argv[i]);
339 } else if(arg == "--show-fps") {
340 g_config->show_fps = true;
341 } else if(arg == "--no-show-fps") {
342 g_config->show_fps = false;
343 } else if(arg == "--console") {
344 g_config->console_enabled = true;
345 } else if(arg == "--noconsole") {
346 g_config->console_enabled = false;
347 } else if(arg == "--disable-sfx") {
348 g_config->sound_enabled = false;
349 } else if(arg == "--disable-music") {
350 g_config->music_enabled = false;
351 } else if(arg == "--play-demo") {
353 print_usage(argv[0]);
354 throw std::runtime_error("Need to specify a demo filename");
356 g_config->start_demo = argv[++i];
357 } else if(arg == "--record-demo") {
359 print_usage(argv[0]);
360 throw std::runtime_error("Need to specify a demo filename");
362 g_config->record_demo = argv[++i];
363 } else if(arg == "--debug-scripts" || arg == "-s") {
364 g_config->enable_script_debugger = true;
365 } else if(arg[0] != '-') {
366 g_config->start_level = arg;
368 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
379 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
380 std::stringstream msg;
381 msg << "Couldn't initialize SDL: " << SDL_GetError();
382 throw std::runtime_error(msg.str());
387 SDL_EnableUNICODE(1);
389 // wait 100ms and clear SDL event queue because sometimes we have random
390 // joystick events in the queue on startup...
393 while(SDL_PollEvent(&dummy))
400 g_config->random_seed = systemRandom.srand(g_config->random_seed);
402 //const char *how = config->random_seed? ", user fixed.": ", from time().";
403 //log_info << "Using random seed " << config->random_seed << how << std::endl;
409 // FIXME: Add something here
413 context_pointer->init_renderer();
414 g_screen = SDL_GetVideoSurface();
416 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
420 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
422 const char* icon_fname = "images/engine/icons/supertux.xpm";
426 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
427 } catch (const std::runtime_error& err) {
429 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
432 SDL_WM_SetIcon(icon, 0);
433 SDL_FreeSurface(icon);
437 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
443 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
444 << " Window: " << g_config->window_size
445 << " Fullscreen: " << g_config->fullscreen_size
446 << " Area: " << g_config->aspect_size << std::endl;
452 sound_manager = new SoundManager();
454 sound_manager->enable_sound(g_config->sound_enabled);
455 sound_manager->enable_music(g_config->music_enabled);
461 if(sound_manager != NULL) {
462 delete sound_manager;
463 sound_manager = NULL;
468 Main::wait_for_event(float min_delay, float max_delay)
470 assert(min_delay <= max_delay);
472 Uint32 min = (Uint32) (min_delay * 1000);
473 Uint32 max = (Uint32) (max_delay * 1000);
475 Uint32 ticks = SDL_GetTicks();
476 while(SDL_GetTicks() - ticks < min) {
478 sound_manager->update();
483 while (SDL_PollEvent(&event))
487 bool running = false;
488 ticks = SDL_GetTicks();
490 while(SDL_PollEvent(&event)) {
493 g_screen_manager->quit();
496 case SDL_JOYBUTTONDOWN:
497 case SDL_MOUSEBUTTONDOWN:
501 if(SDL_GetTicks() - ticks >= (max - min))
503 sound_manager->update();
509 static Uint32 last_timelog_ticks = 0;
510 static const char* last_timelog_component = 0;
512 static inline void timelog(const char* component)
514 Uint32 current_ticks = SDL_GetTicks();
516 if(last_timelog_component != 0) {
517 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
520 last_timelog_ticks = current_ticks;
521 last_timelog_component = component;
524 static inline void timelog(const char* )
530 Main::run(int argc, char** argv)
536 if(pre_parse_commandline(argc, argv))
539 Console::instance = new Console();
540 init_physfs(argv[0]);
543 timelog("controller");
544 g_main_controller = new JoystickKeyboardController();
550 AddonManager::get_instance().load_addons();
552 timelog("tinygettext");
555 timelog("commandline");
556 if(parse_commandline(argc, argv))
563 DrawingContext context;
564 context_pointer = &context;
567 Console::instance->init_graphics();
569 timelog("scripting");
570 scripting::init_squirrel(g_config->enable_script_debugger);
572 timelog("resources");
573 Resources::load_shared();
577 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
579 g_screen_manager = new ScreenManager();
583 if(g_config->start_level != "") {
584 // we have a normal path specified at commandline, not a physfs path.
585 // So we simply mount that path here...
586 std::string dir = FileSystem::dirname(g_config->start_level);
587 log_debug << "Adding dir: " << dir << std::endl;
588 PHYSFS_addToSearchPath(dir.c_str(), true);
590 if(g_config->start_level.size() > 4 &&
591 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
592 g_screen_manager->push_screen(new worldmap::WorldMap(
593 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
595 std::auto_ptr<GameSession> session (
596 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
598 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
599 init_rand();//initialise generator with seed from session
601 if(g_config->start_demo != "")
602 session->play_demo(g_config->start_demo);
604 if(g_config->record_demo != "")
605 session->record_demo(g_config->record_demo);
606 g_screen_manager->push_screen(session.release());
609 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
612 g_screen_manager->run(context);
613 } catch(std::exception& e) {
614 log_fatal << "Unexpected exception: " << e.what() << std::endl;
617 log_fatal << "Unexpected exception" << std::endl;
621 delete g_screen_manager;
622 g_screen_manager = NULL;
624 Resources::unload_shared();
631 delete g_main_controller;
632 g_main_controller = NULL;
633 delete Console::instance;
634 Console::instance = NULL;
635 scripting::exit_squirrel();
636 delete texture_manager;
637 texture_manager = NULL;