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/>.
17 #include "supertux/main.hpp"
22 #include <SDL_image.h>
27 #include <tinygettext/log.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/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 = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
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 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
182 #ifdef ENABLE_BINRELOC
186 dir = br_find_data_dir(APPDATADIR);
191 datadir = APPDATADIR;
193 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
194 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
200 char** searchpath = PHYSFS_getSearchPath();
201 for(char** i = searchpath; *i != NULL; i++)
202 log_info << "[" << *i << "] is in the search path" << std::endl;
203 PHYSFS_freeList(searchpath);
207 Main::print_usage(const char* argv0)
209 std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
211 " -f, --fullscreen Run in fullscreen mode\n"
212 " -w, --window Run in window mode\n"
213 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
214 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
215 " -d, --default Reset video settings to default values\n"
216 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
217 " --disable-sfx Disable sound effects\n"
218 " --disable-music Disable music\n"
219 " -h, --help Show this help message and quit\n"
220 " -v, --version Show SuperTux version and quit\n"
221 " --console Enable ingame scripting console\n"
222 " --noconsole Disable ingame scripting console\n"
223 " --show-fps Display framerate in levels\n"
224 " --no-show-fps Do not display framerate in levels\n"
225 " --record-demo FILE LEVEL Record a demo to FILE\n"
226 " --play-demo FILE LEVEL Play a recorded demo\n"
227 " -s, --debug-scripts Enable script debugger.\n"
233 * Options that should be evaluated prior to any initializations at all go here
236 Main::pre_parse_commandline(int argc, char** argv)
238 for(int i = 1; i < argc; ++i) {
239 std::string arg = argv[i];
241 if(arg == "--version" || arg == "-v") {
242 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
245 if(arg == "--help" || arg == "-h") {
246 print_usage(argv[0]);
255 * Options that should be evaluated after config is read go here
258 Main::parse_commandline(int argc, char** argv)
260 for(int i = 1; i < argc; ++i) {
261 std::string arg = argv[i];
263 if(arg == "--fullscreen" || arg == "-f") {
264 g_config->use_fullscreen = true;
265 } else if(arg == "--default" || arg == "-d") {
266 g_config->use_fullscreen = false;
268 g_config->window_size = Size(800, 600);
269 g_config->fullscreen_size = Size(800, 600);
270 g_config->aspect_size = Size(0, 0); // auto detect
272 } else if(arg == "--window" || arg == "-w") {
273 g_config->use_fullscreen = false;
274 } else if(arg == "--geometry" || arg == "-g") {
278 print_usage(argv[0]);
279 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
284 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
286 print_usage(argv[0]);
287 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
291 g_config->window_size = Size(width, height);
292 g_config->fullscreen_size = Size(width, height);
295 } else if(arg == "--aspect" || arg == "-a") {
299 print_usage(argv[0]);
300 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
304 int aspect_width = 0;
305 int aspect_height = 0;
306 if (strcmp(argv[i], "auto") == 0)
311 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
313 print_usage(argv[0]);
314 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
318 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
320 // use aspect ratio to calculate logical resolution
321 if (aspect_ratio > 1) {
322 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
325 g_config->aspect_size = Size(600,
326 static_cast<int>(600 * 1/aspect_ratio + 0.5));
330 } else if(arg == "--renderer") {
334 print_usage(argv[0]);
335 throw std::runtime_error("Need to specify a renderer for renderer argument");
339 g_config->video = get_video_system(argv[i]);
341 } else if(arg == "--show-fps") {
342 g_config->show_fps = true;
343 } else if(arg == "--no-show-fps") {
344 g_config->show_fps = false;
345 } else if(arg == "--console") {
346 g_config->console_enabled = true;
347 } else if(arg == "--noconsole") {
348 g_config->console_enabled = false;
349 } else if(arg == "--disable-sfx") {
350 g_config->sound_enabled = false;
351 } else if(arg == "--disable-music") {
352 g_config->music_enabled = false;
353 } else if(arg == "--play-demo") {
355 print_usage(argv[0]);
356 throw std::runtime_error("Need to specify a demo filename");
358 g_config->start_demo = argv[++i];
359 } else if(arg == "--record-demo") {
361 print_usage(argv[0]);
362 throw std::runtime_error("Need to specify a demo filename");
364 g_config->record_demo = argv[++i];
365 } else if(arg == "--debug-scripts" || arg == "-s") {
366 g_config->enable_script_debugger = true;
367 } else if(arg[0] != '-') {
368 g_config->start_level = arg;
370 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
381 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
382 std::stringstream msg;
383 msg << "Couldn't initialize SDL: " << SDL_GetError();
384 throw std::runtime_error(msg.str());
389 SDL_EnableUNICODE(1);
391 // wait 100ms and clear SDL event queue because sometimes we have random
392 // joystick events in the queue on startup...
395 while(SDL_PollEvent(&dummy))
402 g_config->random_seed = systemRandom.srand(g_config->random_seed);
404 //const char *how = config->random_seed? ", user fixed.": ", from time().";
405 //log_info << "Using random seed " << config->random_seed << how << std::endl;
411 // FIXME: Add something here
415 context_pointer->init_renderer();
416 g_screen = SDL_GetVideoSurface();
418 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
422 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
424 const char* icon_fname = "images/engine/icons/supertux.xpm";
428 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
429 } catch (const std::runtime_error& err) {
431 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
434 SDL_WM_SetIcon(icon, 0);
435 SDL_FreeSurface(icon);
439 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
445 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
446 << " Window: " << g_config->window_size
447 << " Fullscreen: " << g_config->fullscreen_size
448 << " Area: " << g_config->aspect_size << std::endl;
454 sound_manager = new SoundManager();
456 sound_manager->enable_sound(g_config->sound_enabled);
457 sound_manager->enable_music(g_config->music_enabled);
463 if(sound_manager != NULL) {
464 delete sound_manager;
465 sound_manager = NULL;
470 Main::wait_for_event(float min_delay, float max_delay)
472 assert(min_delay <= max_delay);
474 Uint32 min = (Uint32) (min_delay * 1000);
475 Uint32 max = (Uint32) (max_delay * 1000);
477 Uint32 ticks = SDL_GetTicks();
478 while(SDL_GetTicks() - ticks < min) {
480 sound_manager->update();
485 while (SDL_PollEvent(&event))
489 bool running = false;
490 ticks = SDL_GetTicks();
492 while(SDL_PollEvent(&event)) {
495 g_screen_manager->quit();
498 case SDL_JOYBUTTONDOWN:
499 case SDL_MOUSEBUTTONDOWN:
503 if(SDL_GetTicks() - ticks >= (max - min))
505 sound_manager->update();
511 static Uint32 last_timelog_ticks = 0;
512 static const char* last_timelog_component = 0;
514 static inline void timelog(const char* component)
516 Uint32 current_ticks = SDL_GetTicks();
518 if(last_timelog_component != 0) {
519 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
522 last_timelog_ticks = current_ticks;
523 last_timelog_component = component;
526 static inline void timelog(const char* )
532 Main::main(int argc, char** argv)
538 if(pre_parse_commandline(argc, argv))
541 Console::instance = new Console();
542 init_physfs(argv[0]);
545 timelog("controller");
546 g_main_controller = new JoystickKeyboardController();
552 AddonManager::get_instance().load_addons();
554 timelog("tinygettext");
557 timelog("commandline");
558 if(parse_commandline(argc, argv))
565 DrawingContext context;
566 context_pointer = &context;
569 Console::instance->init_graphics();
571 timelog("scripting");
572 scripting::init_squirrel(g_config->enable_script_debugger);
574 timelog("resources");
575 Resources::load_shared();
579 g_screen_manager = new ScreenManager();
580 if(g_config->start_level != "") {
581 // we have a normal path specified at commandline, not a physfs path.
582 // So we simply mount that path here...
583 std::string dir = FileSystem::dirname(g_config->start_level);
584 log_debug << "Adding dir: " << dir << std::endl;
585 PHYSFS_addToSearchPath(dir.c_str(), true);
587 if(g_config->start_level.size() > 4 &&
588 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
590 g_screen_manager->push_screen(new worldmap::WorldMap(
591 FileSystem::basename(g_config->start_level)));
593 init_rand();//If level uses random eg. for
594 // rain particles before we do this:
595 std::auto_ptr<GameSession> session (
596 new GameSession(FileSystem::basename(g_config->start_level)));
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());
610 g_screen_manager->push_screen(new TitleScreen());
613 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
614 g_screen_manager->run(context);
615 } catch(std::exception& e) {
616 log_fatal << "Unexpected exception: " << e.what() << std::endl;
619 log_fatal << "Unexpected exception" << std::endl;
623 delete g_screen_manager;
624 g_screen_manager = NULL;
626 Resources::unload_shared();
633 delete g_main_controller;
634 g_main_controller = NULL;
635 delete Console::instance;
636 Console::instance = NULL;
637 scripting::exit_squirrel();
638 delete texture_manager;
639 texture_manager = NULL;